docs: modernize treatment of ns-resolution timestamps
[autoconf.git] / doc / autoconf.texi
blobb75b408b7e540ff3b87b7c863dc3e43402b53d4f
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
416 * Go Compiler::                 Likewise
418 Writing Tests
420 * Language Choice::             Selecting which language to use for testing
421 * Writing Test Programs::       Forging source files for compilers
422 * Running the Preprocessor::    Detecting preprocessor symbols
423 * Running the Compiler::        Detecting language or header features
424 * Running the Linker::          Detecting library features
425 * Runtime::                     Testing for runtime features
426 * Systemology::                 A zoology of operating systems
427 * Multiple Cases::              Tests for several possible values
429 Writing Test Programs
431 * Guidelines::                  General rules for writing test programs
432 * Test Functions::              Avoiding pitfalls in test programs
433 * Generating Sources::          Source program boilerplate
435 Results of Tests
437 * Defining Symbols::            Defining C preprocessor symbols
438 * Setting Output Variables::    Replacing variables in output files
439 * Special Chars in Variables::  Characters to beware of in variables
440 * Caching Results::             Speeding up subsequent @command{configure} runs
441 * Printing Messages::           Notifying @command{configure} users
443 Caching Results
445 * Cache Variable Names::        Shell variables used in caches
446 * Cache Files::                 Files @command{configure} uses for caching
447 * Cache Checkpointing::         Loading and saving the cache file
449 Programming in M4
451 * M4 Quotation::                Protecting macros from unwanted expansion
452 * Using autom4te::              The Autoconf executables backbone
453 * Programming in M4sugar::      Convenient pure M4 macros
454 * Debugging via autom4te::      Figuring out what M4 was doing
456 M4 Quotation
458 * Active Characters::           Characters that change the behavior of M4
459 * One Macro Call::              Quotation and one macro call
460 * Quoting and Parameters::      M4 vs. shell parameters
461 * Quotation and Nested Macros::  Macros calling macros
462 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
463 * Quadrigraphs::                Another way to escape special characters
464 * Balancing Parentheses::       Dealing with unbalanced parentheses
465 * Quotation Rule Of Thumb::     One parenthesis, one quote
467 Using @command{autom4te}
469 * autom4te Invocation::         A GNU M4 wrapper
470 * Customizing autom4te::        Customizing the Autoconf package
472 Programming in M4sugar
474 * Redefined M4 Macros::         M4 builtins changed in M4sugar
475 * Diagnostic Macros::           Diagnostic messages from M4sugar
476 * Diversion support::           Diversions in M4sugar
477 * Conditional constructs::      Conditions in M4
478 * Looping constructs::          Iteration in M4
479 * Evaluation Macros::           More quotation and evaluation control
480 * Text processing Macros::      String manipulation in M4
481 * Number processing Macros::    Arithmetic computation in M4
482 * Set manipulation Macros::     Set manipulation in M4
483 * Forbidden Patterns::          Catching unexpanded macros
485 Programming in M4sh
487 * Common Shell Constructs::     Portability layer for common shell constructs
488 * Polymorphic Variables::       Support for indirect variable names
489 * Initialization Macros::       Macros to establish a sane shell environment
490 * File Descriptor Macros::      File descriptor macros for input and output
492 Writing Autoconf Macros
494 * Macro Definitions::           Basic format of an Autoconf macro
495 * Macro Names::                 What to call your new macros
496 * Reporting Messages::          Notifying @command{autoconf} users
497 * Dependencies Between Macros::  What to do when macros depend on other macros
498 * Obsoleting Macros::           Warning about old ways of doing things
499 * Coding Style::                Writing Autoconf macros @`a la Autoconf
501 Dependencies Between Macros
503 * Prerequisite Macros::         Ensuring required information
504 * Suggested Ordering::          Warning about possible ordering problems
505 * One-Shot Macros::             Ensuring a macro is called only once
507 Portable Shell Programming
509 * Shellology::                  A zoology of shells
510 * Here-Documents::              Quirks and tricks
511 * File Descriptors::            FDs and redirections
512 * File System Conventions::     File names
513 * Shell Pattern Matching::      Pattern matching
514 * Shell Substitutions::         Variable and command expansions
515 * Assignments::                 Varying side effects of assignments
516 * Parentheses::                 Parentheses in shell scripts
517 * Slashes::                     Slashes in shell scripts
518 * Special Shell Variables::     Variables you should not change
519 * Shell Functions::             What to look out for if you use them
520 * Limitations of Builtins::     Portable use of not so portable /bin/sh
521 * Limitations of Usual Tools::  Portable use of portable tools
523 Portable Make Programming
525 * $< in Ordinary Make Rules::   $< in ordinary rules
526 * Failure in Make Rules::       Failing portably in rules
527 * Special Chars in Names::      Special Characters in Macro Names
528 * Backslash-Newline-Newline::   Empty last lines in macro definitions
529 * Backslash-Newline Comments::  Spanning comments across line boundaries
530 * Long Lines in Makefiles::     Line length limitations
531 * Macros and Submakes::         @code{make macro=value} and submakes
532 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
533 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
534 * Parallel Make::               Parallel @command{make} quirks
535 * Comments in Make Rules::      Other problems with Make comments
536 * Newlines in Make Rules::      Using literal newlines in rules
537 * Comments in Make Macros::     Other problems with Make comments in macros
538 * Trailing whitespace in Make Macros::  Macro substitution problems
539 * Command-line Macros and whitespace::  Whitespace trimming of values
540 * obj/ and Make::               Don't name a subdirectory @file{obj}
541 * make -k Status::              Exit status of @samp{make -k}
542 * VPATH and Make::              @code{VPATH} woes
543 * Single Suffix Rules::         Single suffix rules and separated dependencies
544 * Timestamps and Make::         Subsecond timestamp resolution
546 @code{VPATH} and Make
548 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
549 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
550 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
551 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
552 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
553 * Make Target Lookup::          More details about @code{VPATH} lookup
555 Portable C and C++ Programming
557 * Varieties of Unportability::  How to make your programs unportable
558 * Integer Overflow::            When integers get too large
559 * Preprocessor Arithmetic::     @code{#if} expression problems
560 * Null Pointers::               Properties of null pointers
561 * Buffer Overruns::             Subscript errors and the like
562 * Volatile Objects::            @code{volatile} and signals
563 * Floating Point Portability::  Portable floating-point arithmetic
564 * Exiting Portably::            Exiting and the exit status
566 Integer Overflow
568 * Integer Overflow Basics::     Why integer overflow is a problem
569 * Signed Overflow Examples::    Examples of code assuming wraparound
570 * Optimization and Wraparound::  Optimizations that break uses of wraparound
571 * Signed Overflow Advice::      Practical advice for signed overflow issues
572 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
574 Manual Configuration
576 * Specifying Target Triplets::  Specifying target triplets
577 * Canonicalizing::              Getting the canonical system type
578 * Using System Type::           What to do with the system type
580 Site Configuration
582 * Help Formatting::             Customizing @samp{configure --help}
583 * External Software::           Working with other optional software
584 * Package Options::             Selecting optional features
585 * Pretty Help Strings::         Formatting help string
586 * Option Checking::             Controlling checking of @command{configure} options
587 * Site Details::                Configuring site details
588 * Transforming Names::          Changing program names when installing
589 * Site Defaults::               Giving @command{configure} local defaults
591 Transforming Program Names When Installing
593 * Transformation Options::      @command{configure} options to transform names
594 * Transformation Examples::     Sample uses of transforming names
595 * Transformation Rules::        Makefile uses of transforming names
597 Running @command{configure} Scripts
599 * Basic Installation::          Instructions for typical cases
600 * Compilers and Options::       Selecting compilers and optimization
601 * Multiple Architectures::      Compiling for multiple architectures at once
602 * Installation Names::          Installing in different directories
603 * Optional Features::           Selecting optional features
604 * Particular Systems::          Particular systems
605 * System Type::                 Specifying the system type
606 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
607 * Defining Variables::          Specifying the compiler etc.
608 * configure Invocation::        Changing how @command{configure} runs
610 Obsolete Constructs
612 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
613 * acconfig Header::             Additional entries in @file{config.h.in}
614 * autoupdate Invocation::       Automatic update of @file{configure.ac}
615 * Obsolete Macros::             Backward compatibility macros
616 * Autoconf 1::                  Tips for upgrading your files
617 * Autoconf 2.13::               Some fresher tips
619 Upgrading From Version 1
621 * Changed File Names::          Files you might rename
622 * Changed Makefiles::           New things to put in @file{Makefile.in}
623 * Changed Macros::              Macro calls you might replace
624 * Changed Results::             Changes in how to check test results
625 * Changed Macro Writing::       Better ways to write your own macros
627 Upgrading From Version 2.13
629 * Changed Quotation::           Broken code which used to work
630 * New Macros::                  Interaction with foreign macros
631 * Hosts and Cross-Compilation::  Bugward compatibility kludges
632 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
633 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
635 Generating Test Suites with Autotest
637 * Using an Autotest Test Suite::  Autotest and the user
638 * Writing Testsuites::          Autotest macros
639 * testsuite Invocation::        Running @command{testsuite} scripts
640 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
642 Using an Autotest Test Suite
644 * testsuite Scripts::           The concepts of Autotest
645 * Autotest Logs::               Their contents
647 Frequent Autoconf Questions, with answers
649 * Distributing::                Distributing @command{configure} scripts
650 * Why GNU M4::                  Why not use the standard M4?
651 * Bootstrapping::               Autoconf and GNU M4 require each other?
652 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
653 * Defining Directories::        Passing @code{datadir} to program
654 * Autom4te Cache::              What is it?  Can I remove it?
655 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
656 * Expanded Before Required::    Expanded Before Required
657 * Debugging::                   Debugging @command{configure} scripts
659 History of Autoconf
661 * Genesis::                     Prehistory and naming of @command{configure}
662 * Exodus::                      The plagues of M4 and Perl
663 * Leviticus::                   The priestly code of portability arrives
664 * Numbers::                     Growth and contributors
665 * Deuteronomy::                 Approaching the promises of easy configuration
667 Indices
669 * Environment Variable Index::  Index of environment variables used
670 * Output Variable Index::       Index of variables set in output files
671 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
672 * Cache Variable Index::        Index of documented cache variables
673 * Autoconf Macro Index::        Index of Autoconf macros
674 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
675 * Autotest Macro Index::        Index of Autotest macros
676 * Program & Function Index::    Index of those with portability problems
677 * Concept Index::               General index
679 @end detailmenu
680 @end menu
682 @c ============================================================= Introduction.
684 @node Introduction
685 @chapter Introduction
686 @cindex Introduction
688 @flushright
689 A physicist, an engineer, and a computer scientist were discussing the
690 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
691 early in the Creation, God made Light; and you know, Maxwell's
692 equations, the dual nature of electromagnetic waves, the relativistic
693 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
694 before making Light, God split the Chaos into Land and Water; it takes a
695 hell of an engineer to handle that big amount of mud, and orderly
696 separation of solids from liquids@enddots{}'' The computer scientist
697 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
699 ---Anonymous
700 @end flushright
701 @c (via Franc,ois Pinard)
703 Autoconf is a tool for producing shell scripts that automatically
704 configure software source code packages to adapt to many kinds of
705 Posix-like systems.  The configuration scripts produced by Autoconf
706 are independent of Autoconf when they are run, so their users do not
707 need to have Autoconf.
709 The configuration scripts produced by Autoconf require no manual user
710 intervention when run; they do not normally even need an argument
711 specifying the system type.  Instead, they individually test for the
712 presence of each feature that the software package they are for might need.
713 (Before each check, they print a one-line message stating what they are
714 checking for, so the user doesn't get too bored while waiting for the
715 script to finish.)  As a result, they deal well with systems that are
716 hybrids or customized from the more common Posix variants.  There is
717 no need to maintain files that list the features supported by each
718 release of each variant of Posix.
720 For each software package that Autoconf is used with, it creates a
721 configuration script from a template file that lists the system features
722 that the package needs or can use.  After the shell code to recognize
723 and respond to a system feature has been written, Autoconf allows it to
724 be shared by many software packages that can use (or need) that feature.
725 If it later turns out that the shell code needs adjustment for some
726 reason, it needs to be changed in only one place; all of the
727 configuration scripts can be regenerated automatically to take advantage
728 of the updated code.
730 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
731 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
732 Those who do not understand Autoconf are condemned to reinvent it, poorly.
733 The primary goal of Autoconf is making the @emph{user's} life easier;
734 making the @emph{maintainer's} life easier is only a secondary goal.
735 Put another way, the primary goal is not to make the generation of
736 @file{configure} automatic for package maintainers (although patches
737 along that front are welcome, since package maintainers form the user
738 base of Autoconf); rather, the goal is to make @file{configure}
739 painless, portable, and predictable for the end user of each
740 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
741 successful at its goal --- most complaints to the Autoconf list are
742 about difficulties in writing Autoconf input, and not in the behavior of
743 the resulting @file{configure}.  Even packages that don't use Autoconf
744 will generally provide a @file{configure} script, and the most common
745 complaint about these alternative home-grown scripts is that they fail
746 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
747 standards, The GNU Coding Standards}) that users
748 have come to expect from Autoconf-generated @file{configure} scripts.
750 The Metaconfig package is similar in purpose to Autoconf, but the
751 scripts it produces require manual user intervention, which is quite
752 inconvenient when configuring large source trees.  Unlike Metaconfig
753 scripts, Autoconf scripts can support cross-compiling, if some care is
754 taken in writing them.
756 Autoconf does not solve all problems related to making portable
757 software packages---for a more complete solution, it should be used in
758 concert with other GNU build tools like Automake and
759 Libtool.  These other tools take on jobs like the creation of a
760 portable, recursive makefile with all of the standard targets,
761 linking of shared libraries, and so on.  @xref{The GNU Build System},
762 for more information.
764 Autoconf imposes some restrictions on the names of macros used with
765 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
767 Autoconf requires GNU M4 version 1.4.6 or later in order to
768 generate the scripts.  It uses features that some versions of M4,
769 including GNU M4 1.3, do not have.  Autoconf works better
770 with GNU M4 version 1.4.14 or later, though this is not
771 required.
773 @xref{Autoconf 1}, for information about upgrading from version 1.
774 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
775 for answers to some common questions about Autoconf.
777 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
778 Autoconf web page} for up-to-date information, details on the mailing
779 lists, pointers to a list of known bugs, etc.
781 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
782 list}.  Past suggestions are
783 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
785 Mail bug reports to @email{bug-autoconf@@gnu.org, the
786 Autoconf Bugs mailing list}.  Past bug reports are
787 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
789 If possible, first check that your bug is
790 not already solved in current development versions, and that it has not
791 been reported yet.  Be sure to include all the needed information and a
792 short @file{configure.ac} that demonstrates the problem.
794 Autoconf's development tree is accessible via @command{git}; see the
795 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
796 Summary} for details, or view
797 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
798 repository}.  Anonymous CVS access is also available, see
799 @file{README} for more details.  Patches relative to the
800 current @command{git} version can be sent for review to the
801 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
802 discussion on prior patches
803 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
804 archived}; and all commits are posted in the read-only
805 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
806 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
807 archived}.
809 Because of its mission, the Autoconf package itself
810 includes only a set of often-used
811 macros that have already demonstrated their usefulness.  Nevertheless,
812 if you wish to share your macros, or find existing ones, see the
813 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
814 Archive}, which is kindly run by @email{simons@@cryp.to,
815 Peter Simons}.
818 @c ================================================= The GNU Build System
820 @node The GNU Build System
821 @chapter The GNU Build System
822 @cindex GNU build system
824 Autoconf solves an important problem---reliable discovery of
825 system-specific build and runtime information---but this is only one
826 piece of the puzzle for the development of portable software.  To this
827 end, the GNU project has developed a suite of integrated
828 utilities to finish the job Autoconf started: the GNU build
829 system, whose most important components are Autoconf, Automake, and
830 Libtool.  In this chapter, we introduce you to those tools, point you
831 to sources of more information, and try to convince you to use the
832 entire GNU build system for your software.
834 @menu
835 * Automake::                    Escaping makefile hell
836 * Gnulib::                      The GNU portability library
837 * Libtool::                     Building libraries portably
838 * Pointers::                    More info on the GNU build system
839 @end menu
841 @node Automake
842 @section Automake
844 The ubiquity of @command{make} means that a makefile is almost the
845 only viable way to distribute automatic build rules for software, but
846 one quickly runs into its numerous limitations.  Its lack of
847 support for automatic dependency tracking, recursive builds in
848 subdirectories, reliable timestamps (e.g., for network file systems), and
849 so on, mean that developers must painfully (and often incorrectly)
850 reinvent the wheel for each project.  Portability is non-trivial, thanks
851 to the quirks of @command{make} on many systems.  On top of all this is the
852 manual labor required to implement the many standard targets that users
853 have come to expect (@code{make install}, @code{make distclean},
854 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
855 you also have to insert repetitive code in your @file{Makefile.in} to
856 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
857 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
858 @cindex Automake
860 Automake allows you to specify your build needs in a @file{Makefile.am}
861 file with a vastly simpler and more powerful syntax than that of a plain
862 makefile, and then generates a portable @file{Makefile.in} for
863 use with Autoconf.  For example, the @file{Makefile.am} to build and
864 install a simple ``Hello world'' program might look like:
866 @example
867 bin_PROGRAMS = hello
868 hello_SOURCES = hello.c
869 @end example
871 @noindent
872 The resulting @file{Makefile.in} (~400 lines) automatically supports all
873 the standard targets, the substitutions provided by Autoconf, automatic
874 dependency tracking, @code{VPATH} building, and so on.  @command{make}
875 builds the @code{hello} program, and @code{make install} installs it
876 in @file{/usr/local/bin} (or whatever prefix was given to
877 @command{configure}, if not @file{/usr/local}).
879 The benefits of Automake increase for larger packages (especially ones
880 with subdirectories), but even for small programs the added convenience
881 and portability can be substantial.  And that's not all@enddots{}
883 @node Gnulib
884 @section Gnulib
886 GNU software has a well-deserved reputation for running on
887 many different types of systems.  While our primary goal is to write
888 software for the GNU system, many users and developers have
889 been introduced to us through the systems that they were already using.
891 @cindex Gnulib
892 Gnulib is a central location for common GNU code, intended to
893 be shared among free software packages.  Its components are typically
894 shared at the source level, rather than being a library that gets built,
895 installed, and linked against.  The idea is to copy files from Gnulib
896 into your own source tree.  There is no distribution tarball; developers
897 should just grab source modules from the repository.  The source files
898 are available online, under various licenses, mostly GNU
899 GPL or GNU LGPL.
901 Gnulib modules typically contain C source code along with Autoconf
902 macros used to configure the source code.  For example, the Gnulib
903 @code{stdbool} module implements a @file{stdbool.h} header that nearly
904 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
905 This module contains a source file for the replacement header, along
906 with an Autoconf macro that arranges to use the replacement header on
907 old-fashioned systems.
909 @node Libtool
910 @section Libtool
912 Often, one wants to build not only programs, but libraries, so that
913 other programs can benefit from the fruits of your labor.  Ideally, one
914 would like to produce @emph{shared} (dynamically linked) libraries,
915 which can be used by multiple programs without duplication on disk or in
916 memory and can be updated independently of the linked programs.
917 Producing shared libraries portably, however, is the stuff of
918 nightmares---each system has its own incompatible tools, compiler flags,
919 and magic incantations.  Fortunately, GNU provides a solution:
920 @dfn{Libtool}.
921 @cindex Libtool
923 Libtool handles all the requirements of building shared libraries for
924 you, and at this time seems to be the @emph{only} way to do so with any
925 portability.  It also handles many other headaches, such as: the
926 interaction of Make rules with the variable suffixes of
927 shared libraries, linking reliably with shared libraries before they are
928 installed by the superuser, and supplying a consistent versioning system
929 (so that different versions of a library can be installed or upgraded
930 without breaking binary compatibility).  Although Libtool, like
931 Autoconf, can be used without Automake, it is most simply utilized in
932 conjunction with Automake---there, Libtool is used automatically
933 whenever shared libraries are needed, and you need not know its syntax.
935 @node Pointers
936 @section Pointers
938 Developers who are used to the simplicity of @command{make} for small
939 projects on a single system might be daunted at the prospect of
940 learning to use Automake and Autoconf.  As your software is
941 distributed to more and more users, however, you otherwise
942 quickly find yourself putting lots of effort into reinventing the
943 services that the GNU build tools provide, and making the
944 same mistakes that they once made and overcame.  (Besides, since
945 you're already learning Autoconf, Automake is a piece of cake.)
947 There are a number of places that you can go to for more information on
948 the GNU build tools.
950 @itemize @minus
952 @item Web
954 The project home pages for
955 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
956 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
957 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
958 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
960 @item Automake Manual
962 @xref{Top, , Automake, automake, GNU Automake}, for more
963 information on Automake.
965 @item Books
967 The book @cite{GNU Autoconf, Automake and
968 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
969 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
970 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
971 build environment.  You can also find
972 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
974 @end itemize
976 @c ================================================= Making configure Scripts.
978 @node Making configure Scripts
979 @chapter Making @command{configure} Scripts
980 @cindex @file{aclocal.m4}
981 @cindex @command{configure}
983 The configuration scripts that Autoconf produces are by convention
984 called @command{configure}.  When run, @command{configure} creates several
985 files, replacing configuration parameters in them with appropriate
986 values.  The files that @command{configure} creates are:
988 @itemize @minus
989 @item
990 one or more @file{Makefile} files, usually one in each subdirectory of the
991 package (@pxref{Makefile Substitutions});
993 @item
994 optionally, a C header file, the name of which is configurable,
995 containing @code{#define} directives (@pxref{Configuration Headers});
997 @item
998 a shell script called @file{config.status} that, when run, recreates
999 the files listed above (@pxref{config.status Invocation});
1001 @item
1002 an optional shell script normally called @file{config.cache}
1003 (created when using @samp{configure --config-cache}) that
1004 saves the results of running many of the tests (@pxref{Cache Files});
1006 @item
1007 a file called @file{config.log} containing any messages produced by
1008 compilers, to help debugging if @command{configure} makes a mistake.
1009 @end itemize
1011 @cindex @file{configure.in}
1012 @cindex @file{configure.ac}
1013 To create a @command{configure} script with Autoconf, you need to write an
1014 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
1015 @command{autoconf} on it.  If you write your own feature tests to
1016 supplement those that come with Autoconf, you might also write files
1017 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1018 file to contain @code{#define} directives, you might also run
1019 @command{autoheader}, and you can distribute the generated file
1020 @file{config.h.in} with the package.
1022 Here is a diagram showing how the files that can be used in
1023 configuration are produced.  Programs that are executed are suffixed by
1024 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1025 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1026 macro files (by reading @file{autoconf.m4}).
1028 @noindent
1029 Files used in preparing a software package for distribution, when using
1030 just Autoconf:
1031 @example
1032 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1034 @group
1035 configure.ac --.
1036                |   .------> autoconf* -----> configure
1037 [aclocal.m4] --+---+
1038                |   `-----> [autoheader*] --> [config.h.in]
1039 [acsite.m4] ---'
1040 @end group
1042 Makefile.in
1043 @end example
1045 @noindent
1046 Additionally, if you use Automake, the following additional productions
1047 come into play:
1049 @example
1050 @group
1051 [acinclude.m4] --.
1052                  |
1053 [local macros] --+--> aclocal* --> aclocal.m4
1054                  |
1055 configure.ac ----'
1056 @end group
1058 @group
1059 configure.ac --.
1060                +--> automake* --> Makefile.in
1061 Makefile.am ---'
1062 @end group
1063 @end example
1065 @noindent
1066 Files used in configuring a software package:
1067 @example
1068 @group
1069                        .-------------> [config.cache]
1070 configure* ------------+-------------> config.log
1071                        |
1072 [config.h.in] -.       v            .-> [config.h] -.
1073                +--> config.status* -+               +--> make*
1074 Makefile.in ---'                    `-> Makefile ---'
1075 @end group
1076 @end example
1078 @menu
1079 * Writing Autoconf Input::      What to put in an Autoconf input file
1080 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1081 * ifnames Invocation::          Listing the conditionals in source code
1082 * autoconf Invocation::         How to create configuration scripts
1083 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1084 @end menu
1086 @node Writing Autoconf Input
1087 @section Writing @file{configure.ac}
1089 To produce a @command{configure} script for a software package, create a
1090 file called @file{configure.ac} that contains invocations of the
1091 Autoconf macros that test the system features your package needs or can
1092 use.  Autoconf macros already exist to check for many features; see
1093 @ref{Existing Tests}, for their descriptions.  For most other features,
1094 you can use Autoconf template macros to produce custom checks; see
1095 @ref{Writing Tests}, for information about them.  For especially tricky
1096 or specialized features, @file{configure.ac} might need to contain some
1097 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1098 Programming}.  The @command{autoscan} program can give you a good start
1099 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1100 information).
1102 Previous versions of Autoconf promoted the name @file{configure.in},
1103 which is somewhat ambiguous (the tool needed to process this file is not
1104 described by its extension), and introduces a slight confusion with
1105 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1106 processed by @command{configure}'').  Using @file{configure.ac} is now
1107 preferred.
1109 @menu
1110 * Shell Script Compiler::       Autoconf as solution of a problem
1111 * Autoconf Language::           Programming in Autoconf
1112 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1113 @end menu
1115 @node Shell Script Compiler
1116 @subsection A Shell Script Compiler
1118 Just as for any other computer language, in order to properly program
1119 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1120 the language tries to address and @emph{how} it does so.
1122 The problem Autoconf addresses is that the world is a mess.  After all,
1123 you are using Autoconf in order to have your package compile easily on
1124 all sorts of different systems, some of them being extremely hostile.
1125 Autoconf itself bears the price for these differences: @command{configure}
1126 must run on all those systems, and thus @command{configure} must limit itself
1127 to their lowest common denominator of features.
1129 Naturally, you might then think of shell scripts; who needs
1130 @command{autoconf}?  A set of properly written shell functions is enough to
1131 make it easy to write @command{configure} scripts by hand.  Sigh!
1132 Unfortunately, even in 2008, where shells without any function support are
1133 far and few between, there are pitfalls to avoid when making use of them.
1134 Also, finding a Bourne shell that accepts shell functions is not trivial,
1135 even though there is almost always one on interesting porting targets.
1137 So, what is really needed is some kind of compiler, @command{autoconf},
1138 that takes an Autoconf program, @file{configure.ac}, and transforms it
1139 into a portable shell script, @command{configure}.
1141 How does @command{autoconf} perform this task?
1143 There are two obvious possibilities: creating a brand new language or
1144 extending an existing one.  The former option is attractive: all
1145 sorts of optimizations could easily be implemented in the compiler and
1146 many rigorous checks could be performed on the Autoconf program
1147 (e.g., rejecting any non-portable construct).  Alternatively, you can
1148 extend an existing language, such as the @code{sh} (Bourne shell)
1149 language.
1151 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1152 therefore most convenient to implement @command{autoconf} as a macro
1153 expander: a program that repeatedly performs @dfn{macro expansions} on
1154 text input, replacing macro calls with macro bodies and producing a pure
1155 @code{sh} script in the end.  Instead of implementing a dedicated
1156 Autoconf macro expander, it is natural to use an existing
1157 general-purpose macro language, such as M4, and implement the extensions
1158 as a set of M4 macros.
1161 @node Autoconf Language
1162 @subsection The Autoconf Language
1163 @cindex quotation
1165 The Autoconf language differs from many other computer
1166 languages because it treats actual code the same as plain text.  Whereas
1167 in C, for instance, data and instructions have different syntactic
1168 status, in Autoconf their status is rigorously the same.  Therefore, we
1169 need a means to distinguish literal strings from text to be expanded:
1170 quotation.
1172 When calling macros that take arguments, there must not be any white
1173 space between the macro name and the open parenthesis.
1175 @example
1176 AC_INIT ([oops], [1.0]) # incorrect
1177 AC_INIT([hello], [1.0]) # good
1178 @end example
1180 Arguments should
1181 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1182 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1183 unless they are quoted.  You should always quote an argument that
1184 might contain a macro name, comma, parenthesis, or a leading blank or
1185 newline.  This rule applies recursively for every macro
1186 call, including macros called from other macros.  For more details on
1187 quoting rules, see @ref{Programming in M4}.
1189 For instance:
1191 @example
1192 AC_CHECK_HEADER([stdio.h],
1193                 [AC_DEFINE([HAVE_STDIO_H], [1],
1194                    [Define to 1 if you have <stdio.h>.])],
1195                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1196 @end example
1198 @noindent
1199 is quoted properly.  You may safely simplify its quotation to:
1201 @example
1202 AC_CHECK_HEADER([stdio.h],
1203                 [AC_DEFINE([HAVE_STDIO_H], 1,
1204                    [Define to 1 if you have <stdio.h>.])],
1205                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1206 @end example
1208 @noindent
1209 because @samp{1} cannot contain a macro call.  Here, the argument of
1210 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1211 interpreted as an argument separator.  Also, the second and third arguments
1212 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1213 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1214 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1215 if you unwisely defined a macro with a name like @samp{Define} or
1216 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1217 would keep the quotes, but many Autoconf users find such precautions
1218 annoying, and would rewrite the example as follows:
1220 @example
1221 AC_CHECK_HEADER(stdio.h,
1222                 [AC_DEFINE(HAVE_STDIO_H, 1,
1223                    [Define to 1 if you have <stdio.h>.])],
1224                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1225 @end example
1227 @noindent
1228 This is safe, so long as you adopt good naming conventions and do not
1229 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1230 @samp{h}.  Though it is also safe here to omit the quotes around
1231 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1232 message strings are more likely to inadvertently contain commas.
1234 The following example is wrong and dangerous, as it is underquoted:
1236 @example
1237 AC_CHECK_HEADER(stdio.h,
1238                 AC_DEFINE(HAVE_STDIO_H, 1,
1239                    Define to 1 if you have <stdio.h>.),
1240                 AC_MSG_ERROR([sorry, can't do anything for you]))
1241 @end example
1243 In other cases, you may have to use text that also resembles a macro
1244 call.  You must quote that text even when it is not passed as a macro
1245 argument.  For example, these two approaches in @file{configure.ac}
1246 (quoting just the potential problems, or quoting the entire line) will
1247 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1249 @example
1250 echo "Hard rock was here!  --[AC_DC]"
1251 [echo "Hard rock was here!  --AC_DC"]
1252 @end example
1254 @noindent
1255 which results in this text in @file{configure}:
1257 @example
1258 echo "Hard rock was here!  --AC_DC"
1259 echo "Hard rock was here!  --AC_DC"
1260 @end example
1262 @noindent
1263 When you use the same text in a macro argument, you must therefore have
1264 an extra quotation level (since one is stripped away by the macro
1265 substitution).  In general, then, it is a good idea to @emph{use double
1266 quoting for all literal string arguments}, either around just the
1267 problematic portions, or over the entire argument:
1269 @example
1270 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1271 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1272 @end example
1274 However, the above example triggers a warning about a possibly
1275 unexpanded macro when running @command{autoconf}, because it collides
1276 with the namespace of macros reserved for the Autoconf language.  To be
1277 really safe, you can use additional escaping (either a quadrigraph, or
1278 creative shell constructs) to silence that particular warning:
1280 @example
1281 echo "Hard rock was here!  --AC""_DC"
1282 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1283 @end example
1285 You are now able to understand one of the constructs of Autoconf that
1286 has been continually misunderstood@enddots{}  The rule of thumb is that
1287 @emph{whenever you expect macro expansion, expect quote expansion};
1288 i.e., expect one level of quotes to be lost.  For instance:
1290 @example
1291 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1292  [AC_MSG_ERROR([you lose])])
1293 @end example
1295 @noindent
1296 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1297 @samp{char b[10];} and is expanded once, which results in
1298 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1299 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1300 in Autoconf's past to
1301 address this issue via the M4 @code{changequote} primitive, but do not
1302 use it!)  Let's take a closer look: the author meant the first argument
1303 to be understood as a literal, and therefore it must be quoted twice;
1304 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1305 once so that it is only expanded after the rest of the body of
1306 @code{AC_COMPILE_IFELSE} is in place:
1308 @example
1309 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1310   [AC_MSG_ERROR([you lose])])
1311 @end example
1313 @noindent
1314 Voil@`a, you actually produce @samp{char b[10];} this time!
1316 On the other hand, descriptions (e.g., the last parameter of
1317 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1318 are subject to line breaking, for example---and should not be double quoted.
1319 Even if these descriptions are short and are not actually broken, double
1320 quoting them yields weird results.
1322 Some macros take optional arguments, which this documentation represents
1323 as @ovar{arg} (not to be confused with the quote characters).  You may
1324 just leave them empty, or use @samp{[]} to make the emptiness of the
1325 argument explicit, or you may simply omit the trailing commas.  The
1326 three lines below are equivalent:
1328 @example
1329 AC_CHECK_HEADERS([stdio.h], [], [], [])
1330 AC_CHECK_HEADERS([stdio.h],,,)
1331 AC_CHECK_HEADERS([stdio.h])
1332 @end example
1334 It is best to put each macro call on its own line in
1335 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1336 rely on the newline after the macro call to terminate the commands.
1337 This approach makes the generated @command{configure} script a little
1338 easier to read by not inserting lots of blank lines.  It is generally
1339 safe to set shell variables on the same line as a macro call, because
1340 the shell allows assignments without intervening newlines.
1342 You can include comments in @file{configure.ac} files by starting them
1343 with the @samp{#}.  For example, it is helpful to begin
1344 @file{configure.ac} files with a line like this:
1346 @example
1347 # Process this file with autoconf to produce a configure script.
1348 @end example
1350 @node Autoconf Input Layout
1351 @subsection Standard @file{configure.ac} Layout
1353 The order in which @file{configure.ac} calls the Autoconf macros is not
1354 important, with a few exceptions.  Every @file{configure.ac} must
1355 contain a call to @code{AC_INIT} before the checks, and a call to
1356 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1357 rely on other macros having been called first, because they check
1358 previously set values of some variables to decide what to do.  These
1359 macros are noted in the individual descriptions (@pxref{Existing
1360 Tests}), and they also warn you when @command{configure} is created if they
1361 are called out of order.
1363 To encourage consistency, here is a suggested order for calling the
1364 Autoconf macros.  Generally speaking, the things near the end of this
1365 list are those that could depend on things earlier in it.  For example,
1366 library functions could be affected by types and libraries.
1368 @display
1369 @group
1370 Autoconf requirements
1371 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1372 information on the package
1373 checks for programs
1374 checks for libraries
1375 checks for header files
1376 checks for types
1377 checks for structures
1378 checks for compiler characteristics
1379 checks for library functions
1380 checks for system services
1381 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1382 @code{AC_OUTPUT}
1383 @end group
1384 @end display
1387 @node autoscan Invocation
1388 @section Using @command{autoscan} to Create @file{configure.ac}
1389 @cindex @command{autoscan}
1391 The @command{autoscan} program can help you create and/or maintain a
1392 @file{configure.ac} file for a software package.  @command{autoscan}
1393 examines source files in the directory tree rooted at a directory given
1394 as a command line argument, or the current directory if none is given.
1395 It searches the source files for common portability problems and creates
1396 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1397 for that package, and checks a possibly existing @file{configure.ac} for
1398 completeness.
1400 When using @command{autoscan} to create a @file{configure.ac}, you
1401 should manually examine @file{configure.scan} before renaming it to
1402 @file{configure.ac}; it probably needs some adjustments.
1403 Occasionally, @command{autoscan} outputs a macro in the wrong order
1404 relative to another macro, so that @command{autoconf} produces a warning;
1405 you need to move such macros manually.  Also, if you want the package to
1406 use a configuration header file, you must add a call to
1407 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1408 also have to change or add some @code{#if} directives to your program in
1409 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1410 information about a program that can help with that job).
1412 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1413 consider adding its suggestions.  The file @file{autoscan.log}
1414 contains detailed information on why a macro is requested.
1416 @command{autoscan} uses several data files (installed along with Autoconf)
1417 to determine which macros to output when it finds particular symbols in
1418 a package's source files.  These data files all have the same format:
1419 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1420 output if that symbol is encountered.  Lines starting with @samp{#} are
1421 comments.
1423 @command{autoscan} accepts the following options:
1425 @table @option
1426 @item --help
1427 @itemx -h
1428 Print a summary of the command line options and exit.
1430 @item --version
1431 @itemx -V
1432 Print the version number of Autoconf and exit.
1434 @item --verbose
1435 @itemx -v
1436 Print the names of the files it examines and the potentially interesting
1437 symbols it finds in them.  This output can be voluminous.
1439 @item --debug
1440 @itemx -d
1441 Don't remove temporary files.
1443 @item --include=@var{dir}
1444 @itemx -I @var{dir}
1445 Append @var{dir} to the include path.  Multiple invocations accumulate.
1447 @item --prepend-include=@var{dir}
1448 @itemx -B @var{dir}
1449 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1450 @end table
1452 @node ifnames Invocation
1453 @section Using @command{ifnames} to List Conditionals
1454 @cindex @command{ifnames}
1456 @command{ifnames} can help you write @file{configure.ac} for a software
1457 package.  It prints the identifiers that the package already uses in C
1458 preprocessor conditionals.  If a package has already been set up to have
1459 some portability, @command{ifnames} can thus help you figure out what its
1460 @command{configure} needs to check for.  It may help fill in some gaps in a
1461 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1462 Invocation}).
1464 @command{ifnames} scans all of the C source files named on the command line
1465 (or the standard input, if none are given) and writes to the standard
1466 output a sorted list of all the identifiers that appear in those files
1467 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1468 directives.  It prints each identifier on a line, followed by a
1469 space-separated list of the files in which that identifier occurs.
1471 @noindent
1472 @command{ifnames} accepts the following options:
1474 @table @option
1475 @item --help
1476 @itemx -h
1477 Print a summary of the command line options and exit.
1479 @item --version
1480 @itemx -V
1481 Print the version number of Autoconf and exit.
1482 @end table
1484 @node autoconf Invocation
1485 @section Using @command{autoconf} to Create @command{configure}
1486 @cindex @command{autoconf}
1488 To create @command{configure} from @file{configure.ac}, run the
1489 @command{autoconf} program with no arguments.  @command{autoconf} processes
1490 @file{configure.ac} with the M4 macro processor, using the
1491 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1492 file instead of @file{configure.ac} and writes the configuration script
1493 to the standard output instead of to @command{configure}.  If you give
1494 @command{autoconf} the argument @option{-}, it reads from the standard
1495 input instead of @file{configure.ac} and writes the configuration script
1496 to the standard output.
1498 The Autoconf macros are defined in several files.  Some of the files are
1499 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1500 looks for the optional file @file{acsite.m4} in the directory that
1501 contains the distributed Autoconf macro files, and for the optional file
1502 @file{aclocal.m4} in the current directory.  Those files can contain
1503 your site's or the package's own Autoconf macro definitions
1504 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1505 defined in more than one of the files that @command{autoconf} reads, the
1506 last definition it reads overrides the earlier ones.
1508 @command{autoconf} accepts the following options:
1510 @table @option
1511 @item --help
1512 @itemx -h
1513 Print a summary of the command line options and exit.
1515 @item --version
1516 @itemx -V
1517 Print the version number of Autoconf and exit.
1519 @item --verbose
1520 @itemx -v
1521 Report processing steps.
1523 @item --debug
1524 @itemx -d
1525 Don't remove the temporary files.
1527 @item --force
1528 @itemx -f
1529 Remake @file{configure} even if newer than its input files.
1531 @item --include=@var{dir}
1532 @itemx -I @var{dir}
1533 Append @var{dir} to the include path.  Multiple invocations accumulate.
1535 @item --prepend-include=@var{dir}
1536 @itemx -B @var{dir}
1537 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1539 @item --output=@var{file}
1540 @itemx -o @var{file}
1541 Save output (script or trace) to @var{file}.  The file @option{-} stands
1542 for the standard output.
1544 @item --warnings=@var{category}
1545 @itemx -W @var{category}
1546 @evindex WARNINGS
1547 Report the warnings related to @var{category} (which can actually be a
1548 comma separated list).  @xref{Reporting Messages}, macro
1549 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1550 values include:
1552 @table @samp
1553 @item all
1554 report all the warnings
1556 @item none
1557 report none
1559 @item error
1560 treats warnings as errors
1562 @item no-@var{category}
1563 disable warnings falling into @var{category}
1564 @end table
1566 Warnings about @samp{syntax} are enabled by default, and the environment
1567 variable @env{WARNINGS}, a comma separated list of categories, is
1568 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1569 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1570 disable the defaults and @env{WARNINGS}, and then
1571 enable warnings about obsolete constructs, use @option{-W
1572 none,obsolete}.
1574 @cindex Back trace
1575 @cindex Macro invocation stack
1576 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1577 displays a back trace for errors, but not for warnings; if you want
1578 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1579 examples.
1581 @item --trace=@var{macro}[:@var{format}]
1582 @itemx -t @var{macro}[:@var{format}]
1583 Do not create the @command{configure} script, but list the calls to
1584 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1585 arguments can be used to list several macros.  Multiple @option{--trace}
1586 arguments for a single macro are not cumulative; instead, you should
1587 just make @var{format} as long as needed.
1589 The @var{format} is a regular string, with newlines if desired, and
1590 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1591 @ref{autom4te Invocation}, for details on the @var{format}.
1593 @item --initialization
1594 @itemx -i
1595 By default, @option{--trace} does not trace the initialization of the
1596 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1597 results in a noticeable speedup, but can be disabled by this option.
1598 @end table
1601 It is often necessary to check the content of a @file{configure.ac}
1602 file, but parsing it yourself is extremely fragile and error-prone.  It
1603 is suggested that you rely upon @option{--trace} to scan
1604 @file{configure.ac}.  For instance, to find the list of variables that
1605 are substituted, use:
1607 @example
1608 @group
1609 $ @kbd{autoconf -t AC_SUBST}
1610 configure.ac:2:AC_SUBST:ECHO_C
1611 configure.ac:2:AC_SUBST:ECHO_N
1612 configure.ac:2:AC_SUBST:ECHO_T
1613 @i{More traces deleted}
1614 @end group
1615 @end example
1617 @noindent
1618 The example below highlights the difference between @samp{$@@},
1619 @samp{$*}, and @samp{$%}.
1621 @example
1622 @group
1623 $ @kbd{cat configure.ac}
1624 AC_DEFINE(This, is, [an
1625 [example]])
1626 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1627 *: $*
1628 %: $%'
1629 @@: [This],[is],[an
1630 [example]]
1631 *: This,is,an
1632 [example]
1633 %: This:is:an [example]
1634 @end group
1635 @end example
1637 @noindent
1638 The @var{format} gives you a lot of freedom:
1640 @example
1641 @group
1642 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1643 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1644 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1645 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1646 @i{More traces deleted}
1647 @end group
1648 @end example
1650 @noindent
1651 A long @var{separator} can be used to improve the readability of complex
1652 structures, and to ease their parsing (for instance when no single
1653 character is suitable as a separator):
1655 @example
1656 @group
1657 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1658 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1659 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1660 AUTOMAKE|:::::|automake|:::::|$missing_dir
1661 @i{More traces deleted}
1662 @end group
1663 @end example
1665 @node autoreconf Invocation
1666 @section Using @command{autoreconf} to Update @command{configure} Scripts
1667 @cindex @command{autoreconf}
1669 Installing the various components of the GNU Build System can be
1670 tedious: running @command{autopoint} for Gettext, @command{automake} for
1671 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1672 because some tools such as @command{automake} have been updated on your
1673 system, or because some of the sources such as @file{configure.ac} have
1674 been updated, or finally, simply in order to install the GNU Build
1675 System in a fresh tree.
1677 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1678 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1679 @command{autopoint} (when appropriate) repeatedly to update the
1680 GNU Build System in the specified directories and their
1681 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1682 those files that are older than their sources.  The environment variables
1683 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1684 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1685 may be used to override the invocation of the respective tools.
1687 If you install a new version of some tool, you can make
1688 @command{autoreconf} remake @emph{all} of the files by giving it the
1689 @option{--force} option.
1691 @xref{Automatic Remaking}, for Make rules to automatically
1692 rebuild @command{configure} scripts when their source files change.  That
1693 method handles the timestamps of configuration header templates
1694 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1695 @option{--localdir=@var{dir}}.
1697 @cindex Gettext
1698 @cindex @command{autopoint}
1699 Gettext supplies the @command{autopoint} command to add translation
1700 infrastructure to a source package.  If you use @command{autopoint},
1701 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1702 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1703 Invocation, , Invoking the @code{autopoint} Program, gettext,
1704 GNU @code{gettext} utilities}, for further details.
1706 @noindent
1707 @command{autoreconf} accepts the following options:
1709 @table @option
1710 @item --help
1711 @itemx -h
1712 Print a summary of the command line options and exit.
1714 @item --version
1715 @itemx -V
1716 Print the version number of Autoconf and exit.
1718 @item --verbose
1719 @itemx -v
1720 Print the name of each directory @command{autoreconf} examines and the
1721 commands it runs.  If given two or more times, pass @option{--verbose}
1722 to subordinate tools that support it.
1724 @item --debug
1725 @itemx -d
1726 Don't remove the temporary files.
1728 @item --force
1729 @itemx -f
1730 Remake even @file{configure} scripts and configuration headers that are
1731 newer than their input files (@file{configure.ac} and, if present,
1732 @file{aclocal.m4}).
1734 @item --install
1735 @itemx -i
1736 Install the missing auxiliary files in the package.  By default, files
1737 are copied; this can be changed with @option{--symlink}.
1739 If deemed appropriate, this option triggers calls to
1740 @samp{automake --add-missing},
1741 @samp{libtoolize}, @samp{autopoint}, etc.
1743 @item --no-recursive
1744 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1745 macro @code{AC_CONFIG_SUBDIRS}).
1747 @item --symlink
1748 @itemx -s
1749 When used with @option{--install}, install symbolic links to the missing
1750 auxiliary files instead of copying them.
1752 @item --make
1753 @itemx -m
1754 When the directories were configured, update the configuration by
1755 running @samp{./config.status --recheck && ./config.status}, and then
1756 run @samp{make}.
1758 @item --include=@var{dir}
1759 @itemx -I @var{dir}
1760 Append @var{dir} to the include path.  Multiple invocations accumulate.
1761 Passed on to @command{aclocal}, @command{autoconf} and
1762 @command{autoheader} internally.
1764 @item --prepend-include=@var{dir}
1765 @itemx -B @var{dir}
1766 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1767 Passed on to @command{autoconf} and @command{autoheader} internally.
1769 @item --warnings=@var{category}
1770 @itemx -W @var{category}
1771 @evindex WARNINGS
1772 Report the warnings related to @var{category} (which can actually be a
1773 comma separated list).
1775 @table @samp
1776 @item cross
1777 related to cross compilation issues.
1779 @item obsolete
1780 report the uses of obsolete constructs.
1782 @item portability
1783 portability issues
1785 @item syntax
1786 dubious syntactic constructs.
1788 @item all
1789 report all the warnings
1791 @item none
1792 report none
1794 @item error
1795 treats warnings as errors
1797 @item no-@var{category}
1798 disable warnings falling into @var{category}
1799 @end table
1801 Warnings about @samp{syntax} are enabled by default, and the environment
1802 variable @env{WARNINGS}, a comma separated list of categories, is
1803 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1804 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1805 disable the defaults and @env{WARNINGS}, and then
1806 enable warnings about obsolete constructs, use @option{-W
1807 none,obsolete}.
1808 @end table
1810 If you want @command{autoreconf} to pass flags that are not listed here
1811 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1812 Due to a limitation in the Autoconf implementation these flags currently
1813 must be set on a single line in @file{Makefile.am}, without any
1814 backslash-newlines.
1816 @c ========================================= Initialization and Output Files.
1818 @node Setup
1819 @chapter Initialization and Output Files
1821 Autoconf-generated @command{configure} scripts need some information about
1822 how to initialize, such as how to find the package's source files and
1823 about the output files to produce.  The following sections describe the
1824 initialization and the creation of output files.
1826 @menu
1827 * Initializing configure::      Option processing etc.
1828 * Versioning::                  Dealing with Autoconf versions
1829 * Notices::                     Copyright, version numbers in @command{configure}
1830 * Input::                       Where Autoconf should find files
1831 * Output::                      Outputting results from the configuration
1832 * Configuration Actions::       Preparing the output based on results
1833 * Configuration Files::         Creating output files
1834 * Makefile Substitutions::      Using output variables in makefiles
1835 * Configuration Headers::       Creating a configuration header file
1836 * Configuration Commands::      Running arbitrary instantiation commands
1837 * Configuration Links::         Links depending on the configuration
1838 * Subdirectories::              Configuring independent packages together
1839 * Default Prefix::              Changing the default installation prefix
1840 @end menu
1842 @node Initializing configure
1843 @section Initializing @command{configure}
1845 Every @command{configure} script must call @code{AC_INIT} before doing
1846 anything else that produces output.  Calls to silent macros, such as
1847 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1848 are generally used via @file{aclocal.m4}, since that is implicitly
1849 included before the start of @file{configure.ac}.  The only other
1850 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1852 @anchor{AC_INIT}
1853 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1854   @ovar{tarname}, @ovar{url})
1855 @acindex{INIT}
1856 Process any command-line arguments and perform various initializations
1857 and verifications.
1859 Set the name of the @var{package} and its @var{version}.  These are
1860 typically used in @option{--version} support, including that of
1861 @command{configure}.  The optional argument @var{bug-report} should be
1862 the email to which users should send bug reports.  The package
1863 @var{tarname} differs from @var{package}: the latter designates the full
1864 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1865 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1866 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1867 other than alphanumerics and underscores are changed to @samp{-}.  If
1868 provided, @var{url} should be the home page for the package.
1870 The arguments of @code{AC_INIT} must be static, i.e., there should not
1871 be any shell computation, quotes, or newlines, but they can be computed
1872 by M4.  This is because the package information strings are expanded at
1873 M4 time into several contexts, and must give the same text at shell time
1874 whether used in single-quoted strings, double-quoted strings, quoted
1875 here-documents, or unquoted here-documents.  It is permissible to use
1876 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1877 that changes with every commit to a version control system (in fact,
1878 Autoconf does just that, for all builds of the development tree made
1879 between releases).
1881 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1882 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1883 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1885 @table @asis
1886 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1887 @acindex{PACKAGE_NAME}
1888 @ovindex PACKAGE_NAME
1889 @cvindex PACKAGE_NAME
1890 Exactly @var{package}.
1892 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1893 @acindex{PACKAGE_TARNAME}
1894 @ovindex PACKAGE_TARNAME
1895 @cvindex PACKAGE_TARNAME
1896 Exactly @var{tarname}, possibly generated from @var{package}.
1898 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1899 @acindex{PACKAGE_VERSION}
1900 @ovindex PACKAGE_VERSION
1901 @cvindex PACKAGE_VERSION
1902 Exactly @var{version}.
1904 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1905 @acindex{PACKAGE_STRING}
1906 @ovindex PACKAGE_STRING
1907 @cvindex PACKAGE_STRING
1908 Exactly @samp{@var{package} @var{version}}.
1910 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1911 @acindex{PACKAGE_BUGREPORT}
1912 @ovindex PACKAGE_BUGREPORT
1913 @cvindex PACKAGE_BUGREPORT
1914 Exactly @var{bug-report}, if one was provided.  Typically an email
1915 address, or URL to a bug management web page.
1917 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1918 @acindex{PACKAGE_URL}
1919 @ovindex PACKAGE_URL
1920 @cvindex PACKAGE_URL
1921 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1922 @var{package} begins with @samp{GNU }, then this defaults to
1923 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1924 assumed.
1925 @end table
1926 @end defmac
1928 If your @command{configure} script does its own option processing, it
1929 should inspect @samp{$@@} or @samp{$*} immediately after calling
1930 @code{AC_INIT}, because other Autoconf macros liberally use the
1931 @command{set} command to process strings, and this has the side effect
1932 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1933 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1934 implement your own option processing.  @xref{Site Configuration}.
1936 @node Versioning
1937 @section Dealing with Autoconf versions
1938 @cindex Autoconf version
1939 @cindex version, Autoconf
1941 The following optional macros can be used to help choose the minimum
1942 version of Autoconf that can successfully compile a given
1943 @file{configure.ac}.
1945 @defmac AC_PREREQ (@var{version})
1946 @acindex{PREREQ}
1947 @cindex Version
1948 Ensure that a recent enough version of Autoconf is being used.  If the
1949 version of Autoconf being used to create @command{configure} is
1950 earlier than @var{version}, print an error message to the standard
1951 error output and exit with failure (exit status is 63).  For example:
1953 @example
1954 AC_PREREQ([@value{VERSION}])
1955 @end example
1957 This macro may be used before @code{AC_INIT}.
1958 @end defmac
1960 @defmac AC_AUTOCONF_VERSION
1961 @acindex{AUTOCONF_VERSION}
1962 This macro was introduced in Autoconf 2.62.  It identifies the version
1963 of Autoconf that is currently parsing the input file, in a format
1964 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1965 other words, for this release of Autoconf, its value is
1966 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1967 conditional fallbacks based on when a feature was added to Autoconf,
1968 rather than using @code{AC_PREREQ} to require the newer version of
1969 Autoconf.  However, remember that the Autoconf philosophy favors feature
1970 checks over version checks.
1972 You should not expand this macro directly; use
1973 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1974 users might
1975 have a beta version of Autoconf installed, with arbitrary letters
1976 included in its version string.  This means it is possible for the
1977 version string to contain the name of a defined macro, such that
1978 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1979 macro during rescanning, and change the version string to be different
1980 than what you intended to check.
1981 @end defmac
1983 @node Notices
1984 @section Notices in @command{configure}
1985 @cindex Notices in @command{configure}
1987 The following macros manage version numbers for @command{configure}
1988 scripts.  Using them is optional.
1990 @defmac AC_COPYRIGHT (@var{copyright-notice})
1991 @acindex{COPYRIGHT}
1992 @cindex Copyright Notice
1993 State that, in addition to the Free Software Foundation's copyright on
1994 the Autoconf macros, parts of your @command{configure} are covered by the
1995 @var{copyright-notice}.
1997 The @var{copyright-notice} shows up in both the head of
1998 @command{configure} and in @samp{configure --version}.
1999 @end defmac
2002 @defmac AC_REVISION (@var{revision-info})
2003 @acindex{REVISION}
2004 @cindex Revision
2005 Copy revision stamp @var{revision-info} into the @command{configure}
2006 script, with any dollar signs or double-quotes removed.  This macro lets
2007 you put a revision stamp from @file{configure.ac} into @command{configure}
2008 without RCS or CVS changing it when you check in
2009 @command{configure}.  That way, you can determine easily which revision of
2010 @file{configure.ac} a particular @command{configure} corresponds to.
2012 For example, this line in @file{configure.ac}:
2014 @c The @w prevents RCS from changing the example in the manual.
2015 @example
2016 AC_REVISION([@w{$}Revision: 1.30 $])
2017 @end example
2019 @noindent
2020 produces this in @command{configure}:
2022 @example
2023 #!/bin/sh
2024 # From configure.ac Revision: 1.30
2025 @end example
2026 @end defmac
2029 @node Input
2030 @section Finding @command{configure} Input
2032 @anchor{AC_CONFIG_SRCDIR}
2033 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2034 @acindex{CONFIG_SRCDIR}
2035 @var{unique-file-in-source-dir} is some file that is in the package's
2036 source directory; @command{configure} checks for this file's existence to
2037 make sure that the directory that it is told contains the source code in
2038 fact does.  Occasionally people accidentally specify the wrong directory
2039 with @option{--srcdir}; this is a safety check.  @xref{configure
2040 Invocation}, for more information.
2041 @end defmac
2044 @c FIXME: Remove definitively once --install explained.
2046 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2047 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2048 @c to split the macros in several files.  In this case, Autoconf must be
2049 @c told which files to load, and in which order.
2051 @c @defmac AC_INCLUDE (@var{file}@dots{})
2052 @c @acindex{INCLUDE}
2053 @c @c FIXME: There is no longer shell globbing.
2054 @c Read the macro definitions that appear in the listed files.  A list of
2055 @c space-separated file names or shell globbing patterns is expected.  The
2056 @c files are read in the order they're listed.
2058 @c Because the order of definition of macros is important (only the last
2059 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2060 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2061 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2062 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2063 @c the latter case, non-macro lines from included files may end up in the
2064 @c @file{configure} script, whereas in the former case, they'd be discarded
2065 @c just like any text that appear before @code{AC_INIT}.
2066 @c @end defmac
2068 Packages that do manual configuration or use the @command{install} program
2069 might need to tell @command{configure} where to find some other shell
2070 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2071 it looks are correct for most cases.
2073 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2074 @acindex{CONFIG_AUX_DIR}
2075 Use the auxiliary build tools (e.g., @file{install-sh},
2076 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2077 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2078 These are auxiliary files used in configuration.  @var{dir} can be
2079 either absolute or relative to @file{@var{srcdir}}.  The default is
2080 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2081 @file{@var{srcdir}/../..}, whichever is the first that contains
2082 @file{install-sh}.  The other files are not checked for, so that using
2083 @code{AC_PROG_INSTALL} does not automatically require distributing the
2084 other auxiliary files.  It checks for @file{install.sh} also, but that
2085 name is obsolete because some @command{make} have a rule that creates
2086 @file{install} from it if there is no makefile.
2088 The auxiliary directory is commonly named @file{build-aux}.
2089 If you need portability to DOS variants, do not name the
2090 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2091 @end defmac
2093 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2094 @acindex{REQUIRE_AUX_FILE}
2095 Declares that @var{file} is expected in the directory defined above.  In
2096 Autoconf proper, this macro does nothing: its sole purpose is to be
2097 traced by third-party tools to produce a list of expected auxiliary
2098 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2099 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2100 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2101 @end defmac
2103 Similarly, packages that use @command{aclocal} should declare where
2104 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2106 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2107 @acindex{CONFIG_MACRO_DIR}
2108 Specify @var{dir} as the location of additional local Autoconf macros.
2109 This macro is intended for use by future versions of commands like
2110 @command{autoreconf} that trace macro calls.  It should be called
2111 directly from @file{configure.ac} so that tools that install macros for
2112 @command{aclocal} can find the macros' declarations.
2114 Note that if you use @command{aclocal} from Automake to generate
2115 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2116 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2117 the Autoconf implementation of @command{autoreconf}, these include
2118 directives currently must be set on a single line in @file{Makefile.am},
2119 without any backslash-newlines.
2120 @end defmac
2123 @node Output
2124 @section Outputting Files
2125 @cindex Outputting files
2127 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2128 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2129 @file{config.status}, which in turn creates the makefiles and any
2130 other files resulting from configuration.  This is the only required
2131 macro besides @code{AC_INIT} (@pxref{Input}).
2133 @anchor{AC_OUTPUT}
2134 @defmac AC_OUTPUT
2135 @acindex{OUTPUT}
2136 @cindex Instantiation
2137 Generate @file{config.status} and launch it.  Call this macro once, at
2138 the end of @file{configure.ac}.
2140 @file{config.status} performs all the configuration actions: all the
2141 output files (see @ref{Configuration Files}, macro
2142 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2143 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2144 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2145 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2146 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2147 are honored.
2149 The location of your @code{AC_OUTPUT} invocation is the exact point
2150 where configuration actions are taken: any code afterwards is
2151 executed by @command{configure} once @command{config.status} was run.  If
2152 you want to bind actions to @command{config.status} itself
2153 (independently of whether @command{configure} is being run), see
2154 @ref{Configuration Commands, , Running Arbitrary Configuration
2155 Commands}.
2156 @end defmac
2158 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2159 @xref{Obsolete Macros}, for a description of the arguments that
2160 @code{AC_OUTPUT} used to support.
2163 If you run @command{make} in subdirectories, you should run it using the
2164 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2165 @code{MAKE} to the name of the @command{make} program plus any options it
2166 was given.  (But many do not include in it the values of any variables
2167 set on the command line, so those are not passed on automatically.)
2168 Some old versions of @command{make} do not set this variable.  The
2169 following macro allows you to use it even with those versions.
2171 @anchor{AC_PROG_MAKE_SET}
2172 @defmac AC_PROG_MAKE_SET
2173 @acindex{PROG_MAKE_SET}
2174 @ovindex SET_MAKE
2175 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2176 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2177 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2178 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2179 @code{SET_MAKE}.
2180 @end defmac
2182 If you use this macro, place a line like this in each @file{Makefile.in}
2183 that runs @command{MAKE} on other directories:
2185 @example
2186 @@SET_MAKE@@
2187 @end example
2191 @node Configuration Actions
2192 @section Performing Configuration Actions
2193 @cindex Configuration actions
2195 @file{configure} is designed so that it appears to do everything itself,
2196 but there is actually a hidden slave: @file{config.status}.
2197 @file{configure} is in charge of examining your system, but it is
2198 @file{config.status} that actually takes the proper actions based on the
2199 results of @file{configure}.  The most typical task of
2200 @file{config.status} is to @emph{instantiate} files.
2202 @acindex{CONFIG_@var{ITEMS}}
2203 This section describes the common behavior of the four standard
2204 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2205 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2206 have this prototype:
2208 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2209 @c awful.
2210 @example
2211 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2212 @end example
2214 @noindent
2215 where the arguments are:
2217 @table @var
2218 @item tag@dots{}
2219 A blank-or-newline-separated list of tags, which are typically the names of
2220 the files to instantiate.
2222 You are encouraged to use literals as @var{tags}.  In particular, you
2223 should avoid
2225 @example
2226 @dots{} && my_foos="$my_foos fooo"
2227 @dots{} && my_foos="$my_foos foooo"
2228 AC_CONFIG_@var{ITEMS}([$my_foos])
2229 @end example
2231 @noindent
2232 and use this instead:
2234 @example
2235 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2236 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2237 @end example
2239 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2240 special @var{tag} values: they may have the form @samp{@var{output}} or
2241 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2242 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2244 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2245 for example, asks for
2246 the creation of the file @file{Makefile} that contains the expansion of the
2247 output variables in the concatenation of @file{boiler/top.mk} and
2248 @file{boiler/bot.mk}.
2250 The special value @samp{-} might be used to denote the standard output
2251 when used in @var{output}, or the standard input when used in the
2252 @var{inputs}.  You most probably don't need to use this in
2253 @file{configure.ac}, but it is convenient when using the command line
2254 interface of @file{./config.status}, see @ref{config.status Invocation},
2255 for more details.
2257 The @var{inputs} may be absolute or relative file names.  In the latter
2258 case they are first looked for in the build tree, and then in the source
2259 tree.  Input files should be text files, and a line length below 2000
2260 bytes should be safe.
2262 @item commands
2263 Shell commands output literally into @file{config.status}, and
2264 associated with a tag that the user can use to tell @file{config.status}
2265 which commands to run.  The commands are run each time a @var{tag}
2266 request is given to @file{config.status}, typically each time the file
2267 @file{@var{tag}} is created.
2269 The variables set during the execution of @command{configure} are
2270 @emph{not} available here: you first need to set them via the
2271 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2273 @table @code
2274 @item srcdir
2275 @vrindex srcdir
2276 The name of the top source directory, assuming that the working
2277 directory is the top build directory.  This
2278 is what the @command{configure} option @option{--srcdir} sets.
2280 @item ac_top_srcdir
2281 @vrindex ac_top_srcdir
2282 The name of the top source directory, assuming that the working
2283 directory is the current build directory.
2285 @item ac_top_build_prefix
2286 @vrindex ac_top_build_prefix
2287 The name of the top build directory, assuming that the working
2288 directory is the current build directory.
2289 It can be empty, or else ends with a slash, so that you may concatenate
2292 @item ac_srcdir
2293 @vrindex ac_srcdir
2294 The name of the corresponding source directory, assuming that the
2295 working directory is the current build directory.
2297 @item tmp
2298 @vrindex tmp
2299 The name of a temporary directory within the build tree, which you
2300 can use if you need to create additional temporary files.  The
2301 directory is cleaned up when @command{config.status} is done or
2302 interrupted.  Please use package-specific file name prefixes to
2303 avoid clashing with files that @command{config.status} may use
2304 internally.
2305 @end table
2307 @noindent
2308 The @dfn{current} directory refers to the directory (or
2309 pseudo-directory) containing the input part of @var{tags}.  For
2310 instance, running
2312 @example
2313 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2314 @end example
2316 @noindent
2317  with @option{--srcdir=../package} produces the following values:
2319 @example
2320 # Argument of --srcdir
2321 srcdir='../package'
2322 # Reversing deep/dir
2323 ac_top_build_prefix='../../'
2324 # Concatenation of $ac_top_build_prefix and srcdir
2325 ac_top_srcdir='../../../package'
2326 # Concatenation of $ac_top_srcdir and deep/dir
2327 ac_srcdir='../../../package/deep/dir'
2328 @end example
2330 @noindent
2331 independently of @samp{in/in.in}.
2333 @item init-cmds
2334 Shell commands output @emph{unquoted} near the beginning of
2335 @file{config.status}, and executed each time @file{config.status} runs
2336 (regardless of the tag).  Because they are unquoted, for example,
2337 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2338 is typically used by @file{configure} to give @file{config.status} some
2339 variables it needs to run the @var{commands}.
2341 You should be extremely cautious in your variable names: all the
2342 @var{init-cmds} share the same name space and may overwrite each other
2343 in unpredictable ways.  Sorry@enddots{}
2344 @end table
2346 All these macros can be called multiple times, with different
2347 @var{tag} values, of course!
2350 @node Configuration Files
2351 @section Creating Configuration Files
2352 @cindex Creating configuration files
2353 @cindex Configuration file creation
2355 Be sure to read the previous section, @ref{Configuration Actions}.
2357 @anchor{AC_CONFIG_FILES}
2358 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2359 @acindex{CONFIG_FILES}
2360 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2361 file (by default @file{@var{file}.in}), substituting the output variable
2362 values.
2363 @c Before we used to have this feature, which was later rejected
2364 @c because it complicates the writing of makefiles:
2365 @c If the file would be unchanged, it is left untouched, to preserve
2366 @c timestamp.
2367 This macro is one of the instantiating macros; see @ref{Configuration
2368 Actions}.  @xref{Makefile Substitutions}, for more information on using
2369 output variables.  @xref{Setting Output Variables}, for more information
2370 on creating them.  This macro creates the directory that the file is in
2371 if it doesn't exist.  Usually, makefiles are created this way,
2372 but other files, such as @file{.gdbinit}, can be specified as well.
2374 Typical calls to @code{AC_CONFIG_FILES} look like this:
2376 @example
2377 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2378 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2379 @end example
2381 You can override an input file name by appending to @var{file} a
2382 colon-separated list of input files.  Examples:
2384 @example
2385 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2386                 [lib/Makefile:boiler/lib.mk])
2387 @end example
2389 @noindent
2390 Doing this allows you to keep your file names acceptable to
2391 DOS variants, or
2392 to prepend and/or append boilerplate to the file.
2393 @end defmac
2397 @node Makefile Substitutions
2398 @section Substitutions in Makefiles
2399 @cindex Substitutions in makefiles
2400 @cindex Makefile substitutions
2402 Each subdirectory in a distribution that contains something to be
2403 compiled or installed should come with a file @file{Makefile.in}, from
2404 which @command{configure} creates a file @file{Makefile} in that directory.
2405 To create @file{Makefile}, @command{configure} performs a simple variable
2406 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2407 @file{Makefile.in} with the value that @command{configure} has determined
2408 for that variable.  Variables that are substituted into output files in
2409 this way are called @dfn{output variables}.  They are ordinary shell
2410 variables that are set in @command{configure}.  To make @command{configure}
2411 substitute a particular variable into the output files, the macro
2412 @code{AC_SUBST} must be called with that variable name as an argument.
2413 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2414 left unchanged.  @xref{Setting Output Variables}, for more information
2415 on creating output variables with @code{AC_SUBST}.
2417 A software package that uses a @command{configure} script should be
2418 distributed with a file @file{Makefile.in}, but no makefile; that
2419 way, the user has to properly configure the package for the local system
2420 before compiling it.
2422 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2423 GNU Coding Standards}, for more information on what to put in
2424 makefiles.
2426 @menu
2427 * Preset Output Variables::     Output variables that are always set
2428 * Installation Directory Variables::  Other preset output variables
2429 * Changed Directory Variables::  Warnings about @file{datarootdir}
2430 * Build Directories::           Supporting multiple concurrent compiles
2431 * Automatic Remaking::          Makefile rules for configuring
2432 @end menu
2434 @node Preset Output Variables
2435 @subsection Preset Output Variables
2436 @cindex Output variables
2438 Some output variables are preset by the Autoconf macros.  Some of the
2439 Autoconf macros set additional output variables, which are mentioned in
2440 the descriptions for those macros.  @xref{Output Variable Index}, for a
2441 complete list of output variables.  @xref{Installation Directory
2442 Variables}, for the list of the preset ones related to installation
2443 directories.  Below are listed the other preset ones, many of which are
2444 precious variables (@pxref{Setting Output Variables},
2445 @code{AC_ARG_VAR}).
2447 The preset variables which are available during @file{config.status}
2448 (@pxref{Configuration Actions}) may also be used during
2449 @command{configure} tests.  For example, it is permissible to reference
2450 @samp{$srcdir} when constructing a list of directories to pass via
2451 option @option{-I} during a compiler feature check.  When used in this
2452 manner, coupled with the fact that @command{configure} is always run
2453 from the top build directory, it is sufficient to use just
2454 @samp{$srcdir} instead of @samp{$top_srcdir}.
2456 @c Just say no to ASCII sorting!  We're humans, not computers.
2457 @c These variables are listed as they would be in a dictionary:
2458 @c actor
2459 @c Actress
2460 @c actress
2462 @defvar CFLAGS
2463 @evindex CFLAGS
2464 @ovindex CFLAGS
2465 Debugging and optimization options for the C compiler.  If it is not set
2466 in the environment when @command{configure} runs, the default value is set
2467 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2468 uses this variable when compiling or linking programs to test for C features.
2470 If a compiler option affects only the behavior of the preprocessor
2471 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2472 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2473 it should be put into @code{LDFLAGS} instead.  If it
2474 affects only the compiler proper, @code{CFLAGS} is the natural home for
2475 it.  If an option affects multiple phases of the compiler, though,
2476 matters get tricky.  One approach to put such options directly into
2477 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2478 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2480 However, remember that some @file{Makefile} variables are reserved by
2481 the GNU Coding Standards for the use of the ``user''---the person
2482 building the package.  For instance, @code{CFLAGS} is one such variable.
2484 Sometimes package developers are tempted to set user variables such as
2485 @code{CFLAGS} because it appears to make their job easier.  However, the
2486 package itself should never set a user variable, particularly not to
2487 include switches that are required for proper compilation of the
2488 package.  Since these variables are documented as being for the package
2489 builder, that person rightfully expects to be able to override any of
2490 these variables at build time.  If the package developer needs to add
2491 switches without interfering with the user, the proper way to do that is
2492 to introduce an additional variable.  Automake makes this easy by
2493 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2494 automake, GNU Automake}), but the concept is the same even if
2495 Automake is not used.
2496 @end defvar
2498 @defvar configure_input
2499 @ovindex configure_input
2500 A comment saying that the file was generated automatically by
2501 @command{configure} and giving the name of the input file.
2502 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2503 of every makefile it creates.  For other files, you should
2504 reference this variable in a comment at the top of each input file.  For
2505 example, an input shell script should begin like this:
2507 @example
2508 #!/bin/sh
2509 # @@configure_input@@
2510 @end example
2512 @noindent
2513 The presence of that line also reminds people editing the file that it
2514 needs to be processed by @command{configure} in order to be used.
2515 @end defvar
2517 @defvar CPPFLAGS
2518 @evindex CPPFLAGS
2519 @ovindex CPPFLAGS
2520 Preprocessor options for the C, C++, Objective C, and Objective C++
2521 preprocessors and compilers.  If
2522 it is not set in the environment when @command{configure} runs, the default
2523 value is empty.  @command{configure} uses this variable when preprocessing
2524 or compiling programs to test for C, C++, Objective C, and Objective C++
2525 features.
2527 This variable's contents should contain options like @option{-I},
2528 @option{-D}, and @option{-U} that affect only the behavior of the
2529 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2530 can do if an option affects other phases of the compiler as well.
2532 Currently, @command{configure} always links as part of a single
2533 invocation of the compiler that also preprocesses and compiles, so it
2534 uses this variable also when linking programs.  However, it is unwise to
2535 depend on this behavior because the GNU Coding Standards do
2536 not require it and many packages do not use @code{CPPFLAGS} when linking
2537 programs.
2539 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2540 might run into.
2541 @end defvar
2543 @defvar CXXFLAGS
2544 @evindex CXXFLAGS
2545 @ovindex CXXFLAGS
2546 Debugging and optimization options for the C++ compiler.  It acts like
2547 @code{CFLAGS}, but for C++ instead of C.
2548 @end defvar
2550 @defvar DEFS
2551 @ovindex DEFS
2552 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2553 is called, @command{configure} replaces @samp{@@DEFS@@} with
2554 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2555 variable is not defined while @command{configure} is performing its tests,
2556 only when creating the output files.  @xref{Setting Output Variables}, for
2557 how to check the results of previous tests.
2558 @end defvar
2560 @defvar ECHO_C
2561 @defvarx ECHO_N
2562 @defvarx ECHO_T
2563 @ovindex ECHO_C
2564 @ovindex ECHO_N
2565 @ovindex ECHO_T
2566 How does one suppress the trailing newline from @command{echo} for
2567 question-answer message pairs?  These variables provide a way:
2569 @example
2570 echo $ECHO_N "And the winner is... $ECHO_C"
2571 sleep 100000000000
2572 echo "$@{ECHO_T@}dead."
2573 @end example
2575 @noindent
2576 Some old and uncommon @command{echo} implementations offer no means to
2577 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2578 want to use it.
2579 @end defvar
2581 @defvar ERLCFLAGS
2582 @evindex ERLCFLAGS
2583 @ovindex ERLCFLAGS
2584 Debugging and optimization options for the Erlang compiler.  If it is not set
2585 in the environment when @command{configure} runs, the default value is empty.
2586 @command{configure} uses this variable when compiling
2587 programs to test for Erlang features.
2588 @end defvar
2590 @defvar FCFLAGS
2591 @evindex FCFLAGS
2592 @ovindex FCFLAGS
2593 Debugging and optimization options for the Fortran compiler.  If it
2594 is not set in the environment when @command{configure} runs, the default
2595 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2596 @command{configure} uses this variable when compiling or linking
2597 programs to test for Fortran features.
2598 @end defvar
2600 @defvar FFLAGS
2601 @evindex FFLAGS
2602 @ovindex FFLAGS
2603 Debugging and optimization options for the Fortran 77 compiler.  If it
2604 is not set in the environment when @command{configure} runs, the default
2605 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2606 @command{configure} uses this variable when compiling or linking
2607 programs to test for Fortran 77 features.
2608 @end defvar
2610 @defvar LDFLAGS
2611 @evindex LDFLAGS
2612 @ovindex LDFLAGS
2613 Options for the linker.  If it is not set
2614 in the environment when @command{configure} runs, the default value is empty.
2615 @command{configure} uses this variable when linking programs to test for
2616 C, C++, Objective C, Objective C++, Fortran, and Go features.
2618 This variable's contents should contain options like @option{-s} and
2619 @option{-L} that affect only the behavior of the linker.  Please see the
2620 explanation of @code{CFLAGS} for what you can do if an option also
2621 affects other phases of the compiler.
2623 Don't use this variable to pass library names
2624 (@option{-l}) to the linker; use @code{LIBS} instead.
2625 @end defvar
2627 @defvar LIBS
2628 @evindex LIBS
2629 @ovindex LIBS
2630 @option{-l} options to pass to the linker.  The default value is empty,
2631 but some Autoconf macros may prepend extra libraries to this variable if
2632 those libraries are found and provide necessary functions, see
2633 @ref{Libraries}.  @command{configure} uses this variable when linking
2634 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2635 features.
2636 @end defvar
2638 @defvar OBJCFLAGS
2639 @evindex OBJCFLAGS
2640 @ovindex OBJCFLAGS
2641 Debugging and optimization options for the Objective C compiler.  It
2642 acts like @code{CFLAGS}, but for Objective C instead of C.
2643 @end defvar
2645 @defvar OBJCXXFLAGS
2646 @evindex OBJCXXFLAGS
2647 @ovindex OBJCXXFLAGS
2648 Debugging and optimization options for the Objective C++ compiler.  It
2649 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2650 @end defvar
2652 @defvar GOFLAGS
2653 @evindex GOFLAGS
2654 @ovindex GOFLAGS
2655 Debugging and optimization options for the Go compiler.  It acts like
2656 @code{CFLAGS}, but for Go instead of C.
2657 @end defvar
2659 @defvar builddir
2660 @ovindex builddir
2661 Rigorously equal to @samp{.}.  Added for symmetry only.
2662 @end defvar
2664 @defvar abs_builddir
2665 @ovindex abs_builddir
2666 Absolute name of @code{builddir}.
2667 @end defvar
2669 @defvar top_builddir
2670 @ovindex top_builddir
2671 The relative name of the top level of the current build tree.  In the
2672 top-level directory, this is the same as @code{builddir}.
2673 @end defvar
2675 @defvar top_build_prefix
2676 @ovindex top_build_prefix
2677 The relative name of the top level of the current build tree with final
2678 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2679 it contains zero or more runs of @code{../}, so it should not be
2680 appended with a slash for concatenation.  This helps for @command{make}
2681 implementations that otherwise do not treat @file{./file} and @file{file}
2682 as equal in the toplevel build directory.
2683 @end defvar
2685 @defvar abs_top_builddir
2686 @ovindex abs_top_builddir
2687 Absolute name of @code{top_builddir}.
2688 @end defvar
2690 @defvar srcdir
2691 @ovindex srcdir
2692 The name of the directory that contains the source code for
2693 that makefile.
2694 @end defvar
2696 @defvar abs_srcdir
2697 @ovindex abs_srcdir
2698 Absolute name of @code{srcdir}.
2699 @end defvar
2701 @defvar top_srcdir
2702 @ovindex top_srcdir
2703 The name of the top-level source code directory for the
2704 package.  In the top-level directory, this is the same as @code{srcdir}.
2705 @end defvar
2707 @defvar abs_top_srcdir
2708 @ovindex abs_top_srcdir
2709 Absolute name of @code{top_srcdir}.
2710 @end defvar
2712 @node Installation Directory Variables
2713 @subsection Installation Directory Variables
2714 @cindex Installation directories
2715 @cindex Directories, installation
2717 The following variables specify the directories for
2718 package installation, see @ref{Directory Variables, , Variables for
2719 Installation Directories, standards, The GNU Coding
2720 Standards}, for more information.  Each variable corresponds to an
2721 argument of @command{configure}; trailing slashes are stripped so that
2722 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2723 between directory names.  See the end of this section for
2724 details on when and how to use these variables.
2726 @defvar bindir
2727 @ovindex bindir
2728 The directory for installing executables that users run.
2729 @end defvar
2731 @defvar datadir
2732 @ovindex datadir
2733 The directory for installing idiosyncratic read-only
2734 architecture-independent data.
2735 @end defvar
2737 @defvar datarootdir
2738 @ovindex datarootdir
2739 The root of the directory tree for read-only architecture-independent
2740 data files.
2741 @end defvar
2743 @defvar docdir
2744 @ovindex docdir
2745 The directory for installing documentation files (other than Info and
2746 man).
2747 @end defvar
2749 @defvar dvidir
2750 @ovindex dvidir
2751 The directory for installing documentation files in DVI format.
2752 @end defvar
2754 @defvar exec_prefix
2755 @ovindex exec_prefix
2756 The installation prefix for architecture-dependent files.  By default
2757 it's the same as @code{prefix}.  You should avoid installing anything
2758 directly to @code{exec_prefix}.  However, the default value for
2759 directories containing architecture-dependent files should be relative
2760 to @code{exec_prefix}.
2761 @end defvar
2763 @defvar htmldir
2764 @ovindex htmldir
2765 The directory for installing HTML documentation.
2766 @end defvar
2768 @defvar includedir
2769 @ovindex includedir
2770 The directory for installing C header files.
2771 @end defvar
2773 @defvar infodir
2774 @ovindex infodir
2775 The directory for installing documentation in Info format.
2776 @end defvar
2778 @defvar libdir
2779 @ovindex libdir
2780 The directory for installing object code libraries.
2781 @end defvar
2783 @defvar libexecdir
2784 @ovindex libexecdir
2785 The directory for installing executables that other programs run.
2786 @end defvar
2788 @defvar localedir
2789 @ovindex localedir
2790 The directory for installing locale-dependent but
2791 architecture-independent data, such as message catalogs.  This directory
2792 usually has a subdirectory per locale.
2793 @end defvar
2795 @defvar localstatedir
2796 @ovindex localstatedir
2797 The directory for installing modifiable single-machine data.
2798 @end defvar
2800 @defvar mandir
2801 @ovindex mandir
2802 The top-level directory for installing documentation in man format.
2803 @end defvar
2805 @defvar oldincludedir
2806 @ovindex oldincludedir
2807 The directory for installing C header files for non-GCC compilers.
2808 @end defvar
2810 @defvar pdfdir
2811 @ovindex pdfdir
2812 The directory for installing PDF documentation.
2813 @end defvar
2815 @defvar prefix
2816 @ovindex prefix
2817 The common installation prefix for all files.  If @code{exec_prefix}
2818 is defined to a different value, @code{prefix} is used only for
2819 architecture-independent files.
2820 @end defvar
2822 @defvar psdir
2823 @ovindex psdir
2824 The directory for installing PostScript documentation.
2825 @end defvar
2827 @defvar sbindir
2828 @ovindex sbindir
2829 The directory for installing executables that system
2830 administrators run.
2831 @end defvar
2833 @defvar sharedstatedir
2834 @ovindex sharedstatedir
2835 The directory for installing modifiable architecture-independent data.
2836 @end defvar
2838 @defvar sysconfdir
2839 @ovindex sysconfdir
2840 The directory for installing read-only single-machine data.
2841 @end defvar
2844 Most of these variables have values that rely on @code{prefix} or
2845 @code{exec_prefix}.  It is deliberate that the directory output
2846 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2847 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2848 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2850 This behavior is mandated by the GNU Coding Standards, so that when
2851 the user runs:
2853 @table @samp
2854 @item make
2855 she can still specify a different prefix from the one specified to
2856 @command{configure}, in which case, if needed, the package should hard
2857 code dependencies corresponding to the make-specified prefix.
2859 @item make install
2860 she can specify a different installation location, in which case the
2861 package @emph{must} still depend on the location which was compiled in
2862 (i.e., never recompile when @samp{make install} is run).  This is an
2863 extremely important feature, as many people may decide to install all
2864 the files of a package grouped together, and then install links from
2865 the final locations to there.
2866 @end table
2868 In order to support these features, it is essential that
2869 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2870 so that its value can be expanded based
2871 on the current value of @code{prefix}.
2873 A corollary is that you should not use these variables except in
2874 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2875 in @file{configure} and hard-coding it in makefiles using
2876 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2877 you should add
2878 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2879 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2881 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2882 @code{bindir} and friends in your shell scripts and other files; instead,
2883 let @command{make} manage their replacement.  For instance Autoconf
2884 ships templates of its shell scripts ending with @samp{.in}, and uses a
2885 makefile snippet similar to the following to build scripts like
2886 @command{autoheader} and @command{autom4te}:
2888 @example
2889 @group
2890 edit = sed \
2891         -e 's|@@bindir[@@]|$(bindir)|g' \
2892         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2893         -e 's|@@prefix[@@]|$(prefix)|g'
2894 @end group
2896 @group
2897 autoheader autom4te: Makefile
2898         rm -f $@@ $@@.tmp
2899         srcdir=''; \
2900           test -f ./$@@.in || srcdir=$(srcdir)/; \
2901           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2902 @c $$ restore font-lock
2903         chmod +x $@@.tmp
2904         chmod a-w $@@.tmp
2905         mv $@@.tmp $@@
2906 @end group
2908 @group
2909 autoheader: $(srcdir)/autoheader.in
2910 autom4te: $(srcdir)/autom4te.in
2911 @end group
2912 @end example
2914 Some details are noteworthy:
2916 @table @asis
2917 @item @samp{@@bindir[@@]}
2918 The brackets prevent @command{configure} from replacing
2919 @samp{@@bindir@@} in the Sed expression itself.
2920 Brackets are preferable to a backslash here, since
2921 Posix says @samp{\@@} is not portable.
2923 @item @samp{$(bindir)}
2924 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2925 instead.
2927 @item @samp{$(pkgdatadir)}
2928 The example takes advantage of the variable @samp{$(pkgdatadir)}
2929 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2931 @item @samp{/}
2932 Don't use @samp{/} in the Sed expressions that replace file names since
2933 most likely the
2934 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2935 Use a shell metacharacter instead, such as @samp{|}.
2937 @item special characters
2938 File names, file name components, and the value of @code{VPATH} should
2939 not contain shell metacharacters or white
2940 space.  @xref{Special Chars in Variables}.
2942 @item dependency on @file{Makefile}
2943 Since @code{edit} uses values that depend on the configuration specific
2944 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2945 the output depends on @file{Makefile}, not @file{configure.ac}.
2947 @item @samp{$@@}
2948 The main rule is generic, and uses @samp{$@@} extensively to
2949 avoid the need for multiple copies of the rule.
2951 @item Separated dependencies and single suffix rules
2952 You can't use them!  The above snippet cannot be (portably) rewritten
2955 @example
2956 autoconf autoheader: Makefile
2957 @group
2958 .in:
2959         rm -f $@@ $@@.tmp
2960         $(edit) $< >$@@.tmp
2961         chmod +x $@@.tmp
2962         mv $@@.tmp $@@
2963 @end group
2964 @end example
2966 @xref{Single Suffix Rules}, for details.
2968 @item @samp{$(srcdir)}
2969 Be sure to specify the name of the source directory,
2970 otherwise the package won't support separated builds.
2971 @end table
2973 For the more specific installation of Erlang libraries, the following variables
2974 are defined:
2976 @defvar ERLANG_INSTALL_LIB_DIR
2977 @ovindex ERLANG_INSTALL_LIB_DIR
2978 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2979 The common parent directory of Erlang library installation directories.
2980 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2981 macro in @file{configure.ac}.
2982 @end defvar
2984 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2985 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2986 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2987 The installation directory for Erlang library @var{library}.
2988 This variable is set by using the
2989 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2990 macro in @file{configure.ac}.
2991 @end defvar
2993 @xref{Erlang Libraries}, for details.
2996 @node Changed Directory Variables
2997 @subsection Changed Directory Variables
2998 @cindex @file{datarootdir}
3000 In Autoconf 2.60, the set of directory variables has changed, and the
3001 defaults of some variables have been adjusted
3002 (@pxref{Installation Directory Variables}) to changes in the
3003 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3004 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3005 upgrading from an earlier Autoconf version, you may need to adjust your files
3006 to ensure that the directory variables are substituted correctly
3007 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3008 in place.  For example, in a @file{Makefile.in}, adding
3010 @example
3011 datarootdir = @@datarootdir@@
3012 @end example
3014 @noindent
3015 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3016 it will add this for you.
3018 To help with the transition, Autoconf warns about files that seem to use
3019 @code{datarootdir} without defining it.  In some cases, it then expands
3020 the value of @code{$datarootdir} in substitutions of the directory
3021 variables.  The following example shows such a warning:
3023 @example
3024 $ @kbd{cat configure.ac}
3025 AC_INIT
3026 AC_CONFIG_FILES([Makefile])
3027 AC_OUTPUT
3028 $ @kbd{cat Makefile.in}
3029 prefix = @@prefix@@
3030 datadir = @@datadir@@
3031 $ @kbd{autoconf}
3032 $ @kbd{configure}
3033 configure: creating ./config.status
3034 config.status: creating Makefile
3035 config.status: WARNING:
3036                Makefile.in seems to ignore the --datarootdir setting
3037 $ @kbd{cat Makefile}
3038 prefix = /usr/local
3039 datadir = $@{prefix@}/share
3040 @end example
3042 Usually one can easily change the file to accommodate both older and newer
3043 Autoconf releases:
3045 @example
3046 $ @kbd{cat Makefile.in}
3047 prefix = @@prefix@@
3048 datarootdir = @@datarootdir@@
3049 datadir = @@datadir@@
3050 $ @kbd{configure}
3051 configure: creating ./config.status
3052 config.status: creating Makefile
3053 $ @kbd{cat Makefile}
3054 prefix = /usr/local
3055 datarootdir = $@{prefix@}/share
3056 datadir = $@{datarootdir@}
3057 @end example
3059 @acindex{DATAROOTDIR_CHECKED}
3060 In some cases, however, the checks may not be able to detect that a suitable
3061 initialization of @code{datarootdir} is in place, or they may fail to detect
3062 that such an initialization is necessary in the output file.  If, after
3063 auditing your package, there are still spurious @file{configure} warnings about
3064 @code{datarootdir}, you may add the line
3066 @example
3067 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3068 @end example
3070 @noindent
3071 to your @file{configure.ac} to disable the warnings.  This is an exception
3072 to the usual rule that you should not define a macro whose name begins with
3073 @code{AC_} (@pxref{Macro Names}).
3077 @node Build Directories
3078 @subsection Build Directories
3079 @cindex Build directories
3080 @cindex Directories, build
3082 You can support compiling a software package for several architectures
3083 simultaneously from the same copy of the source code.  The object files
3084 for each architecture are kept in their own directory.
3086 To support doing this, @command{make} uses the @code{VPATH} variable to
3087 find the files that are in the source directory.  GNU Make
3088 can do this.  Most other recent @command{make} programs can do this as
3089 well, though they may have difficulties and it is often simpler to
3090 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3091 @command{make} programs do not support @code{VPATH}; when using them, the
3092 source code must be in the same directory as the object files.
3094 If you are using GNU Automake, the remaining details in this
3095 section are already covered for you, based on the contents of your
3096 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3097 supporting @code{VPATH} requires the following in your
3098 @file{Makefile.in}:
3100 @example
3101 srcdir = @@srcdir@@
3102 VPATH = @@srcdir@@
3103 @end example
3105 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3106 listed in VPATH}.
3108 @command{configure} substitutes the correct value for @code{srcdir} when
3109 it produces @file{Makefile}.
3111 Do not use the @command{make} variable @code{$<}, which expands to the
3112 file name of the file in the source directory (found with @code{VPATH}),
3113 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3114 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3115 versions of @command{make} do not set @code{$<} in explicit rules; they
3116 expand it to an empty value.
3118 Instead, Make command lines should always refer to source
3119 files by prefixing them with @samp{$(srcdir)/}.  For example:
3121 @example
3122 time.info: time.texinfo
3123         $(MAKEINFO) '$(srcdir)/time.texinfo'
3124 @end example
3126 @node Automatic Remaking
3127 @subsection Automatic Remaking
3128 @cindex Automatic remaking
3129 @cindex Remaking automatically
3131 You can put rules like the following in the top-level @file{Makefile.in}
3132 for a package to automatically update the configuration information when
3133 you change the configuration files.  This example includes all of the
3134 optional files, such as @file{aclocal.m4} and those related to
3135 configuration header files.  Omit from the @file{Makefile.in} rules for
3136 any of these files that your package does not use.
3138 The @samp{$(srcdir)/} prefix is included because of limitations in the
3139 @code{VPATH} mechanism.
3141 The @file{stamp-} files are necessary because the timestamps of
3142 @file{config.h.in} and @file{config.h} are not changed if remaking
3143 them does not change their contents.  This feature avoids unnecessary
3144 recompilation.  You should include the file @file{stamp-h.in} in your
3145 package's distribution, so that @command{make} considers
3146 @file{config.h.in} up to date.  Don't use @command{touch}
3147 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3148 @command{echo} (using
3149 @command{date} would cause needless differences, hence CVS
3150 conflicts, etc.).
3152 @example
3153 @group
3154 $(srcdir)/configure: configure.ac aclocal.m4
3155         cd '$(srcdir)' && autoconf
3157 # autoheader might not change config.h.in, so touch a stamp file.
3158 $(srcdir)/config.h.in: stamp-h.in
3159 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3160         cd '$(srcdir)' && autoheader
3161         echo timestamp > '$(srcdir)/stamp-h.in'
3163 config.h: stamp-h
3164 stamp-h: config.h.in config.status
3165         ./config.status
3167 Makefile: Makefile.in config.status
3168         ./config.status
3170 config.status: configure
3171         ./config.status --recheck
3172 @end group
3173 @end example
3175 @noindent
3176 (Be careful if you copy these lines directly into your makefile, as you
3177 need to convert the indented lines to start with the tab character.)
3179 In addition, you should use
3181 @example
3182 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3183 @end example
3185 @noindent
3186 so @file{config.status} ensures that @file{config.h} is considered up to
3187 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3189 @xref{config.status Invocation}, for more examples of handling
3190 configuration-related dependencies.
3192 @node Configuration Headers
3193 @section Configuration Header Files
3194 @cindex Configuration Header
3195 @cindex @file{config.h}
3197 When a package contains more than a few tests that define C preprocessor
3198 symbols, the command lines to pass @option{-D} options to the compiler
3199 can get quite long.  This causes two problems.  One is that the
3200 @command{make} output is hard to visually scan for errors.  More
3201 seriously, the command lines can exceed the length limits of some
3202 operating systems.  As an alternative to passing @option{-D} options to
3203 the compiler, @command{configure} scripts can create a C header file
3204 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3205 macro selects this kind of output.  Though it can be called anywhere
3206 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3207 it right after @code{AC_INIT}.
3209 The package should @samp{#include} the configuration header file before
3210 any other header files, to prevent inconsistencies in declarations (for
3211 example, if it redefines @code{const}).
3213 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3214 option (or @option{-I..}; whichever directory contains @file{config.h}).
3215 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3216 the directory of the currently read file, i.e., the source directory, not
3217 the build directory.
3219 With the appropriate @option{-I} option, you can use
3220 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3221 because in the rare case when the source directory contains another
3222 @file{config.h}, the build directory should be searched first.
3225 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3226 @acindex{CONFIG_HEADERS}
3227 @cvindex HAVE_CONFIG_H
3228 This macro is one of the instantiating macros; see @ref{Configuration
3229 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3230 blank-or-newline-separated list @var{header} containing C preprocessor
3231 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3232 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3233 The usual name for @var{header} is @file{config.h}.
3235 If @var{header} already exists and its contents are identical to what
3236 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3237 making some changes in the configuration without needlessly causing
3238 object files that depend on the header file to be recompiled.
3240 Usually the input file is named @file{@var{header}.in}; however, you can
3241 override the input file name by appending to @var{header} a
3242 colon-separated list of input files.  For example, you might need to make
3243 the input file name acceptable to DOS variants:
3245 @example
3246 AC_CONFIG_HEADERS([config.h:config.hin])
3247 @end example
3249 @end defmac
3251 @defmac AH_HEADER
3252 @ahindex{HEADER}
3253 This macro is defined as the name of the first declared config header
3254 and undefined if no config headers have been declared up to this point.
3255 A third-party macro may, for example, require use of a config header
3256 without invoking AC_CONFIG_HEADERS twice, like this:
3258 @example
3259 AC_CONFIG_COMMANDS_PRE(
3260         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3261 @end example
3263 @end defmac
3265 @xref{Configuration Actions}, for more details on @var{header}.
3267 @menu
3268 * Header Templates::            Input for the configuration headers
3269 * autoheader Invocation::       How to create configuration templates
3270 * Autoheader Macros::           How to specify CPP templates
3271 @end menu
3273 @node Header Templates
3274 @subsection Configuration Header Templates
3275 @cindex Configuration Header Template
3276 @cindex Header templates
3277 @cindex @file{config.h.in}
3279 Your distribution should contain a template file that looks as you want
3280 the final header file to look, including comments, with @code{#undef}
3281 statements which are used as hooks.  For example, suppose your
3282 @file{configure.ac} makes these calls:
3284 @example
3285 AC_CONFIG_HEADERS([conf.h])
3286 AC_CHECK_HEADERS([unistd.h])
3287 @end example
3289 @noindent
3290 Then you could have code like the following in @file{conf.h.in}.
3291 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3292 to 1, if and only if the system has @file{unistd.h}.
3294 @example
3295 @group
3296 /* Define as 1 if you have unistd.h.  */
3297 #undef HAVE_UNISTD_H
3298 @end group
3299 @end example
3301 The format of the template file is stricter than what the C preprocessor
3302 is required to accept.  A directive line should contain only whitespace,
3303 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3304 instead of @samp{#undef}, or of comments on the same line as
3305 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3306 once.  Other preprocessor lines, such as @samp{#ifdef} or
3307 @samp{#include}, are copied verbatim from the template into the
3308 generated header.
3310 Since it is a tedious task to keep a template header up to date, you may
3311 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3313 During the instantiation of the header, each @samp{#undef} line in the
3314 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3315 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3316 been executed during the @command{configure} run, the @samp{#undef} line is
3317 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3318 on many systems, it can be implicitly defined by the compiler, and
3319 undefining it in the header would then break compilation of subsequent
3320 headers.)
3322 Currently, @emph{all} remaining @samp{#undef} lines in the header
3323 template are commented out, whether or not there was a corresponding
3324 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3325 for future releases of Autoconf.
3327 Generally speaking, since you should not use @samp{#define}, and you
3328 cannot guarantee whether a @samp{#undef} directive in the header
3329 template will be converted to a @samp{#define} or commented out in the
3330 generated header file, the template file cannot be used for conditional
3331 definition effects.  Consequently, if you need to use the construct
3333 @example
3334 @group
3335 #ifdef THIS
3336 # define THAT
3337 #endif
3338 @end group
3339 @end example
3341 @noindent
3342 you must place it outside of the template.
3343 If you absolutely need to hook it to the config header itself, please put
3344 the directives to a separate file, and @samp{#include} that file from the
3345 config header template.  If you are using @command{autoheader}, you would
3346 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3349 @node autoheader Invocation
3350 @subsection Using @command{autoheader} to Create @file{config.h.in}
3351 @cindex @command{autoheader}
3353 The @command{autoheader} program can create a template file of C
3354 @samp{#define} statements for @command{configure} to use.
3355 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3356 @file{configure} sources to determine the name of the template.
3357 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3358 input file name, @command{autoheader} uses the first one.)
3360 It is recommended that only one input file is used.  If you want to append
3361 a boilerplate code, it is preferable to use
3362 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3363 File @file{conf_post.h} is not processed during the configuration then,
3364 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3365 prepend a boilerplate code.
3367 In order to do its job, @command{autoheader} needs you to document all
3368 of the symbols that you might use.  Typically this is done via an
3369 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3370 is a literal symbol and whose third argument describes the symbol
3371 (@pxref{Defining Symbols}).  Alternatively, you can use
3372 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3373 suitable input file for a subsequent configuration header file.
3374 Symbols defined by Autoconf's builtin tests are already documented properly;
3375 you need to document only those that you
3376 define yourself.
3378 You might wonder why @command{autoheader} is needed: after all, why
3379 would @command{configure} need to ``patch'' a @file{config.h.in} to
3380 produce a @file{config.h} instead of just creating @file{config.h} from
3381 scratch?  Well, when everything rocks, the answer is just that we are
3382 wasting our time maintaining @command{autoheader}: generating
3383 @file{config.h} directly is all that is needed.  When things go wrong,
3384 however, you'll be thankful for the existence of @command{autoheader}.
3386 The fact that the symbols are documented is important in order to
3387 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3388 well-defined list of symbols that should be defined (or not) is
3389 also important for people who are porting packages to environments where
3390 @command{configure} cannot be run: they just have to @emph{fill in the
3391 blanks}.
3393 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3395 If you give @command{autoheader} an argument, it uses that file instead
3396 of @file{configure.ac} and writes the header file to the standard output
3397 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3398 argument of @option{-}, it reads the standard input instead of
3399 @file{configure.ac} and writes the header file to the standard output.
3401 @command{autoheader} accepts the following options:
3403 @table @option
3404 @item --help
3405 @itemx -h
3406 Print a summary of the command line options and exit.
3408 @item --version
3409 @itemx -V
3410 Print the version number of Autoconf and exit.
3412 @item --verbose
3413 @itemx -v
3414 Report processing steps.
3416 @item --debug
3417 @itemx -d
3418 Don't remove the temporary files.
3420 @item --force
3421 @itemx -f
3422 Remake the template file even if newer than its input files.
3424 @item --include=@var{dir}
3425 @itemx -I @var{dir}
3426 Append @var{dir} to the include path.  Multiple invocations accumulate.
3428 @item --prepend-include=@var{dir}
3429 @itemx -B @var{dir}
3430 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3432 @item --warnings=@var{category}
3433 @itemx -W @var{category}
3434 @evindex WARNINGS
3435 Report the warnings related to @var{category} (which can actually be a
3436 comma separated list).  Current categories include:
3438 @table @samp
3439 @item obsolete
3440 report the uses of obsolete constructs
3442 @item all
3443 report all the warnings
3445 @item none
3446 report none
3448 @item error
3449 treats warnings as errors
3451 @item no-@var{category}
3452 disable warnings falling into @var{category}
3453 @end table
3455 @end table
3459 @node Autoheader Macros
3460 @subsection Autoheader Macros
3461 @cindex Autoheader macros
3463 @command{autoheader} scans @file{configure.ac} and figures out which C
3464 preprocessor symbols it might define.  It knows how to generate
3465 templates for symbols defined by @code{AC_CHECK_HEADERS},
3466 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3467 symbol, you must define a template for it.  If there are missing
3468 templates, @command{autoheader} fails with an error message.
3470 The template for a @var{symbol} is created
3471 by @command{autoheader} from
3472 the @var{description} argument to an @code{AC_DEFINE};
3473 see @ref{Defining Symbols}.
3475 For special needs, you can use the following macros.
3478 @defmac AH_TEMPLATE (@var{key}, @var{description})
3479 @ahindex{TEMPLATE}
3480 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3481 generates standard templates just like @code{AC_DEFINE} when a
3482 @var{description} is given.
3484 For example:
3486 @example
3487 AH_TEMPLATE([CRAY_STACKSEG_END],
3488             [Define to one of _getb67, GETB67, getb67
3489              for Cray-2 and Cray-YMP systems.  This
3490              function is required for alloca.c support
3491              on those systems.])
3492 @end example
3494 @noindent
3495 generates the following template, with the description properly
3496 justified.
3498 @example
3499 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3500    Cray-YMP systems.  This function is required for alloca.c
3501    support on those systems.  */
3502 #undef CRAY_STACKSEG_END
3503 @end example
3504 @end defmac
3507 @defmac AH_VERBATIM (@var{key}, @var{template})
3508 @ahindex{VERBATIM}
3509 Tell @command{autoheader} to include the @var{template} as-is in the header
3510 template file.  This @var{template} is associated with the @var{key},
3511 which is used to sort all the different templates and guarantee their
3512 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3513 @end defmac
3516 @defmac AH_TOP (@var{text})
3517 @ahindex{TOP}
3518 Include @var{text} at the top of the header template file.
3519 @end defmac
3522 @defmac AH_BOTTOM (@var{text})
3523 @ahindex{BOTTOM}
3524 Include @var{text} at the bottom of the header template file.
3525 @end defmac
3528 Please note that @var{text} gets included ``verbatim'' to the template file,
3529 not to the resulting config header, so it can easily get mangled when the
3530 template is processed.  There is rarely a need for something other than
3532 @example
3533 AH_BOTTOM([#include <custom.h>])
3534 @end example
3538 @node Configuration Commands
3539 @section Running Arbitrary Configuration Commands
3540 @cindex Configuration commands
3541 @cindex Commands for configuration
3543 You can execute arbitrary commands before, during, and after
3544 @file{config.status} is run.  The three following macros accumulate the
3545 commands to run when they are called multiple times.
3546 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3547 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3549 @anchor{AC_CONFIG_COMMANDS}
3550 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3551 @acindex{CONFIG_COMMANDS}
3552 Specify additional shell commands to run at the end of
3553 @file{config.status}, and shell commands to initialize any variables
3554 from @command{configure}.  Associate the commands with @var{tag}.
3555 Since typically the @var{cmds} create a file, @var{tag} should
3556 naturally be the name of that file.  If needed, the directory hosting
3557 @var{tag} is created.  This macro is one of the instantiating macros;
3558 see @ref{Configuration Actions}.
3560 Here is an unrealistic example:
3561 @example
3562 fubar=42
3563 AC_CONFIG_COMMANDS([fubar],
3564                    [echo this is extra $fubar, and so on.],
3565                    [fubar=$fubar])
3566 @end example
3568 Here is a better one:
3569 @example
3570 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3571 @end example
3572 @end defmac
3574 The following two macros look similar, but in fact they are not of the same
3575 breed: they are executed directly by @file{configure}, so you cannot use
3576 @file{config.status} to rerun them.
3578 @c Yet it is good to leave them here.  The user sees them together and
3579 @c decides which best fits their needs.
3581 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3582 @acindex{CONFIG_COMMANDS_PRE}
3583 Execute the @var{cmds} right before creating @file{config.status}.
3585 This macro presents the last opportunity to call @code{AC_SUBST},
3586 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3587 @end defmac
3589 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3590 @acindex{CONFIG_COMMANDS_POST}
3591 Execute the @var{cmds} right after creating @file{config.status}.
3592 @end defmac
3597 @node Configuration Links
3598 @section Creating Configuration Links
3599 @cindex Configuration links
3600 @cindex Links for configuration
3602 You may find it convenient to create links whose destinations depend upon
3603 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3604 creation of relative symbolic links can be delicate when the package is
3605 built in a directory different from the source directory.
3607 @anchor{AC_CONFIG_LINKS}
3608 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3609   @ovar{init-cmds})
3610 @acindex{CONFIG_LINKS}
3611 @cindex Links
3612 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3613 the corresponding link name @var{dest}.  Makes a symbolic link if
3614 possible, otherwise a hard link if possible, otherwise a copy.  The
3615 @var{dest} and @var{source} names should be relative to the top level
3616 source or build directory.  This macro is one of the instantiating
3617 macros; see @ref{Configuration Actions}.
3619 For example, this call:
3621 @example
3622 AC_CONFIG_LINKS([host.h:config/$machine.h
3623                 object.h:config/$obj_format.h])
3624 @end example
3626 @noindent
3627 creates in the current directory @file{host.h} as a link to
3628 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3629 link to @file{@var{srcdir}/config/$obj_format.h}.
3631 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3632 impossible for @samp{config.status} to guess the links to establish.
3634 One can then run:
3635 @example
3636 ./config.status host.h object.h
3637 @end example
3638 @noindent
3639 to create the links.
3640 @end defmac
3644 @node Subdirectories
3645 @section Configuring Other Packages in Subdirectories
3646 @cindex Configure subdirectories
3647 @cindex Subdirectory configure
3649 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3650 makefiles in subdirectories.  However, @command{configure} scripts
3651 that control more than one independent package can use
3652 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3653 packages in subdirectories.
3655 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3656 @acindex{CONFIG_SUBDIRS}
3657 @ovindex subdirs
3658 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3659 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3660 be a literal, i.e., please do not use:
3662 @example
3663 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3664 if test "x$package_foo_enabled" = xyes; then
3665   my_subdirs="$my_subdirs foo"
3667 AC_CONFIG_SUBDIRS([$my_subdirs])
3668 @end example
3670 @noindent
3671 because this prevents @samp{./configure --help=recursive} from
3672 displaying the options of the package @code{foo}.  Instead, you should
3673 write:
3675 @example
3676 if test "x$package_foo_enabled" = xyes; then
3677   AC_CONFIG_SUBDIRS([foo])
3679 @end example
3681 If a given @var{dir} is not found at @command{configure} run time, a
3682 warning is reported; if the subdirectory is optional, write:
3684 @example
3685 if test -d "$srcdir/foo"; then
3686   AC_CONFIG_SUBDIRS([foo])
3688 @end example
3690 @c NB: Yes, below we mean configure.in, not configure.ac.
3691 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3692 of @command{configure}.  This is for packages that might use a
3693 non-Autoconf script @command{Configure}, which can't be called through a
3694 wrapper @command{configure} since it would be the same file on
3695 case-insensitive file systems.  Likewise, if a @var{dir} contains
3696 @file{configure.in} but no @command{configure}, the Cygnus
3697 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3699 The subdirectory @command{configure} scripts are given the same command
3700 line options that were given to this @command{configure} script, with minor
3701 changes if needed, which include:
3703 @itemize @minus
3704 @item
3705 adjusting a relative name for the cache file;
3707 @item
3708 adjusting a relative name for the source directory;
3710 @item
3711 propagating the current value of @code{$prefix}, including if it was
3712 defaulted, and if the default values of the top level and of the subdirectory
3713 @file{configure} differ.
3714 @end itemize
3716 This macro also sets the output variable @code{subdirs} to the list of
3717 directories @samp{@var{dir} @dots{}}.  Make rules can use
3718 this variable to determine which subdirectories to recurse into.
3720 This macro may be called multiple times.
3721 @end defmac
3723 @node Default Prefix
3724 @section Default Prefix
3725 @cindex Install prefix
3726 @cindex Prefix for install
3728 By default, @command{configure} sets the prefix for files it installs to
3729 @file{/usr/local}.  The user of @command{configure} can select a different
3730 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3731 There are two ways to change the default: when creating
3732 @command{configure}, and when running it.
3734 Some software packages might want to install in a directory other than
3735 @file{/usr/local} by default.  To accomplish that, use the
3736 @code{AC_PREFIX_DEFAULT} macro.
3738 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3739 @acindex{PREFIX_DEFAULT}
3740 Set the default installation prefix to @var{prefix} instead of
3741 @file{/usr/local}.
3742 @end defmac
3744 It may be convenient for users to have @command{configure} guess the
3745 installation prefix from the location of a related program that they
3746 have already installed.  If you wish to do that, you can call
3747 @code{AC_PREFIX_PROGRAM}.
3749 @anchor{AC_PREFIX_PROGRAM}
3750 @defmac AC_PREFIX_PROGRAM (@var{program})
3751 @acindex{PREFIX_PROGRAM}
3752 If the user did not specify an installation prefix (using the
3753 @option{--prefix} option), guess a value for it by looking for
3754 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3755 is found, set the prefix to the parent of the directory containing
3756 @var{program}, else default the prefix as described above
3757 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3758 @var{program} is @code{gcc} and the @env{PATH} contains
3759 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3760 @end defmac
3764 @c ======================================================== Existing tests
3766 @node Existing Tests
3767 @chapter Existing Tests
3769 These macros test for particular system features that packages might
3770 need or want to use.  If you need to test for a kind of feature that
3771 none of these macros check for, you can probably do it by calling
3772 primitive test macros with appropriate arguments (@pxref{Writing
3773 Tests}).
3775 These tests print messages telling the user which feature they're
3776 checking for, and what they find.  They cache their results for future
3777 @command{configure} runs (@pxref{Caching Results}).
3779 Some of these macros set output variables.  @xref{Makefile
3780 Substitutions}, for how to get their values.  The phrase ``define
3781 @var{name}'' is used below as a shorthand to mean ``define the C
3782 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3783 Symbols}, for how to get those symbol definitions into your program.
3785 @menu
3786 * Common Behavior::             Macros' standard schemes
3787 * Alternative Programs::        Selecting between alternative programs
3788 * Files::                       Checking for the existence of files
3789 * Libraries::                   Library archives that might be missing
3790 * Library Functions::           C library functions that might be missing
3791 * Header Files::                Header files that might be missing
3792 * Declarations::                Declarations that may be missing
3793 * Structures::                  Structures or members that might be missing
3794 * Types::                       Types that might be missing
3795 * Compilers and Preprocessors::  Checking for compiling programs
3796 * System Services::             Operating system services
3797 * Posix Variants::              Special kludges for specific Posix variants
3798 * Erlang Libraries::            Checking for the existence of Erlang libraries
3799 @end menu
3801 @node Common Behavior
3802 @section Common Behavior
3803 @cindex Common autoconf behavior
3805 Much effort has been expended to make Autoconf easy to learn.  The most
3806 obvious way to reach this goal is simply to enforce standard interfaces
3807 and behaviors, avoiding exceptions as much as possible.  Because of
3808 history and inertia, unfortunately, there are still too many exceptions
3809 in Autoconf; nevertheless, this section describes some of the common
3810 rules.
3812 @menu
3813 * Standard Symbols::            Symbols defined by the macros
3814 * Default Includes::            Includes used by the generic macros
3815 @end menu
3817 @node Standard Symbols
3818 @subsection Standard Symbols
3819 @cindex Standard symbols
3821 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3822 their test transform their @var{argument} values to a standard alphabet.
3823 First, @var{argument} is converted to upper case and any asterisks
3824 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3825 that are not alphanumeric are converted to underscores.
3827 For instance,
3829 @example
3830 AC_CHECK_TYPES([struct $Expensive*])
3831 @end example
3833 @noindent
3834 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3835 succeeds.
3838 @node Default Includes
3839 @subsection Default Includes
3840 @cindex Default includes
3841 @cindex Includes, default
3843 Several tests depend upon a set of header files.  Since these headers
3844 are not universally available, tests actually have to provide a set of
3845 protected includes, such as:
3847 @example
3848 @group
3849 #ifdef TIME_WITH_SYS_TIME
3850 # include <sys/time.h>
3851 # include <time.h>
3852 #else
3853 # ifdef HAVE_SYS_TIME_H
3854 #  include <sys/time.h>
3855 # else
3856 #  include <time.h>
3857 # endif
3858 #endif
3859 @end group
3860 @end example
3862 @noindent
3863 Unless you know exactly what you are doing, you should avoid using
3864 unconditional includes, and check the existence of the headers you
3865 include beforehand (@pxref{Header Files}).
3867 Most generic macros use the following macro to provide the default set
3868 of includes:
3870 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3871 @acindex{INCLUDES_DEFAULT}
3872 Expand to @var{include-directives} if defined, otherwise to:
3874 @example
3875 @group
3876 #include <stdio.h>
3877 #ifdef HAVE_SYS_TYPES_H
3878 # include <sys/types.h>
3879 #endif
3880 #ifdef HAVE_SYS_STAT_H
3881 # include <sys/stat.h>
3882 #endif
3883 #ifdef STDC_HEADERS
3884 # include <stdlib.h>
3885 # include <stddef.h>
3886 #else
3887 # ifdef HAVE_STDLIB_H
3888 #  include <stdlib.h>
3889 # endif
3890 #endif
3891 #ifdef HAVE_STRING_H
3892 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3893 #  include <memory.h>
3894 # endif
3895 # include <string.h>
3896 #endif
3897 #ifdef HAVE_STRINGS_H
3898 # include <strings.h>
3899 #endif
3900 #ifdef HAVE_INTTYPES_H
3901 # include <inttypes.h>
3902 #endif
3903 #ifdef HAVE_STDINT_H
3904 # include <stdint.h>
3905 #endif
3906 #ifdef HAVE_UNISTD_H
3907 # include <unistd.h>
3908 #endif
3909 @end group
3910 @end example
3912 If the default includes are used, then check for the presence of these
3913 headers and their compatibility, i.e., you don't need to run
3914 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3916 These headers are checked for in the same order as they are included.
3917 For instance, on some systems @file{string.h} and @file{strings.h} both
3918 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3919 @code{HAVE_STRINGS_H}.
3920 @end defmac
3922 @node Alternative Programs
3923 @section Alternative Programs
3924 @cindex Programs, checking
3926 These macros check for the presence or behavior of particular programs.
3927 They are used to choose between several alternative programs and to
3928 decide what to do once one has been chosen.  If there is no macro
3929 specifically defined to check for a program you need, and you don't need
3930 to check for any special properties of it, then you can use one of the
3931 general program-check macros.
3933 @menu
3934 * Particular Programs::         Special handling to find certain programs
3935 * Generic Programs::            How to find other programs
3936 @end menu
3938 @node Particular Programs
3939 @subsection Particular Program Checks
3941 These macros check for particular programs---whether they exist, and
3942 in some cases whether they support certain features.
3944 @defmac AC_PROG_AWK
3945 @acindex{PROG_AWK}
3946 @ovindex AWK
3947 @caindex prog_AWK
3948 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3949 order, and set output variable @code{AWK} to the first one that is found.
3950 It tries @code{gawk} first because that is reported to be the
3951 best implementation.  The result can be overridden by setting the
3952 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
3954 Using this macro is sufficient to avoid the pitfalls of traditional
3955 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
3956 @end defmac
3958 @defmac AC_PROG_GREP
3959 @acindex{PROG_GREP}
3960 @ovindex GREP
3961 @caindex prog_GREP
3962 Look for the best available @code{grep} or @code{ggrep} that accepts the
3963 longest input lines possible, and that supports multiple @option{-e} options.
3964 Set the output variable @code{GREP} to whatever is chosen.
3965 @xref{grep, , Limitations of Usual Tools}, for more information about
3966 portability problems with the @command{grep} command family.  The result
3967 can be overridden by setting the @code{GREP} variable and is cached in the
3968 @code{ac_cv_path_GREP} variable.
3969 @end defmac
3971 @defmac AC_PROG_EGREP
3972 @acindex{PROG_EGREP}
3973 @ovindex EGREP
3974 @caindex prog_EGREP
3975 Check whether @code{$GREP -E} works, or else look for the best available
3976 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3977 Set the output variable @code{EGREP} to whatever is chosen.  The result
3978 can be overridden by setting the @code{EGREP} variable and is cached in the
3979 @code{ac_cv_path_EGREP} variable.
3980 @end defmac
3982 @defmac AC_PROG_FGREP
3983 @acindex{PROG_FGREP}
3984 @ovindex FGREP
3985 @caindex prog_FGREP
3986 Check whether @code{$GREP -F} works, or else look for the best available
3987 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3988 Set the output variable @code{FGREP} to whatever is chosen.  The result
3989 can be overridden by setting the @code{FGREP} variable and is cached in the
3990 @code{ac_cv_path_FGREP} variable.
3991 @end defmac
3993 @defmac AC_PROG_INSTALL
3994 @acindex{PROG_INSTALL}
3995 @ovindex INSTALL
3996 @ovindex INSTALL_PROGRAM
3997 @ovindex INSTALL_DATA
3998 @ovindex INSTALL_SCRIPT
3999 @caindex path_install
4000 Set output variable @code{INSTALL} to the name of a BSD-compatible
4001 @command{install} program, if one is found in the current @env{PATH}.
4002 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4003 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4004 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4005 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4006 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4008 @samp{@@INSTALL@@} is special, as its value may vary for different
4009 configuration files.
4011 This macro screens out various instances of @command{install} known not to
4012 work.  It prefers to find a C program rather than a shell script, for
4013 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4014 but that name is obsolete because some @command{make} programs have a rule
4015 that creates @file{install} from it if there is no makefile.  Further, this
4016 macro requires @command{install} to be able to install multiple files into a
4017 target directory in a single invocation.
4019 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4020 you use @code{AC_PROG_INSTALL}, you must include either
4021 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4022 @command{configure} produces an error message saying it can't find
4023 them---even if the system you're on has a good @command{install} program.
4024 This check is a safety measure to prevent you from accidentally leaving
4025 that file out, which would prevent your package from installing on
4026 systems that don't have a BSD-compatible @command{install} program.
4028 If you need to use your own installation program because it has features
4029 not found in standard @command{install} programs, there is no reason to use
4030 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4031 @file{Makefile.in} files.
4033 The result of the test can be overridden by setting the variable
4034 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4035 @end defmac
4037 @defmac AC_PROG_MKDIR_P
4038 @acindex{PROG_MKDIR_P}
4039 @ovindex MKDIR_P
4040 @caindex path_mkdir
4041 Set output variable @code{MKDIR_P} to a program that ensures that for
4042 each argument, a directory named by this argument exists, creating it
4043 and its parent directories if needed, and without race conditions when
4044 two instances of the program attempt to make the same directory at
4045 nearly the same time.
4047 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4048 falls back on invoking @command{install-sh} with the @option{-d} option,
4049 so your package should
4050 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4051 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4052 is vulnerable to race conditions, so if you want to support parallel
4053 installs from
4054 different packages into the same directory you need to make sure you
4055 have an up-to-date @file{install-sh}.  In particular, be careful about
4056 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4058 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4059 in M4sh}), but it sets an output variable intended for use in other
4060 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4061 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4062 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4063 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4064 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4065 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4066 Finally, @code{AS_MKDIR_P} does not check for race condition
4067 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4069 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4070 configuration files.
4072 The result of the test can be overridden by setting the variable
4073 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4074 @end defmac
4076 @anchor{AC_PROG_LEX}
4077 @defmac AC_PROG_LEX
4078 @acindex{PROG_LEX}
4079 @ovindex LEX
4080 @ovindex LEXLIB
4081 @cvindex YYTEXT_POINTER
4082 @ovindex LEX_OUTPUT_ROOT
4083 @caindex prog_LEX
4084 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4085 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4086 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4087 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4088 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4089 alongside the source @file{file.l}, this default allows users without a
4090 lexer generator to still build the package even if the timestamp for
4091 @file{file.l} is inadvertantly changed.
4093 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4094 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4095 the base of the file name that the lexer generates; usually
4096 @file{lex.yy}, but sometimes something else.  These results vary
4097 according to whether @code{lex} or @code{flex} is being used.
4099 You are encouraged to use Flex in your sources, since it is both more
4100 pleasant to use than plain Lex and the C source it produces is portable.
4101 In order to ensure portability, however, you must either provide a
4102 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4103 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4104 statement in the scanner's source.  Once this done, the scanner is
4105 portable (unless @emph{you} felt free to use nonportable constructs) and
4106 does not depend on any library.  In this case, and in this case only, it
4107 is suggested that you use this Autoconf snippet:
4109 @example
4110 AC_PROG_LEX
4111 if test "x$LEX" != xflex; then
4112   LEX="$SHELL $missing_dir/missing flex"
4113   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4114   AC_SUBST([LEXLIB], [''])
4116 @end example
4118 The shell script @command{missing} can be found in the Automake
4119 distribution.
4121 Remember that the user may have supplied an alternate location in
4122 @env{LEX}, so if Flex is required, it is better to check that the user
4123 provided something sufficient by parsing the output of @samp{$LEX
4124 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4126 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4127 (indirectly) this macro twice, which causes an annoying but benign
4128 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4129 of Automake will fix this issue; meanwhile, just ignore this message.
4131 As part of running the test, this macro may delete any file in the
4132 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4134 The result of this test can be influenced by setting the variable
4135 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4136 @end defmac
4138 @anchor{AC_PROG_LN_S}
4139 @defmac AC_PROG_LN_S
4140 @acindex{PROG_LN_S}
4141 @ovindex LN_S
4142 If @samp{ln -s} works on the current file system (the operating system
4143 and file system support symbolic links), set the output variable
4144 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4145 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
4147 If you make a link in a directory other than the current directory, its
4148 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4149 create links using @samp{$(LN_S)}, either find out which form is used
4150 and adjust the arguments, or always invoke @code{ln} in the directory
4151 where the link is to be created.
4153 In other words, it does not work to do:
4154 @example
4155 $(LN_S) foo /x/bar
4156 @end example
4158 Instead, do:
4160 @example
4161 (cd /x && $(LN_S) foo bar)
4162 @end example
4163 @end defmac
4165 @defmac AC_PROG_RANLIB
4166 @acindex{PROG_RANLIB}
4167 @ovindex RANLIB
4168 @c @caindex prog_RANLIB
4169 @c @caindex prog_ac_ct_RANLIB
4170 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4171 is found, and otherwise to @samp{:} (do nothing).
4172 @end defmac
4174 @defmac AC_PROG_SED
4175 @acindex{PROG_SED}
4176 @ovindex SED
4177 @caindex path_SED
4178 Set output variable @code{SED} to a Sed implementation that conforms to
4179 Posix and does not have arbitrary length limits.  Report an error if no
4180 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4181 information about portability problems with Sed.
4183 The result of this test can be overridden by setting the @code{SED} variable
4184 and is cached in the @code{ac_cv_path_SED} variable.
4185 @end defmac
4187 @defmac AC_PROG_YACC
4188 @acindex{PROG_YACC}
4189 @evindex YACC
4190 @evindex YFLAGS
4191 @ovindex YACC
4192 @caindex prog_YACC
4193 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4194 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4195 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4196 The result of this test can be influenced by setting the variable
4197 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4198 @end defmac
4200 @node Generic Programs
4201 @subsection Generic Program and File Checks
4203 These macros are used to find programs not covered by the ``particular''
4204 test macros.  If you need to check the behavior of a program as well as
4205 find out whether it is present, you have to write your own test for it
4206 (@pxref{Writing Tests}).  By default, these macros use the environment
4207 variable @env{PATH}.  If you need to check for a program that might not
4208 be in the user's @env{PATH}, you can pass a modified path to use
4209 instead, like this:
4211 @example
4212 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4213              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4214 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4215 @end example
4217 You are strongly encouraged to declare the @var{variable} passed to
4218 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4219 @code{AC_ARG_VAR}, for more details.
4221 @anchor{AC_CHECK_PROG}
4222 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4223   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4224   @ovar{reject})
4225 @acindex{CHECK_PROG}
4226 @caindex prog_@var{variable}
4227 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4228 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4229 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4230 absolute file name) even if it is the first found in the search path; in
4231 that case, set @var{variable} using the absolute file name of the
4232 @var{prog-to-check-for} found that is not @var{reject}.  If
4233 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4234 @var{variable}.  The result of this test can be overridden by setting the
4235 @var{variable} variable or the cache variable
4236 @code{ac_cv_prog_@var{variable}}.
4237 @end defmac
4239 @anchor{AC_CHECK_PROGS}
4240 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4241   @ovar{value-if-not-found}, @dvar{path, $PATH})
4242 @acindex{CHECK_PROGS}
4243 @caindex prog_@var{variable}
4244 Check for each program in the blank-separated list
4245 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4246 @var{variable} to the name of that program.  Otherwise, continue
4247 checking the next program in the list.  If none of the programs in the
4248 list are found, set @var{variable} to @var{value-if-not-found}; if
4249 @var{value-if-not-found} is not specified, the value of @var{variable}
4250 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4251 this test can be overridden by setting the @var{variable} variable or the
4252 cache variable @code{ac_cv_prog_@var{variable}}.
4253 @end defmac
4255 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4256   @ovar{value-if-not-found}, @dvar{path, $PATH})
4257 @acindex{CHECK_TARGET_TOOL}
4258 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4259 with a prefix of the target type as determined by
4260 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4261 If the tool cannot be found with a prefix, and if the build and target
4262 types are equal, then it is also searched for without a prefix.
4264 As noted in @ref{Specifying Target Triplets}, the
4265 target is rarely specified, because most of the time it is the same
4266 as the host: it is the type of system for which any compiler tool in
4267 the package produces code.  What this macro looks for is,
4268 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4269 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4270 uses to produce objects, archives or executables}.
4271 @end defmac
4273 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4274   @ovar{value-if-not-found}, @dvar{path, $PATH})
4275 @acindex{CHECK_TOOL}
4276 @c @caindex prog_@var{VARIABLE}
4277 @c @caindex prog_ac_ct_@var{VARIABLE}
4278 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4279 with a prefix of the host type as specified by @option{--host}, followed by a
4280 dash.  For example, if the user runs
4281 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4282 @example
4283 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4284 @end example
4285 @noindent
4286 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4287 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4288 @var{path}, or to @samp{:} if neither program exists.
4290 When cross-compiling, this macro will issue a warning if no program
4291 prefixed with the host type could be found.
4292 For more information, see @ref{Specifying Target Triplets}.
4293 @end defmac
4295 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4296   @ovar{value-if-not-found}, @dvar{path, $PATH})
4297 @acindex{CHECK_TARGET_TOOLS}
4298 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4299 @var{progs-to-check-for} are checked with a prefix of the target type as
4300 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4301 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4302 prefix, and if the build and target types are equal, then the first one
4303 without a prefix is used.  If a tool is found, set @var{variable} to
4304 the name of that program.  If none of the tools in the list are found,
4305 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4306 is not specified, the value of @var{variable} is not changed.  Calls
4307 @code{AC_SUBST} for @var{variable}.
4308 @end defmac
4310 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4311   @ovar{value-if-not-found}, @dvar{path, $PATH})
4312 @acindex{CHECK_TOOLS}
4313 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4314 @var{progs-to-check-for} are checked with a prefix of the host type as
4315 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4316 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4317 prefix, then the first one without a prefix is used.  If a tool is found,
4318 set @var{variable} to the name of that program.  If none of the tools in
4319 the list are found, set @var{variable} to @var{value-if-not-found}; if
4320 @var{value-if-not-found} is not specified, the value of @var{variable}
4321 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4323 When cross-compiling, this macro will issue a warning if no program
4324 prefixed with the host type could be found.
4325 For more information, see @ref{Specifying Target Triplets}.
4326 @end defmac
4328 @anchor{AC_PATH_PROG}
4329 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4330   @ovar{value-if-not-found}, @dvar{path, $PATH})
4331 @acindex{PATH_PROG}
4332 @caindex path_@var{variable}
4333 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4334 name of @var{prog-to-check-for} if found.  The result of this test
4335 can be overridden by setting the @var{variable} variable.  A positive
4336 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4337 variable.
4338 @end defmac
4340 @anchor{AC_PATH_PROGS}
4341 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4342   @ovar{value-if-not-found}, @dvar{path, $PATH})
4343 @acindex{PATH_PROGS}
4344 @caindex path_@var{variable}
4345 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4346 are found, set @var{variable} to the absolute name of the program
4347 found.  The result of this test can be overridden by setting the
4348 @var{variable} variable.  A positive result of this test is cached in
4349 the @code{ac_cv_path_@var{variable}} variable.
4350 @end defmac
4352 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4353   @var{progs-to-check-for}, @var{feature-test}, @
4354   @ovar{action-if-not-found}, @dvar{path, $PATH})
4355 @acindex{PATH_PROGS_FEATURE_CHECK}
4356 @caindex path_@var{variable}
4357 @vrindex ac_path_@var{variable}
4358 @vrindex ac_path_@var{variable}_found
4359 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4360 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4361 its value.  Otherwise, check for each program in the blank-separated
4362 list @var{progs-to-check-for} existing in @var{path}.  For each program
4363 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4364 set to the absolute name of the candidate program.  If no invocation of
4365 @var{feature-test} sets the shell variable
4366 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4367 executed.  @var{feature-test} will be run even when
4368 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4369 choose a better candidate found later in @var{path}; to accept the
4370 current setting and bypass all futher checks, @var{feature-test} can
4371 execute @code{ac_path_@var{variable}_found=:}.
4373 Note that this macro has some subtle differences from
4374 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4375 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4376 particular, @var{variable} is not set to the final value of
4377 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4378 run.  Also, on failure, any action can be performed, whereas
4379 @code{AC_CHECK_PROGS} only performs
4380 @code{@var{variable}=@var{value-if-not-found}}.
4382 Here is an example, similar to what Autoconf uses in its own configure
4383 script.  It will search for an implementation of @command{m4} that
4384 supports the @code{indir} builtin, even if it goes by the name
4385 @command{gm4} or is not the first implementation on @env{PATH}.
4387 @example
4388 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4389   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4390     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4391       test "x$m4out" = x0 \
4392       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4393     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4394 AC_SUBST([M4], [$ac_cv_path_M4])
4395 @end example
4396 @end defmac
4398 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4399   @ovar{value-if-not-found}, @dvar{path, $PATH})
4400 @acindex{PATH_TARGET_TOOL}
4401 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4402 name of the program if it is found.
4403 @end defmac
4405 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4406   @ovar{value-if-not-found}, @dvar{path, $PATH})
4407 @acindex{PATH_TOOL}
4408 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4409 name of the program if it is found.
4411 When cross-compiling, this macro will issue a warning if no program
4412 prefixed with the host type could be found.
4413 For more information, see @ref{Specifying Target Triplets}.
4414 @end defmac
4417 @node Files
4418 @section Files
4419 @cindex File, checking
4421 You might also need to check for the existence of files.  Before using
4422 these macros, ask yourself whether a runtime test might not be a better
4423 solution.  Be aware that, like most Autoconf macros, they test a feature
4424 of the host machine, and therefore, they die when cross-compiling.
4426 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4427   @ovar{action-if-not-found})
4428 @acindex{CHECK_FILE}
4429 @caindex file_@var{file}
4430 Check whether file @var{file} exists on the native system.  If it is
4431 found, execute @var{action-if-found}, otherwise do
4432 @var{action-if-not-found}, if given.  The result of this test is cached
4433 in the @code{ac_cv_file_@var{file}} variable, with characters not
4434 suitable for a variable name mapped to underscores.
4435 @end defmac
4437 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4438   @ovar{action-if-not-found})
4439 @acindex{CHECK_FILES}
4440 @caindex file_@var{file}
4441 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4442 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4443 for each file found.  The results of each test are cached in the
4444 @code{ac_cv_file_@var{file}} variable, with characters not suitable for
4445 a variable name mapped to underscores.
4446 @end defmac
4449 @node Libraries
4450 @section Library Files
4451 @cindex Library, checking
4453 The following macros check for the presence of certain C, C++, Fortran,
4454 or Go library archive files.
4456 @anchor{AC_CHECK_LIB}
4457 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4458   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4459 @acindex{CHECK_LIB}
4460 @caindex lib_@var{library}_@var{function}
4461 Test whether the library @var{library} is available by trying to link
4462 a test program that calls function @var{function} with the library.
4463 @var{function} should be a function provided by the library.
4464 Use the base
4465 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4466 the @var{library} argument.
4468 @var{action-if-found} is a list of shell commands to run if the link
4469 with the library succeeds; @var{action-if-not-found} is a list of shell
4470 commands to run if the link fails.  If @var{action-if-found} is not
4471 specified, the default action prepends @option{-l@var{library}} to
4472 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4473 capitals).  This macro is intended to support building @code{LIBS} in
4474 a right-to-left (least-dependent to most-dependent) fashion such that
4475 library dependencies are satisfied as a natural side effect of
4476 consecutive tests.  Linkers are sensitive to library ordering
4477 so the order in which @code{LIBS} is generated is important to reliable
4478 detection of libraries.
4480 If linking with @var{library} results in unresolved symbols that would
4481 be resolved by linking with additional libraries, give those libraries
4482 as the @var{other-libraries} argument, separated by spaces:
4483 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4484 that @var{library} is present, because linking the test program can
4485 fail with unresolved symbols.  The @var{other-libraries} argument
4486 should be limited to cases where it is desirable to test for one library
4487 in the presence of another that is not already in @code{LIBS}.
4489 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4490 in some common cases.  Many standard functions like @code{gethostbyname}
4491 appear in the standard C library on some hosts, and in special libraries
4492 like @code{nsl} on other hosts.  On some hosts the special libraries
4493 contain variant implementations that you may not want to use.  These
4494 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4495 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4497 The result of this test is cached in the
4498 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4499 @end defmac
4501 @anchor{AC_SEARCH_LIBS}
4502 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4503   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4504 @acindex{SEARCH_LIBS}
4505 @caindex search_@var{function}
4506 Search for a library defining @var{function} if it's not already
4507 available.  This equates to calling
4508 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4509 no libraries, then for each library listed in @var{search-libs}.
4511 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4512 to contain @var{function}, and run @var{action-if-found}.  If the
4513 function is not found, run @var{action-if-not-found}.
4515 If linking with @var{library} results in unresolved symbols that would
4516 be resolved by linking with additional libraries, give those libraries
4517 as the @var{other-libraries} argument, separated by spaces:
4518 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4519 that @var{function} is present, because linking the test program
4520 always fails with unresolved symbols.
4522 The result of this test is cached in the
4523 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4524 @var{function} is already available, as @samp{no} if no library
4525 containing @var{function} was found, otherwise as the
4526 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4527 @end defmac
4531 @node Library Functions
4532 @section Library Functions
4534 The following macros check for particular C library functions.
4535 If there is no macro specifically defined to check for a function you need,
4536 and you don't need to check for any special properties of
4537 it, then you can use one of the general function-check macros.
4539 @menu
4540 * Function Portability::        Pitfalls with usual functions
4541 * Particular Functions::        Special handling to find certain functions
4542 * Generic Functions::           How to find other functions
4543 @end menu
4545 @node Function Portability
4546 @subsection Portability of C Functions
4547 @cindex Portability of C functions
4548 @cindex C function portability
4550 Most usual functions can either be missing, or be buggy, or be limited
4551 on some architectures.  This section tries to make an inventory of these
4552 portability issues.  By definition, this list always requires
4553 additions.  A much more complete list is maintained by the Gnulib
4554 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4555 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4556 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4557 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4558 help us keep the gnulib list as complete as possible.
4560 @table @asis
4561 @item @code{exit}
4562 @c @fuindex exit
4563 @prindex @code{exit}
4564 On ancient hosts, @code{exit} returned @code{int}.
4565 This is because @code{exit} predates @code{void}, and there was a long
4566 tradition of it returning @code{int}.
4568 On current hosts, the problem more likely is that @code{exit} is not
4569 declared, due to C++ problems of some sort or another.  For this reason
4570 we suggest that test programs not invoke @code{exit}, but return from
4571 @code{main} instead.
4573 @item @code{free}
4574 @c @fuindex free
4575 @prindex @code{free}
4576 The C standard says a call @code{free (NULL)} does nothing, but
4577 some old systems don't support this (e.g., NextStep).
4579 @item @code{isinf}
4580 @itemx @code{isnan}
4581 @c @fuindex isinf
4582 @c @fuindex isnan
4583 @prindex @code{isinf}
4584 @prindex @code{isnan}
4585 The C99 standard says that @code{isinf} and @code{isnan} are
4586 macros.  On some systems just macros are available
4587 (e.g., HP-UX and Solaris 10), on
4588 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4589 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4590 these functions are declared in nonstandard headers like
4591 @code{<sunmath.h>} and defined in non-default libraries like
4592 @option{-lm} or @option{-lsunmath}.
4594 The C99 @code{isinf} and @code{isnan} macros work correctly with
4595 @code{long double} arguments, but pre-C99 systems that use functions
4596 typically assume @code{double} arguments.  On such a system,
4597 @code{isinf} incorrectly returns true for a finite @code{long double}
4598 argument that is outside the range of @code{double}.
4600 The best workaround for these issues is to use gnulib modules
4601 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4602 solution involves code like the following.
4604 @smallexample
4605 #include <math.h>
4607 #ifndef isnan
4608 # define isnan(x) \
4609     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4610      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4611      : isnan_f (x))
4612 static inline int isnan_f  (float       x) @{ return x != x; @}
4613 static inline int isnan_d  (double      x) @{ return x != x; @}
4614 static inline int isnan_ld (long double x) @{ return x != x; @}
4615 #endif
4617 #ifndef isinf
4618 # define isinf(x) \
4619     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4620      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4621      : isinf_f (x))
4622 static inline int isinf_f  (float       x)
4623 @{ return !isnan (x) && isnan (x - x); @}
4624 static inline int isinf_d  (double      x)
4625 @{ return !isnan (x) && isnan (x - x); @}
4626 static inline int isinf_ld (long double x)
4627 @{ return !isnan (x) && isnan (x - x); @}
4628 #endif
4629 @end smallexample
4631 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4632 compilers that lack the @code{inline} keyword.  Some optimizing
4633 compilers mishandle these definitions, but systems with that bug
4634 typically have many other floating point corner-case compliance problems
4635 anyway, so it's probably not worth worrying about.
4637 @item @code{malloc}
4638 @c @fuindex malloc
4639 @prindex @code{malloc}
4640 The C standard says a call @code{malloc (0)} is implementation
4641 dependent.  It can return either @code{NULL} or a new non-null pointer.
4642 The latter is more common (e.g., the GNU C Library) but is by
4643 no means universal.  @code{AC_FUNC_MALLOC}
4644 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4646 @item @code{putenv}
4647 @c @fuindex putenv
4648 @prindex @code{putenv}
4649 Posix prefers @code{setenv} to @code{putenv}; among other things,
4650 @code{putenv} is not required of all Posix implementations, but
4651 @code{setenv} is.
4653 Posix specifies that @code{putenv} puts the given string directly in
4654 @code{environ}, but some systems make a copy of it instead (e.g.,
4655 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4656 not free it, causing a memory leak (e.g., FreeBSD 4).
4658 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4659 environment, but this is not standard usage and it dumps core
4660 on some systems (e.g., AIX).
4662 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4663 environment, rather than inserting it with an empty value.
4665 @item @code{realloc}
4666 @c @fuindex realloc
4667 @prindex @code{realloc}
4668 The C standard says a call @code{realloc (NULL, size)} is equivalent
4669 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4670 NextStep).
4672 @item @code{signal} handler
4673 @c @fuindex signal
4674 @prindex @code{signal}
4675 @prindex @code{sigaction}
4676 Normally @code{signal} takes a handler function with a return type of
4677 @code{void}, but some old systems required @code{int} instead.  Any
4678 actual @code{int} value returned is not used; this is only a
4679 difference in the function prototype demanded.
4681 All systems we know of in current use return @code{void}.  The
4682 @code{int} was to support K&R C, where of course @code{void} is not
4683 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4684 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4685 all cases.
4687 In most cases, it is more robust to use @code{sigaction} when it is
4688 available, rather than @code{signal}.
4690 @item @code{snprintf}
4691 @c @fuindex snprintf
4692 @prindex @code{snprintf}
4693 @c @fuindex vsnprintf
4694 @prindex @code{vsnprintf}
4695 The C99 standard says that if the output array isn't big enough
4696 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4697 truncate the output and return the number of bytes that ought to have
4698 been produced.  Some older systems return the truncated length (e.g.,
4699 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4700 (e.g., earlier GNU C Library versions), and some the buffer
4701 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4702 older systems ignore the length and overrun the buffer (e.g., 64-bit
4703 Solaris 7).
4705 @item @code{sprintf}
4706 @c @fuindex sprintf
4707 @prindex @code{sprintf}
4708 @c @fuindex vsprintf
4709 @prindex @code{vsprintf}
4710 The C standard says @code{sprintf} and @code{vsprintf} return the
4711 number of bytes written.  On some ancient systems (SunOS 4 for
4712 instance) they return the buffer pointer instead, but these no
4713 longer need to be worried about.
4715 @item @code{sscanf}
4716 @c @fuindex sscanf
4717 @prindex @code{sscanf}
4718 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4719 that its
4720 input string be writable (though it doesn't actually change it).  This
4721 can be a problem when using @command{gcc} since it normally puts
4722 constant strings in read-only memory (@pxref{Incompatibilities,
4723 Incompatibilities of GCC, , gcc, Using and
4724 Porting the GNU Compiler Collection}).  Apparently in some cases even
4725 having format strings read-only can be a problem.
4727 @item @code{strerror_r}
4728 @c @fuindex strerror_r
4729 @prindex @code{strerror_r}
4730 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4731 systems (e.g., GNU C Library version 2.2.4) provide a
4732 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4733 can detect which is in use (@pxref{Particular Functions}).
4735 @item @code{strnlen}
4736 @c @fuindex strnlen
4737 @prindex @code{strnlen}
4738 AIX 4.3 provides a broken version which produces the
4739 following results:
4741 @example
4742 strnlen ("foobar", 0) = 0
4743 strnlen ("foobar", 1) = 3
4744 strnlen ("foobar", 2) = 2
4745 strnlen ("foobar", 3) = 1
4746 strnlen ("foobar", 4) = 0
4747 strnlen ("foobar", 5) = 6
4748 strnlen ("foobar", 6) = 6
4749 strnlen ("foobar", 7) = 6
4750 strnlen ("foobar", 8) = 6
4751 strnlen ("foobar", 9) = 6
4752 @end example
4754 @item @code{sysconf}
4755 @c @fuindex sysconf
4756 @prindex @code{sysconf}
4757 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4758 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4759 @code{#ifdef}.
4761 @item @code{unlink}
4762 @c @fuindex unlink
4763 @prindex @code{unlink}
4764 The Posix spec says that @code{unlink} causes the given file to be
4765 removed only after there are no more open file handles for it.  Some
4766 non-Posix hosts have trouble with this requirement, though,
4767 and some DOS variants even corrupt the file system.
4769 @item @code{unsetenv}
4770 @c @fuindex unsetenv
4771 @prindex @code{unsetenv}
4772 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4773 can be removed with a call @code{putenv ("FOO=")}, as described under
4774 @code{putenv} above.
4776 @item @code{va_copy}
4777 @c @fuindex va_copy
4778 @prindex @code{va_copy}
4779 The C99 standard provides @code{va_copy} for copying
4780 @code{va_list} variables.  It may be available in older environments
4781 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4782 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4783 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4784 portability.
4786 @item @code{va_list}
4787 @c @fuindex va_list
4788 @prindex @code{va_list}
4789 @code{va_list} is not necessarily just a pointer.  It can be a
4790 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4791 not portable.  Or it can be an array (e.g., @command{gcc} in some
4792 PowerPC configurations), which means as a function parameter it can be
4793 effectively call-by-reference and library routines might modify the
4794 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4795 2.1).
4797 @item Signed @code{>>}
4798 Normally the C @code{>>} right shift of a signed type replicates the
4799 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4800 taken since Standard C doesn't require that behavior.  On those
4801 few processors without a native arithmetic shift (for instance Cray
4802 vector systems) zero bits may be shifted in, the same as a shift of an
4803 unsigned type.
4805 @item Integer @code{/}
4806 C divides signed integers by truncating their quotient toward zero,
4807 yielding the same result as Fortran.  However, before C99 the standard
4808 allowed C implementations to take the floor or ceiling of the quotient
4809 in some cases.  Hardly any implementations took advantage of this
4810 freedom, though, and it's probably not worth worrying about this issue
4811 nowadays.
4812 @end table
4815 @node Particular Functions
4816 @subsection Particular Function Checks
4817 @cindex Function, checking
4819 These macros check for particular C functions---whether they exist, and
4820 in some cases how they respond when given certain arguments.
4822 @anchor{AC_FUNC_ALLOCA}
4823 @defmac AC_FUNC_ALLOCA
4824 @acindex{FUNC_ALLOCA}
4825 @cvindex C_ALLOCA
4826 @cvindex HAVE_ALLOCA_H
4827 @ovindex ALLOCA
4828 @c @fuindex alloca
4829 @prindex @code{alloca}
4830 @hdrindex{alloca.h}
4831 @c @caindex working_alloca_h
4832 Check how to get @code{alloca}.  Tries to get a builtin version by
4833 checking for @file{alloca.h} or the predefined C preprocessor macros
4834 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4835 it defines @code{HAVE_ALLOCA_H}.
4837 If those attempts fail, it looks for the function in the standard C
4838 library.  If any of those methods succeed, it defines
4839 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4840 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4841 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4842 garbage collect).  This variable is separate from @code{LIBOBJS} so
4843 multiple programs can share the value of @code{ALLOCA} without needing
4844 to create an actual library, in case only some of them use the code in
4845 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4846 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4848 This macro does not try to get @code{alloca} from the System V R3
4849 @file{libPW} or the System V R4 @file{libucb} because those libraries
4850 contain some incompatible functions that cause trouble.  Some versions
4851 do not even contain @code{alloca} or contain a buggy version.  If you
4852 still want to use their @code{alloca}, use @code{ar} to extract
4853 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4855 Source files that use @code{alloca} should start with a piece of code
4856 like the following, to declare it properly.
4858 @example
4859 @group
4860 #ifdef STDC_HEADERS
4861 # include <stdlib.h>
4862 # include <stddef.h>
4863 #else
4864 # ifdef HAVE_STDLIB_H
4865 #  include <stdlib.h>
4866 # endif
4867 #endif
4868 #ifdef HAVE_ALLOCA_H
4869 # include <alloca.h>
4870 #elif defined __GNUC__
4871 # define alloca __builtin_alloca
4872 #elif defined _AIX
4873 # define alloca __alloca
4874 #elif defined _MSC_VER
4875 # include <malloc.h>
4876 # define alloca _alloca
4877 #else
4878 # ifndef HAVE_ALLOCA
4879 #  ifdef  __cplusplus
4880 extern "C"
4881 #  endif
4882 void *alloca (size_t);
4883 # endif
4884 #endif
4885 @end group
4886 @end example
4887 @end defmac
4889 @defmac AC_FUNC_CHOWN
4890 @acindex{FUNC_CHOWN}
4891 @cvindex HAVE_CHOWN
4892 @c @fuindex chown
4893 @prindex @code{chown}
4894 @caindex func_chown_works
4895 If the @code{chown} function is available and works (in particular, it
4896 should accept @option{-1} for @code{uid} and @code{gid}), define
4897 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4898 @code{ac_cv_func_chown_works} variable.
4899 @end defmac
4901 @anchor{AC_FUNC_CLOSEDIR_VOID}
4902 @defmac AC_FUNC_CLOSEDIR_VOID
4903 @acindex{FUNC_CLOSEDIR_VOID}
4904 @cvindex CLOSEDIR_VOID
4905 @c @fuindex closedir
4906 @prindex @code{closedir}
4907 @caindex func_closedir_void
4908 If the @code{closedir} function does not return a meaningful value,
4909 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4910 return value for an error indicator.
4912 Currently this test is implemented by running a test program.  When
4913 cross compiling the pessimistic assumption that @code{closedir} does not
4914 return a meaningful value is made.
4916 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4917 variable.
4919 This macro is obsolescent, as @code{closedir} returns a meaningful value
4920 on current systems.  New programs need not use this macro.
4921 @end defmac
4923 @defmac AC_FUNC_ERROR_AT_LINE
4924 @acindex{FUNC_ERROR_AT_LINE}
4925 @c @fuindex error_at_line
4926 @prindex @code{error_at_line}
4927 @caindex lib_error_at_line
4928 If the @code{error_at_line} function is not found, require an
4929 @code{AC_LIBOBJ} replacement of @samp{error}.
4931 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4932 variable.
4934 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4935 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4936 @end defmac
4938 @defmac AC_FUNC_FNMATCH
4939 @acindex{FUNC_FNMATCH}
4940 @c @fuindex fnmatch
4941 @prindex @code{fnmatch}
4942 @caindex func_fnmatch_works
4943 If the @code{fnmatch} function conforms to Posix, define
4944 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4945 the bugs in Solaris 2.4.
4947 Unlike the other specific
4948 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4949 broken/missing @code{fnmatch}.  This is for historical reasons.
4950 See @code{AC_REPLACE_FNMATCH} below.
4952 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
4953 variable.
4955 This macro is obsolescent.  New programs should use Gnulib's
4956 @code{fnmatch-posix} module.  @xref{Gnulib}.
4957 @end defmac
4959 @defmac AC_FUNC_FNMATCH_GNU
4960 @acindex{FUNC_FNMATCH_GNU}
4961 @c @fuindex fnmatch
4962 @prindex @code{fnmatch}
4963 @caindex func_fnmatch_gnu
4964 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4965 whether @code{fnmatch} supports GNU extensions.  Detect common
4966 implementation bugs, for example, the bugs in the GNU C
4967 Library 2.1.
4969 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
4970 variable.
4972 This macro is obsolescent.  New programs should use Gnulib's
4973 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4974 @end defmac
4976 @anchor{AC_FUNC_FORK}
4977 @defmac AC_FUNC_FORK
4978 @acindex{FUNC_FORK}
4979 @cvindex HAVE_VFORK_H
4980 @cvindex HAVE_WORKING_FORK
4981 @cvindex HAVE_WORKING_VFORK
4982 @cvindex vfork
4983 @c @fuindex fork
4984 @prindex @code{fork}
4985 @c @fuindex vfork
4986 @prindex @code{vfork}
4987 @hdrindex{vfork.h}
4988 @c @caindex func_fork
4989 @c @caindex func_fork_works
4990 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4991 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4992 checks whether @code{fork} is just a stub by trying to run it.
4994 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4995 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4996 define @code{vfork} to be @code{fork} for backward compatibility with
4997 previous versions of @command{autoconf}.  This macro checks for several known
4998 errors in implementations of @code{vfork} and considers the system to not
4999 have a working @code{vfork} if it detects any of them.  It is not considered
5000 to be an implementation error if a child's invocation of @code{signal}
5001 modifies the parent's signal handler, since child processes rarely change
5002 their signal handlers.
5004 Since this macro defines @code{vfork} only for backward compatibility with
5005 previous versions of @command{autoconf} you're encouraged to define it
5006 yourself in new code:
5007 @example
5008 @group
5009 #ifndef HAVE_WORKING_VFORK
5010 # define vfork fork
5011 #endif
5012 @end group
5013 @end example
5015 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5016 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5017 test, you also need to set the @code{ac_cv_func_fork} and
5018 @code{ac_cv_func_vfork} variables.
5019 @end defmac
5021 @defmac AC_FUNC_FSEEKO
5022 @acindex{FUNC_FSEEKO}
5023 @cvindex _LARGEFILE_SOURCE
5024 @cvindex HAVE_FSEEKO
5025 @c @fuindex fseeko
5026 @prindex @code{fseeko}
5027 @c @fuindex ftello
5028 @prindex @code{ftello}
5029 @c @caindex sys_largefile_source
5030 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5031 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5032 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5033 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5034 largefile-sensitive systems where @code{off_t} does not default to a
5035 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5036 @end defmac
5038 @defmac AC_FUNC_GETGROUPS
5039 @acindex{FUNC_GETGROUPS}
5040 @cvindex HAVE_GETGROUPS
5041 @ovindex GETGROUPS_LIBS
5042 @c @fuindex getgroups
5043 @prindex @code{getgroups}
5044 @caindex func_getgroups_works
5045 If the @code{getgroups} function is available and works (unlike on
5046 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5047 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5048 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5049 @end defmac
5051 @anchor{AC_FUNC_GETLOADAVG}
5052 @defmac AC_FUNC_GETLOADAVG
5053 @acindex{FUNC_GETLOADAVG}
5054 @cvindex SVR4
5055 @cvindex DGUX
5056 @cvindex UMAX
5057 @cvindex UMAX4_3
5058 @cvindex HAVE_NLIST_H
5059 @cvindex NLIST_NAME_UNION
5060 @cvindex GETLOADAVG_PRIVILEGED
5061 @cvindex NEED_SETGID
5062 @cvindex C_GETLOADAVG
5063 @ovindex LIBOBJS
5064 @ovindex NEED_SETGID
5065 @ovindex KMEM_GROUP
5066 @ovindex GETLOADAVG_LIBS
5067 @c @fuindex getloadavg
5068 @prindex @code{getloadavg}
5069 Check how to get the system load averages.  To perform its tests
5070 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5071 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5072 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5074 If the system has the @code{getloadavg} function, define
5075 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5076 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5077 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5078 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
5079 possibly define several other C preprocessor macros and output
5080 variables:
5082 @enumerate
5083 @item
5084 Define @code{C_GETLOADAVG}.
5086 @item
5087 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5088 those systems.
5090 @item
5091 @hdrindex{nlist.h}
5092 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5094 @item
5095 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5096 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5097 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5099 @item
5100 Programs may need to be installed set-group-ID (or set-user-ID) for
5101 @code{getloadavg} to work.  In this case, define
5102 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5103 to @samp{true} (and otherwise to @samp{false}), and set
5104 @code{KMEM_GROUP} to the name of the group that should own the installed
5105 program.
5106 @end enumerate
5108 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5109 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5110 @end defmac
5112 @anchor{AC_FUNC_GETMNTENT}
5113 @defmac AC_FUNC_GETMNTENT
5114 @acindex{FUNC_GETMNTENT}
5115 @cvindex HAVE_GETMNTENT
5116 @c @fuindex getmntent
5117 @prindex @code{getmntent}
5118 @caindex search_getmntent
5119 Check for @code{getmntent} in the standard C library, and then in the
5120 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5121 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5122 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5123 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5124 @code{ac_cv_func_getmntent} to @code{no}.
5126 The result of this macro can be overridden by setting the cache variable
5127 @code{ac_cv_search_getmntent}.
5128 @end defmac
5130 @defmac AC_FUNC_GETPGRP
5131 @acindex{FUNC_GETPGRP}
5132 @cvindex GETPGRP_VOID
5133 @c @fuindex getpgid
5134 @c @fuindex getpgrp
5135 @prindex @code{getpgid}
5136 @prindex @code{getpgrp}
5137 @caindex func_getpgrp_void
5138 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5139 @code{getpgrp}; this is the Posix behavior.  On older BSD
5140 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5141 behaves like Posix's @code{getpgid}.
5143 @example
5144 #ifdef GETPGRP_VOID
5145   pid = getpgrp ();
5146 #else
5147   pid = getpgrp (0);
5148 #endif
5149 @end example
5151 This macro does not check whether
5152 @code{getpgrp} exists at all; if you need to work in that situation,
5153 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5155 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5156 variable.
5158 This macro is obsolescent, as current systems have a @code{getpgrp}
5159 whose signature conforms to Posix.  New programs need not use this macro.
5160 @end defmac
5162 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5163 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5164 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5165 @c @fuindex lstat
5166 @prindex @code{lstat}
5167 @caindex func_lstat_dereferences_slashed_symlink
5168 If @file{link} is a symbolic link, then @code{lstat} should treat
5169 @file{link/} the same as @file{link/.}.  However, many older
5170 @code{lstat} implementations incorrectly ignore trailing slashes.
5172 It is safe to assume that if @code{lstat} incorrectly ignores
5173 trailing slashes, then other symbolic-link-aware functions like
5174 @code{unlink} also incorrectly ignore trailing slashes.
5176 If @code{lstat} behaves properly, define
5177 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5178 @code{AC_LIBOBJ} replacement of @code{lstat}.
5180 The result of this macro is cached in the
5181 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5183 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5184 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5185 @end defmac
5187 @defmac AC_FUNC_MALLOC
5188 @acindex{FUNC_MALLOC}
5189 @cvindex HAVE_MALLOC
5190 @cvindex malloc
5191 @c @fuindex malloc
5192 @prindex @code{malloc}
5193 @caindex func_malloc_0_nonnull
5194 If the @code{malloc} function is compatible with the GNU C
5195 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5196 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5197 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5198 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5199 native @code{malloc} is not used in the main project.
5201 Typically, the replacement file @file{malloc.c} should look like (note
5202 the @samp{#undef malloc}):
5204 @verbatim
5205 #include <config.h>
5206 #undef malloc
5208 #include <sys/types.h>
5210 void *malloc ();
5212 /* Allocate an N-byte block of memory from the heap.
5213    If N is zero, allocate a 1-byte block.  */
5215 void *
5216 rpl_malloc (size_t n)
5218   if (n == 0)
5219     n = 1;
5220   return malloc (n);
5222 @end verbatim
5224 The result of this macro is cached in the
5225 @code{ac_cv_func_malloc_0_nonnull} variable.
5226 @end defmac
5228 @defmac AC_FUNC_MBRTOWC
5229 @acindex{FUNC_MBRTOWC}
5230 @cvindex HAVE_MBRTOWC
5231 @c @fuindex mbrtowc
5232 @prindex @code{mbrtowc}
5233 @caindex func_mbrtowc
5234 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5235 type @code{mbstate_t} are properly declared.
5237 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5238 variable.
5239 @end defmac
5241 @defmac AC_FUNC_MEMCMP
5242 @acindex{FUNC_MEMCMP}
5243 @ovindex LIBOBJS
5244 @c @fuindex memcmp
5245 @prindex @code{memcmp}
5246 @caindex func_memcmp_working
5247 If the @code{memcmp} function is not available, or does not work on
5248 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5249 bytes or more and with at least one buffer not starting on a 4-byte
5250 boundary (such as the one on NeXT x86 OpenStep), require an
5251 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5253 The result of this macro is cached in the
5254 @code{ac_cv_func_memcmp_working} variable.
5256 This macro is obsolescent, as current systems have a working
5257 @code{memcmp}.  New programs need not use this macro.
5258 @end defmac
5260 @defmac AC_FUNC_MKTIME
5261 @acindex{FUNC_MKTIME}
5262 @ovindex LIBOBJS
5263 @c @fuindex mktime
5264 @prindex @code{mktime}
5265 @caindex func_working_mktime
5266 If the @code{mktime} function is not available, or does not work
5267 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5268 For the purposes of this test, @code{mktime} should conform to the
5269 Posix standard and should be the inverse of
5270 @code{localtime}.
5272 The result of this macro is cached in the
5273 @code{ac_cv_func_working_mktime} variable.
5275 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5276 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5277 @end defmac
5279 @anchor{AC_FUNC_MMAP}
5280 @defmac AC_FUNC_MMAP
5281 @acindex{FUNC_MMAP}
5282 @cvindex HAVE_MMAP
5283 @c @fuindex mmap
5284 @prindex @code{mmap}
5285 @caindex func_mmap_fixed_mapped
5286 If the @code{mmap} function exists and works correctly, define
5287 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5288 memory.
5290 The result of this macro is cached in the
5291 @code{ac_cv_func_mmap_fixed_mapped} variable.
5292 @end defmac
5294 @defmac AC_FUNC_OBSTACK
5295 @acindex{FUNC_OBSTACK}
5296 @cvindex HAVE_OBSTACK
5297 @cindex obstack
5298 @caindex func_obstack
5299 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5300 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5302 The result of this macro is cached in the @code{ac_cv_func_obstack}
5303 variable.
5304 @end defmac
5306 @defmac AC_FUNC_REALLOC
5307 @acindex{FUNC_REALLOC}
5308 @cvindex HAVE_REALLOC
5309 @cvindex realloc
5310 @c @fuindex realloc
5311 @prindex @code{realloc}
5312 @caindex func_realloc_0_nonnull
5313 If the @code{realloc} function is compatible with the GNU C
5314 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5315 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5316 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5317 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5318 the native @code{realloc} is not used in the main project.  See
5319 @code{AC_FUNC_MALLOC} for details.
5321 The result of this macro is cached in the
5322 @code{ac_cv_func_realloc_0_nonnull} variable.
5323 @end defmac
5325 @defmac AC_FUNC_SELECT_ARGTYPES
5326 @acindex{FUNC_SELECT_ARGTYPES}
5327 @cvindex SELECT_TYPE_ARG1
5328 @cvindex SELECT_TYPE_ARG234
5329 @cvindex SELECT_TYPE_ARG5
5330 @c @fuindex select
5331 @prindex @code{select}
5332 @c @caindex func_select_args
5333 Determines the correct type to be passed for each of the
5334 @code{select} function's arguments, and defines those types
5335 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5336 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5337 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5338 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5340 This macro is obsolescent, as current systems have a @code{select} whose
5341 signature conforms to Posix.  New programs need not use this macro.
5342 @end defmac
5344 @defmac AC_FUNC_SETPGRP
5345 @acindex{FUNC_SETPGRP}
5346 @cvindex SETPGRP_VOID
5347 @c @fuindex setpgrp
5348 @prindex @code{setpgrp}
5349 @caindex func_setpgrp_void
5350 If @code{setpgrp} takes no argument (the Posix version), define
5351 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5352 two process IDs as arguments.  This macro does not check whether
5353 @code{setpgrp} exists at all; if you need to work in that situation,
5354 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5356 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5357 variable.
5359 This macro is obsolescent, as current systems have a @code{setpgrp}
5360 whose signature conforms to Posix.  New programs need not use this macro.
5361 @end defmac
5363 @defmac AC_FUNC_STAT
5364 @defmacx AC_FUNC_LSTAT
5365 @acindex{FUNC_STAT}
5366 @acindex{FUNC_LSTAT}
5367 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5368 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5369 @c @fuindex stat
5370 @prindex @code{stat}
5371 @c @fuindex lstat
5372 @prindex @code{lstat}
5373 @caindex func_stat_empty_string_bug
5374 @caindex func_lstat_empty_string_bug
5375 Determine whether @code{stat} or @code{lstat} have the bug that it
5376 succeeds when given the zero-length file name as argument.  The @code{stat}
5377 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5378 this.
5380 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5381 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5382 replacement of it.
5384 The results of these macros are cached in the
5385 @code{ac_cv_func_stat_empty_string_bug} and the
5386 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5388 These macros are obsolescent, as no current systems have the bug.
5389 New programs need not use these macros.
5390 @end defmac
5392 @anchor{AC_FUNC_STRCOLL}
5393 @defmac AC_FUNC_STRCOLL
5394 @acindex{FUNC_STRCOLL}
5395 @cvindex HAVE_STRCOLL
5396 @c @fuindex strcoll
5397 @prindex @code{strcoll}
5398 @caindex func_strcoll_works
5399 If the @code{strcoll} function exists and works correctly, define
5400 @code{HAVE_STRCOLL}.  This does a bit more than
5401 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5402 definitions of @code{strcoll} that should not be used.
5404 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5405 variable.
5406 @end defmac
5408 @defmac AC_FUNC_STRERROR_R
5409 @acindex{FUNC_STRERROR_R}
5410 @cvindex HAVE_STRERROR_R
5411 @cvindex HAVE_DECL_STRERROR_R
5412 @cvindex STRERROR_R_CHAR_P
5413 @c @fuindex strerror_r
5414 @caindex func_strerror_r_char_p
5415 @prindex @code{strerror_r}
5416 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5417 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5418 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5419 returns an @code{int} error number.  The Thread-Safe Functions option of
5420 Posix requires @code{strerror_r} to return @code{int}, but
5421 many systems (including, for example, version 2.2.4 of the GNU C
5422 Library) return a @code{char *} value that is not necessarily equal to
5423 the buffer argument.
5425 The result of this macro is cached in the
5426 @code{ac_cv_func_strerror_r_char_p} variable.
5427 @end defmac
5429 @anchor{AC_FUNC_STRFTIME}
5430 @defmac AC_FUNC_STRFTIME
5431 @acindex{FUNC_STRFTIME}
5432 @cvindex HAVE_STRFTIME
5433 @c @fuindex strftime
5434 @prindex @code{strftime}
5435 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5436 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5438 This macro is obsolescent, as no current systems require the @file{intl}
5439 library for @code{strftime}.  New programs need not use this macro.
5440 @end defmac
5442 @defmac AC_FUNC_STRTOD
5443 @acindex{FUNC_STRTOD}
5444 @ovindex POW_LIB
5445 @c @fuindex strtod
5446 @prindex @code{strtod}
5447 @caindex func_strtod
5448 @caindex func_pow
5449 If the @code{strtod} function does not exist or doesn't work correctly,
5450 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5451 because @file{strtod.c} is likely to need @samp{pow}, set the output
5452 variable @code{POW_LIB} to the extra library needed.
5454 This macro caches its result in the @code{ac_cv_func_strtod} variable
5455 and depends upon the result in the @code{ac_cv_func_pow} variable.
5457 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5458 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5459 @end defmac
5461 @defmac AC_FUNC_STRTOLD
5462 @acindex{FUNC_STRTOLD}
5463 @cvindex HAVE_STRTOLD
5464 @prindex @code{strtold}
5465 @caindex func_strtold
5466 If the @code{strtold} function exists and conforms to C99, define
5467 @code{HAVE_STRTOLD}.
5469 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5470 @end defmac
5472 @defmac AC_FUNC_STRNLEN
5473 @acindex{FUNC_STRNLEN}
5474 @cvindex HAVE_STRNLEN
5475 @c @fuindex strnlen
5476 @prindex @code{strnlen}
5477 @caindex func_strnlen_working
5478 If the @code{strnlen} function is not available, or is buggy (like the one
5479 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5481 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5482 variable.
5483 @end defmac
5485 @anchor{AC_FUNC_UTIME_NULL}
5486 @defmac AC_FUNC_UTIME_NULL
5487 @acindex{FUNC_UTIME_NULL}
5488 @cvindex HAVE_UTIME_NULL
5489 @c @fuindex utime
5490 @prindex @code{utime}
5491 @caindex func_utime_null
5492 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5493 the present, define @code{HAVE_UTIME_NULL}.
5495 This macro caches its result in the @code{ac_cv_func_utime_null}
5496 variable.
5498 This macro is obsolescent, as all current systems have a @code{utime}
5499 that behaves this way.  New programs need not use this macro.
5500 @end defmac
5502 @anchor{AC_FUNC_VPRINTF}
5503 @defmac AC_FUNC_VPRINTF
5504 @acindex{FUNC_VPRINTF}
5505 @cvindex HAVE_VPRINTF
5506 @cvindex HAVE_DOPRNT
5507 @c @fuindex vprintf
5508 @prindex @code{vprintf}
5509 @c @fuindex vsprintf
5510 @prindex @code{vsprintf}
5511 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5512 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5513 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5514 are also available.)
5516 This macro is obsolescent, as all current systems have @code{vprintf}.
5517 New programs need not use this macro.
5518 @end defmac
5520 @defmac AC_REPLACE_FNMATCH
5521 @acindex{REPLACE_FNMATCH}
5522 @c @fuindex fnmatch
5523 @prindex @code{fnmatch}
5524 @hdrindex{fnmatch.h}
5525 @caindex func_fnmatch_works
5526 If the @code{fnmatch} function does not conform to Posix (see
5527 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5529 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5530 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5531 copy of the source code of GNU @code{fnmatch}.  If necessary,
5532 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5533 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5534 included in place of the system @code{<fnmatch.h>}.
5536 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5537 variable.
5539 This macro is obsolescent, as it assumes the use of particular source
5540 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5541 which provides this macro along with the source files.  @xref{Gnulib}.
5542 @end defmac
5546 @node Generic Functions
5547 @subsection Generic Function Checks
5549 These macros are used to find functions not covered by the ``particular''
5550 test macros.  If the functions might be in libraries other than the
5551 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5552 If you need to check the behavior of a function as well as find out
5553 whether it is present, you have to write your own test for
5554 it (@pxref{Writing Tests}).
5556 @anchor{AC_CHECK_FUNC}
5557 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5558   @ovar{action-if-not-found})
5559 @acindex{CHECK_FUNC}
5560 @caindex func_@var{function}
5561 If C function @var{function} is available, run shell commands
5562 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5563 want to define a symbol if the function is available, consider using
5564 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5565 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5566 standardized than C++.  (@pxref{Language Choice}, for more information
5567 about selecting the language for checks.)
5569 This macro caches its result in the @code{ac_cv_func_@var{function}}
5570 variable.
5571 @end defmac
5573 @anchor{AC_CHECK_FUNCS}
5574 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5575   @ovar{action-if-not-found})
5576 @acindex{CHECK_FUNCS}
5577 @cvindex HAVE_@var{function}
5578 For each @var{function} enumerated in the blank-or-newline-separated argument
5579 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5580 If @var{action-if-found} is given, it is additional shell code to
5581 execute when one of the functions is found.  You can give it a value of
5582 @samp{break} to break out of the loop on the first match.  If
5583 @var{action-if-not-found} is given, it is executed when one of the
5584 functions is not found.
5586 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5587 @end defmac
5589 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5590 @acindex{CHECK_FUNCS_ONCE}
5591 @cvindex HAVE_@var{function}
5592 For each @var{function} enumerated in the blank-or-newline-separated argument
5593 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5594 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5595 checking code at most once, so that @command{configure} is smaller and
5596 faster; but the checks cannot be conditionalized and are always done once,
5597 early during the @command{configure} run.
5598 @end defmac
5600 @sp 1
5602 Autoconf follows a philosophy that was formed over the years by those
5603 who have struggled for portability: isolate the portability issues in
5604 specific files, and then program as if you were in a Posix
5605 environment.  Some functions may be missing or unfixable, and your
5606 package must be ready to replace them.
5608 Suitable replacements for many such problem functions are available from
5609 Gnulib (@pxref{Gnulib}).
5611 @defmac AC_LIBOBJ (@var{function})
5612 @acindex{LIBOBJ}
5613 @ovindex LIBOBJS
5614 Specify that @samp{@var{function}.c} must be included in the executables
5615 to replace a missing or broken implementation of @var{function}.
5617 @vrindex ac_objext
5618 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5619 variable @code{LIBOBJS} if it is not already in, and calls
5620 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5621 directly change @code{LIBOBJS}, since this is not traceable.
5622 @end defmac
5624 @defmac AC_LIBSOURCE (@var{file})
5625 @acindex{LIBSOURCE}
5626 Specify that @var{file} might be needed to compile the project.  If you
5627 need to know what files might be needed by a @file{configure.ac}, you
5628 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5630 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5631 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5632 that case, since shell variables cannot be traced statically, you must
5633 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5634 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5635 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5636 @code{"foo"} or @code{"bar"}, you should do:
5638 @example
5639 AC_LIBSOURCE([foo.c])
5640 AC_LIBSOURCE([bar.c])
5641 AC_LIBOBJ([$foo_or_bar])
5642 @end example
5644 @noindent
5645 There is usually a way to avoid this, however, and you are encouraged to
5646 simply call @code{AC_LIBOBJ} with literal arguments.
5648 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5649 slightly different semantics: the old macro took the function name,
5650 e.g., @code{foo}, as its argument rather than the file name.
5651 @end defmac
5653 @defmac AC_LIBSOURCES (@var{files})
5654 @acindex{LIBSOURCES}
5655 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5656 comma-separated M4 list.  Thus, the above example might be rewritten:
5658 @example
5659 AC_LIBSOURCES([foo.c, bar.c])
5660 AC_LIBOBJ([$foo_or_bar])
5661 @end example
5662 @end defmac
5664 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5665 @acindex{CONFIG_LIBOBJ_DIR}
5666 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5667 @var{directory}, a name relative to the top level of the
5668 source tree.  The replacement directory defaults to @file{.}, the top
5669 level directory, and the most typical value is @file{lib}, corresponding
5670 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5672 @command{configure} might need to know the replacement directory for the
5673 following reasons: (i) some checks use the replacement files, (ii) some
5674 macros bypass broken system headers by installing links to the
5675 replacement headers (iii) when used in conjunction with Automake,
5676 within each makefile, @var{directory} is used as a relative path
5677 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5678 @code{LTLIBOBJS}, etc.
5679 @end defmac
5681 @sp 1
5683 It is common to merely check for the existence of a function, and ask
5684 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5685 a convenient shorthand.
5687 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5688 @acindex{REPLACE_FUNCS}
5689 @cvindex HAVE_@var{function}
5690 @ovindex LIBOBJS
5691 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5692 @var{action-if-not-found}.  You can declare your replacement function by
5693 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5694 system has the function, it probably declares it in a header file you
5695 should be including, so you shouldn't redeclare it lest your declaration
5696 conflict.
5697 @end defmac
5699 @node Header Files
5700 @section Header Files
5701 @cindex Header, checking
5703 The following macros check for the presence of certain C header files.
5704 If there is no macro specifically defined to check for a header file you need,
5705 and you don't need to check for any special properties of
5706 it, then you can use one of the general header-file check macros.
5708 @menu
5709 * Header Portability::          Collected knowledge on common headers
5710 * Particular Headers::          Special handling to find certain headers
5711 * Generic Headers::             How to find other headers
5712 @end menu
5714 @node Header Portability
5715 @subsection Portability of Headers
5716 @cindex Portability of headers
5717 @cindex Header portability
5719 This section documents some collected knowledge about common headers,
5720 and the problems they cause.  By definition, this list always requires
5721 additions.  A much more complete list is maintained by the Gnulib
5722 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5723 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5724 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5725 the gnulib list as complete as possible.
5727 @table @asis
5729 @item @file{limits.h}
5730 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5731 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5732 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5733 define them.
5735 @item @file{inttypes.h} vs.@: @file{stdint.h}
5736 @hdrindex{inttypes.h}
5737 @hdrindex{stdint.h}
5738 The C99 standard says that @file{inttypes.h} includes
5739 @file{stdint.h}, so there's no need to include @file{stdint.h}
5740 separately in a standard environment.  Some implementations have
5741 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5742 know of any implementation that has @file{stdint.h} but not
5743 @file{inttypes.h}.
5745 @item @file{linux/irda.h}
5746 @hdrindex{linux/irda.h}
5747 It requires @file{linux/types.h} and @file{sys/socket.h}.
5749 @item @file{linux/random.h}
5750 @hdrindex{linux/random.h}
5751 It requires @file{linux/types.h}.
5753 @item @file{net/if.h}
5754 @hdrindex{net/if.h}
5755 On Darwin, this file requires that @file{sys/socket.h} be included
5756 beforehand.  One should run:
5758 @example
5759 AC_CHECK_HEADERS([sys/socket.h])
5760 AC_CHECK_HEADERS([net/if.h], [], [],
5761 [#include <stdio.h>
5762 #ifdef STDC_HEADERS
5763 # include <stdlib.h>
5764 # include <stddef.h>
5765 #else
5766 # ifdef HAVE_STDLIB_H
5767 #  include <stdlib.h>
5768 # endif
5769 #endif
5770 #ifdef HAVE_SYS_SOCKET_H
5771 # include <sys/socket.h>
5772 #endif
5774 @end example
5776 @item @file{netinet/if_ether.h}
5777 @hdrindex{netinet/if_ether.h}
5778 On Darwin, this file requires that @file{stdio.h} and
5779 @file{sys/socket.h} be included beforehand.  One should run:
5781 @example
5782 AC_CHECK_HEADERS([sys/socket.h])
5783 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5784 [#include <stdio.h>
5785 #ifdef STDC_HEADERS
5786 # include <stdlib.h>
5787 # include <stddef.h>
5788 #else
5789 # ifdef HAVE_STDLIB_H
5790 #  include <stdlib.h>
5791 # endif
5792 #endif
5793 #ifdef HAVE_SYS_SOCKET_H
5794 # include <sys/socket.h>
5795 #endif
5797 @end example
5799 @item @file{stdint.h}
5800 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5802 @item @file{stdlib.h}
5803 @hdrindex{stdlib.h}
5804 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5806 @item @file{sys/mount.h}
5807 @hdrindex{sys/mount.h}
5808 On FreeBSD 4.8 on ia32 and using gcc version 2.95.4,
5809 @file{sys/params.h} is a prerequisite.
5811 @item @file{sys/ptem.h}
5812 @hdrindex{sys/ptem.h}
5813 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5815 @item @file{sys/socket.h}
5816 @hdrindex{sys/socket.h}
5817 On Darwin, @file{stdlib.h} is a prerequisite.
5819 @item @file{sys/ucred.h}
5820 @hdrindex{sys/ucred.h}
5821 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5823 @item @file{X11/extensions/scrnsaver.h}
5824 @hdrindex{X11/extensions/scrnsaver.h}
5825 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5826 so required that you might not even consider looking for it.
5828 @example
5829 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5830 [[#include <X11/Xlib.h>
5832 @end example
5833 @end table
5836 @node Particular Headers
5837 @subsection Particular Header Checks
5839 These macros check for particular system header files---whether they
5840 exist, and in some cases whether they declare certain symbols.
5842 @defmac AC_CHECK_HEADER_STDBOOL
5843 @acindex{CHECK_HEADER_STDBOOL}
5844 @cvindex HAVE__BOOL
5845 @hdrindex{stdbool.h}
5846 @caindex header_stdbool_h
5847 Check whether @file{stdbool.h} exists and conforms to C99, and cache the
5848 result in the @code{ac_cv_header_stdbool_h} variable.  If the type
5849 @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5851 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5852 packages that supply a substitute @file{stdbool.h} on platforms lacking
5853 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5854 that explicitly checks for @file{stdbool.h}.
5855 @end defmac
5857 @defmac AC_HEADER_ASSERT
5858 @acindex{HEADER_ASSERT}
5859 @cvindex NDEBUG
5860 @hdrindex{assert.h}
5861 Check whether to enable assertions in the style of @file{assert.h}.
5862 Assertions are enabled by default, but the user can override this by
5863 invoking @command{configure} with the @option{--disable-assert} option.
5864 @end defmac
5866 @anchor{AC_HEADER_DIRENT}
5867 @defmac AC_HEADER_DIRENT
5868 @acindex{HEADER_DIRENT}
5869 @cvindex HAVE_DIRENT_H
5870 @cvindex HAVE_NDIR_H
5871 @cvindex HAVE_SYS_DIR_H
5872 @cvindex HAVE_SYS_NDIR_H
5873 @hdrindex{dirent.h}
5874 @hdrindex{sys/ndir.h}
5875 @hdrindex{sys/dir.h}
5876 @hdrindex{ndir.h}
5877 Check for the following header files.  For the first one that is
5878 found and defines @samp{DIR}, define the listed C preprocessor macro:
5880 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5881 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5882 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5883 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5884 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5885 @end multitable
5887 The directory-library declarations in your source code should look
5888 something like the following:
5890 @example
5891 @group
5892 #include <sys/types.h>
5893 #ifdef HAVE_DIRENT_H
5894 # include <dirent.h>
5895 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5896 #else
5897 # define dirent direct
5898 # define NAMLEN(dirent) ((dirent)->d_namlen)
5899 # ifdef HAVE_SYS_NDIR_H
5900 #  include <sys/ndir.h>
5901 # endif
5902 # ifdef HAVE_SYS_DIR_H
5903 #  include <sys/dir.h>
5904 # endif
5905 # ifdef HAVE_NDIR_H
5906 #  include <ndir.h>
5907 # endif
5908 #endif
5909 @end group
5910 @end example
5912 Using the above declarations, the program would declare variables to be
5913 of type @code{struct dirent}, not @code{struct direct}, and would access
5914 the length of a directory entry name by passing a pointer to a
5915 @code{struct dirent} to the @code{NAMLEN} macro.
5917 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5919 This macro is obsolescent, as all current systems with directory
5920 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5922 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5923 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5924 @end defmac
5926 @anchor{AC_HEADER_MAJOR}
5927 @defmac AC_HEADER_MAJOR
5928 @acindex{HEADER_MAJOR}
5929 @cvindex MAJOR_IN_MKDEV
5930 @cvindex MAJOR_IN_SYSMACROS
5931 @hdrindex{sys/mkdev.h}
5932 @hdrindex{sys/sysmacros.h}
5933 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5934 @code{makedev}, but @file{sys/mkdev.h} does, define
5935 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5936 @code{MAJOR_IN_SYSMACROS}.
5937 @end defmac
5939 @defmac AC_HEADER_RESOLV
5940 @acindex{HEADER_RESOLV}
5941 @cvindex HAVE_RESOLV_H
5942 @hdrindex{resolv.h}
5943 Checks for header @file{resolv.h}, checking for prerequisites first.
5944 To properly use @file{resolv.h}, your code should contain something like
5945 the following:
5947 @verbatim
5948 #ifdef HAVE_SYS_TYPES_H
5949 #  include <sys/types.h>
5950 #endif
5951 #ifdef HAVE_NETINET_IN_H
5952 #  include <netinet/in.h>   /* inet_ functions / structs */
5953 #endif
5954 #ifdef HAVE_ARPA_NAMESER_H
5955 #  include <arpa/nameser.h> /* DNS HEADER struct */
5956 #endif
5957 #ifdef HAVE_NETDB_H
5958 #  include <netdb.h>
5959 #endif
5960 #include <resolv.h>
5961 @end verbatim
5962 @end defmac
5964 @anchor{AC_HEADER_STAT}
5965 @defmac AC_HEADER_STAT
5966 @acindex{HEADER_STAT}
5967 @cvindex STAT_MACROS_BROKEN
5968 @hdrindex{sys/stat.h}
5969 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5970 @file{sys/stat.h} do not work properly (returning false positives),
5971 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5972 Amdahl UTS and Motorola System V/88.
5974 This macro is obsolescent, as no current systems have the bug.
5975 New programs need not use this macro.
5976 @end defmac
5978 @defmac AC_HEADER_STDBOOL
5979 @acindex{HEADER_STDBOOL}
5980 @cvindex HAVE_STDBOOL_H
5981 @cvindex HAVE__BOOL
5982 @hdrindex{stdbool.h}
5983 @caindex header_stdbool_h
5984 If @file{stdbool.h} exists and conforms to C99, define
5985 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5986 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5987 program could contain the following code:
5989 @example
5990 @group
5991 #ifdef HAVE_STDBOOL_H
5992 # include <stdbool.h>
5993 #else
5994 # ifndef HAVE__BOOL
5995 #  ifdef __cplusplus
5996 typedef bool _Bool;
5997 #  else
5998 #   define _Bool signed char
5999 #  endif
6000 # endif
6001 # define bool _Bool
6002 # define false 0
6003 # define true 1
6004 # define __bool_true_false_are_defined 1
6005 #endif
6006 @end group
6007 @end example
6009 Alternatively you can use the @samp{stdbool} package of Gnulib
6010 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6011 @code{#include <stdbool.h>}, and it adds support for less-common
6012 platforms.
6014 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6015 variable.
6017 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6018 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6019 does not.
6020 @end defmac
6022 @anchor{AC_HEADER_STDC}
6023 @defmac AC_HEADER_STDC
6024 @acindex{HEADER_STDC}
6025 @cvindex STDC_HEADERS
6026 @hdrindex{stdlib.h}
6027 @hdrindex{stdarg.h}
6028 @hdrindex{string.h}
6029 @hdrindex{float.h}
6030 @hdrindex{ctype.h}
6031 @caindex header_stdc
6032 Define @code{STDC_HEADERS} if the system has C header files
6033 conforming to ANSI C89 (ISO C90).
6034 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
6035 @file{string.h}, and @file{float.h}; if the system has those, it
6036 probably has the rest of the C89 header files.  This macro also
6037 checks whether @file{string.h} declares @code{memchr} (and thus
6038 presumably the other @code{mem} functions), whether @file{stdlib.h}
6039 declare @code{free} (and thus presumably @code{malloc} and other related
6040 functions), and whether the @file{ctype.h} macros work on characters
6041 with the high bit set, as the C standard requires.
6043 If you use this macro, your code can refer to @code{STDC_HEADERS} to
6044 determine whether the system has conforming header files (and probably C
6045 library functions).
6047 This macro caches its result in the @code{ac_cv_header_stdc} variable.
6049 This macro is obsolescent, as current systems have conforming header
6050 files.  New programs need not use this macro.
6052 @hdrindex{string.h}
6053 @hdrindex{strings.h}
6054 Nowadays @file{string.h} is part of the C standard and declares functions like
6055 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
6056 BSD functions like @code{bcopy}; but
6057 historically, string functions were a major sticking point in this area.
6058 If you still want to worry about portability to ancient systems without
6059 standard headers, there is so much variation
6060 that it is probably easier to declare the functions you use than to
6061 figure out exactly what the system header files declare.  Some ancient systems
6062 contained a mix of functions from the C standard and from BSD;
6063 some were mostly standard but lacked @samp{memmove}; some defined the
6064 BSD functions as macros in @file{string.h} or
6065 @file{strings.h}; some had only the BSD functions but
6066 @file{string.h}; some declared the memory functions in @file{memory.h},
6067 some in @file{string.h}; etc.  It is probably sufficient to check for
6068 one string function and one memory function; if the library had the
6069 standard versions of those then it probably had most of the others.
6070 If you put the following in @file{configure.ac}:
6072 @example
6073 # This example is obsolescent.
6074 # Nowadays you can omit these macro calls.
6075 AC_HEADER_STDC
6076 AC_CHECK_FUNCS([strchr memcpy])
6077 @end example
6079 @noindent
6080 then, in your code, you can use declarations like this:
6082 @example
6083 @group
6084 /* This example is obsolescent.
6085    Nowadays you can just #include <string.h>.  */
6086 #ifdef STDC_HEADERS
6087 # include <string.h>
6088 #else
6089 # ifndef HAVE_STRCHR
6090 #  define strchr index
6091 #  define strrchr rindex
6092 # endif
6093 char *strchr (), *strrchr ();
6094 # ifndef HAVE_MEMCPY
6095 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
6096 #  define memmove(d, s, n) bcopy ((s), (d), (n))
6097 # endif
6098 #endif
6099 @end group
6100 @end example
6102 @noindent
6103 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
6104 or @code{strspn}, which have no BSD equivalent, then macros don't
6105 suffice to port to ancient hosts; you must provide an implementation of
6106 each function.  An easy
6107 way to incorporate your implementations only when needed (since the ones
6108 in system C libraries may be hand optimized) is to, taking @code{memchr}
6109 for example, put it in @file{memchr.c} and use
6110 @samp{AC_REPLACE_FUNCS([memchr])}.
6111 @end defmac
6113 @defmac AC_HEADER_SYS_WAIT
6114 @acindex{HEADER_SYS_WAIT}
6115 @cvindex HAVE_SYS_WAIT_H
6116 @hdrindex{sys/wait.h}
6117 @caindex header_sys_wait_h
6118 If @file{sys/wait.h} exists and is compatible with Posix, define
6119 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6120 does not exist, or if it uses the old BSD @code{union wait} instead
6121 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6122 Posix compatible, then instead of including it, define the
6123 Posix macros with their usual interpretations.  Here is an
6124 example:
6126 @example
6127 @group
6128 #include <sys/types.h>
6129 #ifdef HAVE_SYS_WAIT_H
6130 # include <sys/wait.h>
6131 #endif
6132 #ifndef WEXITSTATUS
6133 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6134 #endif
6135 #ifndef WIFEXITED
6136 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6137 #endif
6138 @end group
6139 @end example
6141 @noindent
6142 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6143 variable.
6145 This macro is obsolescent, as current systems are compatible with Posix.
6146 New programs need not use this macro.
6147 @end defmac
6149 @cvindex _POSIX_VERSION
6150 @hdrindex{unistd.h}
6151 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6152 Posix systems.  If there is no @file{unistd.h}, it is definitely
6153 not a Posix system.  However, some non-Posix systems do
6154 have @file{unistd.h}.
6156 The way to check whether the system supports Posix is:
6158 @example
6159 @group
6160 #ifdef HAVE_UNISTD_H
6161 # include <sys/types.h>
6162 # include <unistd.h>
6163 #endif
6165 #ifdef _POSIX_VERSION
6166 /* Code for Posix systems.  */
6167 #endif
6168 @end group
6169 @end example
6171 @anchor{AC_HEADER_TIME}
6172 @defmac AC_HEADER_TIME
6173 @acindex{HEADER_TIME}
6174 @cvindex TIME_WITH_SYS_TIME
6175 @hdrindex{time.h}
6176 @hdrindex{sys/time.h}
6177 @caindex header_time
6178 If a program may include both @file{time.h} and @file{sys/time.h},
6179 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
6180 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
6181 protected against multiple inclusion, so programs could not explicitly
6182 include both files.  This macro is useful in programs that use, for
6183 example, @code{struct timeval} as well as
6184 @code{struct tm}.  It is best used in conjunction with
6185 @code{HAVE_SYS_TIME_H}, which can be checked for using
6186 @code{AC_CHECK_HEADERS([sys/time.h])}.
6188 @example
6189 @group
6190 #ifdef TIME_WITH_SYS_TIME
6191 # include <sys/time.h>
6192 # include <time.h>
6193 #else
6194 # ifdef HAVE_SYS_TIME_H
6195 #  include <sys/time.h>
6196 # else
6197 #  include <time.h>
6198 # endif
6199 #endif
6200 @end group
6201 @end example
6203 @noindent
6204 This macro caches its result in the @code{ac_cv_header_time} variable.
6206 This macro is obsolescent, as current systems can include both files
6207 when they exist.  New programs need not use this macro.
6208 @end defmac
6211 @defmac AC_HEADER_TIOCGWINSZ
6212 @acindex{HEADER_TIOCGWINSZ}
6213 @cvindex GWINSZ_IN_SYS_IOCTL
6214 @hdrindex{sys/ioctl.h}
6215 @hdrindex{termios.h}
6216 @c FIXME: I need clarifications from Jim.
6217 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6218 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6219 found in @file{<termios.h>}.
6221 Use:
6223 @example
6224 @group
6225 #ifdef HAVE_TERMIOS_H
6226 # include <termios.h>
6227 #endif
6229 #ifdef GWINSZ_IN_SYS_IOCTL
6230 # include <sys/ioctl.h>
6231 #endif
6232 @end group
6233 @end example
6234 @end defmac
6236 @node Generic Headers
6237 @subsection Generic Header Checks
6239 These macros are used to find system header files not covered by the
6240 ``particular'' test macros.  If you need to check the contents of a header
6241 as well as find out whether it is present, you have to write your own
6242 test for it (@pxref{Writing Tests}).
6244 @anchor{AC_CHECK_HEADER}
6245 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6246   @ovar{action-if-not-found}, @ovar{includes})
6247 @acindex{CHECK_HEADER}
6248 @caindex header_@var{header-file}
6249 If the system header file @var{header-file} is compilable, execute shell
6250 commands @var{action-if-found}, otherwise execute
6251 @var{action-if-not-found}.  If you just want to define a symbol if the
6252 header file is available, consider using @code{AC_CHECK_HEADERS}
6253 instead.
6255 @var{includes} is decoded to determine the appropriate include
6256 directives.  If omitted or empty, @file{configure} will check for both header
6257 existence (with the preprocessor) and usability (with the compiler),
6258 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
6259 there is a discrepancy between the results, a warning is issued to the
6260 user, and the compiler results are favored (@pxref{Present But
6261 Cannot Be Compiled}).  In general, favoring the compiler results means
6262 that a header will be treated as not found even though the file exists,
6263 because you did not provide enough prerequisites.
6265 Providing a non-empty @var{includes} argument allows the code to provide
6266 any prerequisites prior to including the header under test; it is common
6267 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6268 Includes}).  With an explicit fourth argument, no preprocessor test is
6269 needed.  As a special case, an @var{includes} of exactly @samp{-}
6270 triggers the older preprocessor check, which merely determines existence
6271 of the file in the preprocessor search path; this should only be used as
6272 a last resort (it is safer to determine the actual prerequisites and
6273 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
6274 it obvious that only a preprocessor check is desired).
6276 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6277 variable, with characters not suitable for a variable name mapped to
6278 underscores.
6279 @end defmac
6281 @anchor{AC_CHECK_HEADERS}
6282 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6283   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6284   @ovar{includes})
6285 @acindex{CHECK_HEADERS}
6286 @cvindex HAVE_@var{header}
6287 @caindex header_@var{header-file}
6288 For each given system header file @var{header-file} in the
6289 blank-separated argument list that exists, define
6290 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6291 is given, it is additional shell code to execute when one of the header
6292 files is found.  You can give it a value of @samp{break} to break out of
6293 the loop on the first match.  If @var{action-if-not-found} is given, it
6294 is executed when one of the header files is not found.
6296 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6297 choose the set of preprocessor directives supplied before the header
6298 under test.
6300 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6301 variable, with characters not suitable for a variable name mapped to
6302 underscores.
6303 @end defmac
6305 Previous versions of Autoconf merely checked whether the header was
6306 accepted by the preprocessor.  This was changed because the old test was
6307 inappropriate for typical uses.  Headers are typically used to compile,
6308 not merely to preprocess, and the old behavior sometimes accepted
6309 headers that clashed at compile-time (@pxref{Present But Cannot Be
6310 Compiled}).  If you need to check whether a header is preprocessable,
6311 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
6313 Actually requiring a header to compile improves the robustness of the
6314 test, but it also requires
6315 that you make sure that headers that must be included before the
6316 @var{header-file} be part of the @var{includes}, (@pxref{Default
6317 Includes}).  If looking for @file{bar.h}, which requires that
6318 @file{foo.h} be included before if it exists, we suggest the following
6319 scheme:
6321 @verbatim
6322 AC_CHECK_HEADERS([foo.h])
6323 AC_CHECK_HEADERS([bar.h], [], [],
6324 [#ifdef HAVE_FOO_H
6325 # include <foo.h>
6326 #endif
6328 @end verbatim
6330 The following variant generates smaller, faster @command{configure}
6331 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
6333 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6334 @acindex{CHECK_HEADERS_ONCE}
6335 @cvindex HAVE_@var{header}
6336 For each given system header file @var{header-file} in the
6337 blank-separated argument list that exists, define
6338 @code{HAVE_@var{header-file}} (in all capitals).
6339 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
6340 checking code at most once, so that @command{configure} is smaller and
6341 faster; but the checks cannot be conditionalized and are always done once,
6342 early during the @command{configure} run.  Thus, this macro is only safe
6343 for checking headers that do not have prerequisites beyond what
6344 @code{AC_INCLUDES_DEFAULT} provides.
6345 @end defmac
6347 @node Declarations
6348 @section Declarations
6349 @cindex Declaration, checking
6351 The following macros check for the declaration of variables and
6352 functions.  If there is no macro specifically defined to check for a
6353 symbol you need, then you can use the general macros (@pxref{Generic
6354 Declarations}) or, for more complex tests, you may use
6355 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6357 @menu
6358 * Particular Declarations::     Macros to check for certain declarations
6359 * Generic Declarations::        How to find other declarations
6360 @end menu
6362 @node Particular Declarations
6363 @subsection Particular Declaration Checks
6365 There are no specific macros for declarations.
6367 @node Generic Declarations
6368 @subsection Generic Declaration Checks
6370 These macros are used to find declarations not covered by the ``particular''
6371 test macros.
6373 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6374   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6375 @acindex{CHECK_DECL}
6376 @caindex have_decl_@var{symbol}
6377 If @var{symbol} (a function, variable, or constant) is not declared in
6378 @var{includes} and a declaration is needed, run the shell commands
6379 @var{action-if-not-found}, otherwise @var{action-if-found}.
6380 @var{includes} is a series of include directives, defaulting to
6381 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6382 prior to the declaration under test.
6384 This macro actually tests whether @var{symbol} is defined as a macro or
6385 can be used as an r-value, not whether it is really declared, because it
6386 is much safer to avoid introducing extra declarations when they are not
6387 needed.  In order to facilitate use of C++ and overloaded function
6388 declarations, it is possible to specify function argument types in
6389 parentheses for types which can be zero-initialized:
6391 @example
6392 AC_CHECK_DECL([basename(char *)])
6393 @end example
6395 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6396 variable, with characters not suitable for a variable name mapped to
6397 underscores.
6398 @end defmac
6400 @anchor{AC_CHECK_DECLS}
6401 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6402   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6403 @acindex{CHECK_DECLS}
6404 @cvindex HAVE_DECL_@var{symbol}
6405 @caindex have_decl_@var{symbol}
6406 For each of the @var{symbols} (@emph{comma}-separated list with optional
6407 function argument types for C++ overloads), define
6408 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6409 @var{symbol} is declared, otherwise to @samp{0}.  If
6410 @var{action-if-not-found} is given, it is additional shell code to
6411 execute when one of the function declarations is needed, otherwise
6412 @var{action-if-found} is executed.
6414 @var{includes} is a series of include directives, defaulting to
6415 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6416 prior to the declarations under test.
6418 This macro uses an M4 list as first argument:
6419 @example
6420 AC_CHECK_DECLS([strdup])
6421 AC_CHECK_DECLS([strlen])
6422 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6423 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6424 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6425 @end example
6427 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6428 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6429 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6430 @emph{sure} that the check was performed, use
6431 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6433 @example
6434 #if !HAVE_DECL_SYMBOL
6435 extern char *symbol;
6436 #endif
6437 @end example
6439 @noindent
6440 If the test may have not been performed, however, because it is safer
6441 @emph{not} to declare a symbol than to use a declaration that conflicts
6442 with the system's one, you should use:
6444 @example
6445 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6446 void *malloc (size_t *s);
6447 #endif
6448 @end example
6450 @noindent
6451 You fall into the second category only in extreme situations: either
6452 your files may be used without being configured, or they are used during
6453 the configuration.  In most cases the traditional approach is enough.
6455 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6456 variables, with characters not suitable for a variable name mapped to
6457 underscores.
6458 @end defmac
6460 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6461 @acindex{CHECK_DECLS_ONCE}
6462 @cvindex HAVE_DECL_@var{symbol}
6463 For each of the @var{symbols} (@emph{comma}-separated list), define
6464 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6465 @var{symbol} is declared in the default include files, otherwise to
6466 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6467 generates the checking code at most once, so that @command{configure} is
6468 smaller and faster; but the checks cannot be conditionalized and are
6469 always done once, early during the @command{configure} run.
6470 @end defmac
6473 @node Structures
6474 @section Structures
6475 @cindex Structure, checking
6477 The following macros check for the presence of certain members in C
6478 structures.  If there is no macro specifically defined to check for a
6479 member you need, then you can use the general structure-member macros
6480 (@pxref{Generic Structures}) or, for more complex tests, you may use
6481 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6483 @menu
6484 * Particular Structures::       Macros to check for certain structure members
6485 * Generic Structures::          How to find other structure members
6486 @end menu
6488 @node Particular Structures
6489 @subsection Particular Structure Checks
6491 The following macros check for certain structures or structure members.
6493 @defmac AC_STRUCT_DIRENT_D_INO
6494 @acindex{STRUCT_DIRENT_D_INO}
6495 @cvindex HAVE_STRUCT_DIRENT_D_INO
6496 @c @caindex header_dirent_dirent_h
6497 @c @caindex member_struct_dirent_d_ino
6498 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6499 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6500 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6502 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6503 @code{d_ino}, not whether its contents are always reliable.
6504 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6505 though current systems hide this detail from the user and never return
6506 zero @code{d_ino} values.
6507 Many current systems report an incorrect @code{d_ino} for a directory
6508 entry that is a mount point.
6509 @end defmac
6511 @defmac AC_STRUCT_DIRENT_D_TYPE
6512 @acindex{STRUCT_DIRENT_D_TYPE}
6513 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6514 @c @caindex header_dirent_dirent_h
6515 @c @caindex member_struct_dirent_d_type
6516 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6517 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6518 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6519 @end defmac
6521 @anchor{AC_STRUCT_ST_BLOCKS}
6522 @defmac AC_STRUCT_ST_BLOCKS
6523 @acindex{STRUCT_ST_BLOCKS}
6524 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6525 @cvindex HAVE_ST_BLOCKS
6526 @ovindex LIBOBJS
6527 @caindex member_struct_stat_st_blocks
6528 If @code{struct stat} contains an @code{st_blocks} member, define
6529 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6530 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6531 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6532 future.
6534 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6535 variable.
6536 @end defmac
6538 @defmac AC_STRUCT_TM
6539 @acindex{STRUCT_TM}
6540 @cvindex TM_IN_SYS_TIME
6541 @hdrindex{time.h}
6542 @hdrindex{sys/time.h}
6543 If @file{time.h} does not define @code{struct tm}, define
6544 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6545 had better define @code{struct tm}.
6547 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6548 current systems.  New programs need not use this macro.
6549 @end defmac
6551 @anchor{AC_STRUCT_TIMEZONE}
6552 @defmac AC_STRUCT_TIMEZONE
6553 @acindex{STRUCT_TIMEZONE}
6554 @cvindex HAVE_DECL_TZNAME
6555 @cvindex HAVE_STRUCT_TM_TM_ZONE
6556 @cvindex HAVE_TM_ZONE
6557 @cvindex HAVE_TZNAME
6558 @c @caindex member_struct_tm_tm_zone
6559 @c @caindex struct_tm
6560 Figure out how to get the current timezone.  If @code{struct tm} has a
6561 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6562 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6563 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6564 define @code{HAVE_DECL_TZNAME}.
6565 @end defmac
6567 @node Generic Structures
6568 @subsection Generic Structure Checks
6570 These macros are used to find structure members not covered by the
6571 ``particular'' test macros.
6573 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6574   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6575   @dvar{includes, AC_INCLUDES_DEFAULT})
6576 @acindex{CHECK_MEMBER}
6577 @caindex member_@var{aggregate}_@var{member}
6578 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6579 If no @var{includes} are specified, the default includes are used
6580 (@pxref{Default Includes}).
6582 @example
6583 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6584                 [AC_MSG_ERROR([we need `passwd.pw_gecos'])],
6585                 [[#include <pwd.h>]])
6586 @end example
6588 You can use this macro for submembers:
6590 @example
6591 AC_CHECK_MEMBER(struct top.middle.bot)
6592 @end example
6594 This macro caches its result in the
6595 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6596 characters not suitable for a variable name mapped to underscores.
6597 @end defmac
6599 @anchor{AC_CHECK_MEMBERS}
6600 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6601   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6602 @acindex{CHECK_MEMBERS}
6603 @cvindex HAVE_@var{aggregate}_@var{member}
6604 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6605 @var{members} using the previous macro.  When @var{member} belongs to
6606 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6607 capitals, with spaces and dots replaced by underscores).  If
6608 @var{action-if-found} is given, it is executed for each of the found
6609 members.  If @var{action-if-not-found} is given, it is executed for each
6610 of the members that could not be found.
6612 @var{includes} is a series of include directives, defaulting to
6613 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6614 prior to the members under test.
6616 This macro uses M4 lists:
6617 @example
6618 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6619 @end example
6620 @end defmac
6623 @node Types
6624 @section Types
6625 @cindex Types
6626 @cindex C types
6628 The following macros check for C types, either builtin or typedefs.  If
6629 there is no macro specifically defined to check for a type you need, and
6630 you don't need to check for any special properties of it, then you can
6631 use a general type-check macro.
6633 @menu
6634 * Particular Types::            Special handling to find certain types
6635 * Generic Types::               How to find other types
6636 @end menu
6638 @node Particular Types
6639 @subsection Particular Type Checks
6641 @hdrindex{sys/types.h}
6642 @hdrindex{stdlib.h}
6643 @hdrindex{stdint.h}
6644 @hdrindex{inttypes.h}
6645 These macros check for particular C types in @file{sys/types.h},
6646 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6647 exist.
6649 The Gnulib @code{stdint} module is an alternate way to define many of
6650 these symbols; it is useful if you prefer your code to assume a
6651 C99-or-better environment.  @xref{Gnulib}.
6653 @anchor{AC_TYPE_GETGROUPS}
6654 @defmac AC_TYPE_GETGROUPS
6655 @acindex{TYPE_GETGROUPS}
6656 @cvindex GETGROUPS_T
6657 @caindex type_getgroups
6658 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6659 is the base type of the array argument to @code{getgroups}.
6661 This macro caches the base type in the @code{ac_cv_type_getgroups}
6662 variable.
6663 @end defmac
6665 @defmac AC_TYPE_INT8_T
6666 @acindex{TYPE_INT8_T}
6667 @cvindex HAVE_INT8_T
6668 @cvindex int8_t
6669 @caindex c_int8_t
6670 If @file{stdint.h} or @file{inttypes.h} does not define the type
6671 @code{int8_t}, define @code{int8_t} to a signed
6672 integer type that is exactly 8 bits wide and that uses two's complement
6673 representation, if such a type exists.
6674 If you are worried about porting to hosts that lack such a type, you can
6675 use the results of this macro in C89-or-later code as follows:
6677 @example
6678 #if HAVE_STDINT_H
6679 # include <stdint.h>
6680 #endif
6681 #if defined INT8_MAX || defined int8_t
6682  @emph{code using int8_t}
6683 #else
6684  @emph{complicated alternative using >8-bit 'signed char'}
6685 #endif
6686 @end example
6688 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6689 @end defmac
6691 @defmac AC_TYPE_INT16_T
6692 @acindex{TYPE_INT16_T}
6693 @cvindex HAVE_INT16_T
6694 @cvindex int16_t
6695 @caindex c_int16_t
6696 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6697 @end defmac
6699 @defmac AC_TYPE_INT32_T
6700 @acindex{TYPE_INT32_T}
6701 @cvindex HAVE_INT32_T
6702 @cvindex int32_t
6703 @caindex c_int32_t
6704 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6705 @end defmac
6707 @defmac AC_TYPE_INT64_T
6708 @acindex{TYPE_INT64_T}
6709 @cvindex HAVE_INT64_T
6710 @cvindex int64_t
6711 @caindex c_int64_t
6712 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6713 @end defmac
6715 @defmac AC_TYPE_INTMAX_T
6716 @acindex{TYPE_INTMAX_T}
6717 @cvindex HAVE_INTMAX_T
6718 @cvindex intmax_t
6719 @c @caindex type_intmax_t
6720 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6721 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6722 widest signed integer type.
6723 @end defmac
6725 @defmac AC_TYPE_INTPTR_T
6726 @acindex{TYPE_INTPTR_T}
6727 @cvindex HAVE_INTPTR_T
6728 @cvindex intptr_t
6729 @c @caindex type_intptr_t
6730 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6731 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6732 signed integer type wide enough to hold a pointer, if such a type
6733 exists.
6734 @end defmac
6736 @defmac AC_TYPE_LONG_DOUBLE
6737 @acindex{TYPE_LONG_DOUBLE}
6738 @cvindex HAVE_LONG_DOUBLE
6739 @caindex type_long_double
6740 If the C compiler supports a working @code{long double} type, define
6741 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6742 same range and precision as @code{double}.
6744 This macro caches its result in the @code{ac_cv_type_long_double}
6745 variable.
6747 This macro is obsolescent, as current C compilers support @code{long
6748 double}.  New programs need not use this macro.
6749 @end defmac
6751 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6752 @acindex{TYPE_LONG_DOUBLE_WIDER}
6753 @cvindex HAVE_LONG_DOUBLE_WIDER
6754 @caindex type_long_double_wider
6755 If the C compiler supports a working @code{long double} type with more
6756 range or precision than the @code{double} type, define
6757 @code{HAVE_LONG_DOUBLE_WIDER}.
6759 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6760 variable.
6761 @end defmac
6763 @defmac AC_TYPE_LONG_LONG_INT
6764 @acindex{TYPE_LONG_LONG_INT}
6765 @cvindex HAVE_LONG_LONG_INT
6766 @caindex type_long_long_int
6767 If the C compiler supports a working @code{long long int} type, define
6768 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6769 @code{long long int} values in preprocessor @code{#if} expressions,
6770 because too many compilers mishandle such expressions.
6771 @xref{Preprocessor Arithmetic}.
6773 This macro caches its result in the @code{ac_cv_type_long_long_int}
6774 variable.
6775 @end defmac
6777 @defmac AC_TYPE_MBSTATE_T
6778 @acindex{TYPE_MBSTATE_T}
6779 @cvindex mbstate_t
6780 @hdrindex{wchar.h}
6781 @caindex type_mbstate_t
6782 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6783 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6784 @code{<wchar.h>} does not declare it.
6786 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6787 variable.
6788 @end defmac
6790 @anchor{AC_TYPE_MODE_T}
6791 @defmac AC_TYPE_MODE_T
6792 @acindex{TYPE_MODE_T}
6793 @cvindex mode_t
6794 @caindex type_mode_t
6795 Define @code{mode_t} to a suitable type, if standard headers do not
6796 define it.
6798 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6799 @end defmac
6801 @anchor{AC_TYPE_OFF_T}
6802 @defmac AC_TYPE_OFF_T
6803 @acindex{TYPE_OFF_T}
6804 @cvindex off_t
6805 @caindex type_off_t
6806 Define @code{off_t} to a suitable type, if standard headers do not
6807 define it.
6809 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6810 @end defmac
6812 @anchor{AC_TYPE_PID_T}
6813 @defmac AC_TYPE_PID_T
6814 @acindex{TYPE_PID_T}
6815 @cvindex pid_t
6816 @caindex type_pid_t
6817 Define @code{pid_t} to a suitable type, if standard headers do not
6818 define it.
6820 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6821 @end defmac
6823 @anchor{AC_TYPE_SIZE_T}
6824 @defmac AC_TYPE_SIZE_T
6825 @acindex{TYPE_SIZE_T}
6826 @cvindex size_t
6827 @caindex type_size_t
6828 Define @code{size_t} to a suitable type, if standard headers do not
6829 define it.
6831 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6832 @end defmac
6834 @defmac AC_TYPE_SSIZE_T
6835 @acindex{TYPE_SSIZE_T}
6836 @cvindex ssize_t
6837 @caindex type_ssize_t
6838 Define @code{ssize_t} to a suitable type, if standard headers do not
6839 define it.
6841 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6842 @end defmac
6844 @anchor{AC_TYPE_UID_T}
6845 @defmac AC_TYPE_UID_T
6846 @acindex{TYPE_UID_T}
6847 @cvindex uid_t
6848 @cvindex gid_t
6849 @caindex type_uid_t
6850 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6851 headers do not define them.
6853 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6854 @end defmac
6856 @defmac AC_TYPE_UINT8_T
6857 @acindex{TYPE_UINT8_T}
6858 @cvindex HAVE_UINT8_T
6859 @cvindex uint8_t
6860 @caindex c_uint8_t
6861 If @file{stdint.h} or @file{inttypes.h} does not define the type
6862 @code{uint8_t}, define @code{uint8_t} to an
6863 unsigned integer type that is exactly 8 bits wide, if such a type
6864 exists.
6865 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6866 @end defmac
6868 @defmac AC_TYPE_UINT16_T
6869 @acindex{TYPE_UINT16_T}
6870 @cvindex HAVE_UINT16_T
6871 @cvindex uint16_t
6872 @caindex c_uint16_t
6873 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6874 @end defmac
6876 @defmac AC_TYPE_UINT32_T
6877 @acindex{TYPE_UINT32_T}
6878 @cvindex HAVE_UINT32_T
6879 @cvindex uint32_t
6880 @caindex c_uint32_t
6881 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6882 @end defmac
6884 @defmac AC_TYPE_UINT64_T
6885 @acindex{TYPE_UINT64_T}
6886 @cvindex HAVE_UINT64_T
6887 @cvindex uint64_t
6888 @caindex c_uint64_t
6889 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6890 @end defmac
6892 @defmac AC_TYPE_UINTMAX_T
6893 @acindex{TYPE_UINTMAX_T}
6894 @cvindex HAVE_UINTMAX_T
6895 @cvindex uintmax_t
6896 @c @caindex type_uintmax_t
6897 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6898 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6899 widest unsigned integer type.
6900 @end defmac
6902 @defmac AC_TYPE_UINTPTR_T
6903 @acindex{TYPE_UINTPTR_T}
6904 @cvindex HAVE_UINTPTR_T
6905 @cvindex uintptr_t
6906 @c @caindex type_uintptr_t
6907 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6908 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6909 unsigned integer type wide enough to hold a pointer, if such a type
6910 exists.
6911 @end defmac
6913 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6914 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6915 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6916 @caindex type_unsigned_long_long_int
6917 If the C compiler supports a working @code{unsigned long long int} type,
6918 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6919 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6920 because too many compilers mishandle such expressions.
6921 @xref{Preprocessor Arithmetic}.
6923 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6924 variable.
6925 @end defmac
6927 @node Generic Types
6928 @subsection Generic Type Checks
6930 These macros are used to check for types not covered by the ``particular''
6931 test macros.
6933 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6934   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6935 @acindex{CHECK_TYPE}
6936 @caindex type_@var{type}
6937 Check whether @var{type} is defined.  It may be a compiler builtin type
6938 or defined by the @var{includes}.  @var{includes} is a series of include
6939 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6940 Includes}), which are used prior to the type under test.
6942 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6943 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6944 same test is applied when compiling for C++, which means that in C++
6945 @var{type} should be a type-id and should not be an anonymous
6946 @samp{struct} or @samp{union}.
6948 This macro caches its result in the @code{ac_cv_type_@var{type}}
6949 variable, with @samp{*} mapped to @samp{p} and other characters not
6950 suitable for a variable name mapped to underscores.
6951 @end defmac
6954 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6955   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6956 @acindex{CHECK_TYPES}
6957 @cvindex HAVE_@var{type}
6958 For each @var{type} of the @var{types} that is defined, define
6959 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6960 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6961 specified, the default includes are used (@pxref{Default Includes}).  If
6962 @var{action-if-found} is given, it is additional shell code to execute
6963 when one of the types is found.  If @var{action-if-not-found} is given,
6964 it is executed when one of the types is not found.
6966 This macro uses M4 lists:
6967 @example
6968 AC_CHECK_TYPES([ptrdiff_t])
6969 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6970 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6971 @end example
6973 @end defmac
6975 Autoconf, up to 2.13, used to provide to another version of
6976 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6977 compatibility, a simple heuristic, quite safe but not totally, is
6978 implemented.  In case of doubt, read the documentation of the former
6979 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6982 @node Compilers and Preprocessors
6983 @section Compilers and Preprocessors
6984 @cindex Compilers
6985 @cindex Preprocessors
6987 @ovindex EXEEXT
6988 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6989 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6990 the output of the compiler, typically to the empty string if
6991 Posix and @samp{.exe} if a DOS variant.
6993 @ovindex OBJEXT
6994 They also define the output variable @code{OBJEXT} based on the
6995 output of the compiler, after @file{.c} files have been excluded, typically
6996 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6998 If the compiler being used does not produce executables, the tests fail.  If
6999 the executables can't be run, and cross-compilation is not enabled, they
7000 fail too.  @xref{Manual Configuration}, for more on support for cross
7001 compiling.
7003 @menu
7004 * Specific Compiler Characteristics::  Some portability issues
7005 * Generic Compiler Characteristics::  Language independent tests and features
7006 * C Compiler::                  Checking its characteristics
7007 * C++ Compiler::                Likewise
7008 * Objective C Compiler::        Likewise
7009 * Objective C++ Compiler::      Likewise
7010 * Erlang Compiler and Interpreter::  Likewise
7011 * Fortran Compiler::            Likewise
7012 * Go Compiler::                 Likewise
7013 @end menu
7015 @node Specific Compiler Characteristics
7016 @subsection Specific Compiler Characteristics
7018 Some compilers exhibit different behaviors.
7020 @table @asis
7021 @item Static/Dynamic Expressions
7022 Autoconf relies on a trick to extract one bit of information from the C
7023 compiler: using negative array sizes.  For instance the following
7024 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7025 bytes wide:
7027 @example
7028 static int test_array[sizeof (int) == 4 ? 1 : -1];
7029 @end example
7031 @noindent
7032 To our knowledge, there is a single compiler that does not support this
7033 trick: the HP C compilers (the real ones, not only the
7034 ``bundled'') on HP-UX 11.00.
7035 They incorrectly reject the above program with the diagnostic
7036 ``Variable-length arrays cannot have static storage.''
7037 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7038 not from the @code{? 1 : -1}, and
7039 Autoconf works around this problem by casting @code{sizeof (int)} to
7040 @code{long int} before comparing it.
7041 @end table
7043 @node Generic Compiler Characteristics
7044 @subsection Generic Compiler Characteristics
7046 @anchor{AC_CHECK_SIZEOF}
7047 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7048   @dvar{includes, AC_INCLUDES_DEFAULT})
7049 @acindex{CHECK_SIZEOF}
7050 @cvindex SIZEOF_@var{type-or-expr}
7051 @caindex sizeof_@var{type-or-expr}
7052 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7053 the size in bytes of @var{type-or-expr}, which may be either a type or
7054 an expression returning a value that has a size.  If the expression
7055 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7056 @var{includes} is a series of include directives, defaulting to
7057 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7058 prior to the expression under test.
7060 This macro now works even when cross-compiling.  The @var{unused}
7061 argument was used when cross-compiling.
7063 For example, the call
7065 @example
7066 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7067 AC_CHECK_SIZEOF([int *])
7068 @end example
7070 @noindent
7071 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7073 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7074 variable, with @samp{*} mapped to @samp{p} and other characters not
7075 suitable for a variable name mapped to underscores.
7076 @end defmac
7078 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7079 @acindex{CHECK_ALIGNOF}
7080 @cvindex ALIGNOF_@var{type}
7081 @caindex alignof_@var{type-or-expr}
7082 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7083 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7084 a structure member declaration.  If @samp{type} is unknown, the result
7085 is 0.  If no @var{includes} are specified, the default includes are used
7086 (@pxref{Default Includes}).
7088 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7089 variable, with @samp{*} mapped to @samp{p} and other characters not
7090 suitable for a variable name mapped to underscores.
7091 @end defmac
7093 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7094   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7095 @acindex{COMPUTE_INT}
7096 Store into the shell variable @var{var} the value of the integer
7097 @var{expression}.  The
7098 value should fit in an initializer in a C variable of type @code{signed
7099 long}.  To support cross compilation (in which case, the macro only works on
7100 hosts that use twos-complement arithmetic), it should be possible to evaluate
7101 the expression at compile-time.  If no @var{includes} are specified, the
7102 default includes are used (@pxref{Default Includes}).
7104 Execute @var{action-if-fails} if the value cannot be determined correctly.
7105 @end defmac
7107 @defmac AC_LANG_WERROR
7108 @acindex{LANG_WERROR}
7109 Normally Autoconf ignores warnings generated by the compiler, linker, and
7110 preprocessor.  If this macro is used, warnings count as fatal
7111 errors for the current language.  This macro is useful when the
7112 results of configuration are used where warnings are unacceptable; for
7113 instance, if parts of a program are built with the GCC
7114 @option{-Werror}
7115 option.  If the whole program is built using @option{-Werror} it is
7116 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7117 etc.).
7118 @end defmac
7120 @defmac AC_OPENMP
7121 @acindex{OPENMP}
7122 @cvindex _OPENMP
7123 @ovindex OPENMP_CFLAGS
7124 @ovindex OPENMP_CXXFLAGS
7125 @ovindex OPENMP_FFLAGS
7126 @ovindex OPENMP_FCFLAGS
7127 @caindex prog_c_openmp
7128 @caindex prog_cxx_openmp
7129 @caindex prog_f77_openmp
7130 @caindex prog_fc_openmp
7131 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7132 and Fortran that simplify optimization of shared memory parallelism,
7133 which is a common problem on multicore CPUs.
7135 If the current language is C, the macro @code{AC_OPENMP} sets the
7136 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7137 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7138 compiler already supports OpenMP, if it has no way to activate OpenMP
7139 support, or if the user rejects OpenMP support by invoking
7140 @samp{configure} with the @samp{--disable-openmp} option.
7142 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7143 preprocessing program source, and when linking programs.  Therefore you
7144 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7145 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7146 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7147 OpenMP support is revealed at compile time by the preprocessor macro
7148 @code{_OPENMP}.
7150 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7151 shared library to the program's dependencies, so its use is recommended
7152 only on programs that actually require OpenMP.
7154 If the current language is C++, @code{AC_OPENMP} sets the variable
7155 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7156 hold as for C.
7158 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7159 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7160 respectively.  Similar remarks as for C hold, except that
7161 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7162 signals OpenMP support.
7164 For portability, it is best to avoid spaces between @samp{#} and
7165 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7166 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7167 latter.
7169 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7170 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7171 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7172 @end defmac
7174 @node C Compiler
7175 @subsection C Compiler Characteristics
7177 The following macros provide ways to find and exercise a C Compiler.
7178 There are a few constructs that ought to be avoided, but do not deserve
7179 being checked for, since they can easily be worked around.
7181 @table @asis
7182 @item Don't use lines containing solitary backslashes
7183 They tickle a bug in the HP-UX C compiler (checked on
7184 HP-UX 10.20,
7185 11.00, and 11i).  When given the following source:
7187 @example
7188 #ifdef __STDC__
7190 * A comment with backslash-newlines in it.  %@{ %@} *\
7193 char str[] = "\\
7194 " A string with backslash-newlines in it %@{ %@} \\
7196 char apostrophe = '\\
7200 #endif
7201 @end example
7203 @noindent
7204 the compiler incorrectly fails with the diagnostics ``Non-terminating
7205 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7206 Removing the lines with solitary backslashes solves the problem.
7208 @item Don't compile several files at once if output matters to you
7209 Some compilers, such as HP's, report names of files being
7210 compiled when given more than one file operand.  For instance:
7212 @example
7213 $ @kbd{cc a.c b.c}
7214 a.c:
7215 b.c:
7216 @end example
7218 @noindent
7219 This can cause problems if you observe the output of the compiler to
7220 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7221 b.o} solves the issue.
7223 @item Don't rely on @code{#error} failing
7224 The IRIX C compiler does not fail when #error is preprocessed; it
7225 simply emits a diagnostic and continues, exiting successfully.  So,
7226 instead of an error directive like @code{#error "Unsupported word size"}
7227 it is more portable to use an invalid directive like @code{#Unsupported
7228 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7229 OK, since installers with inadequate compilers like IRIX can simply
7230 examine these compilers' diagnostic output.
7232 @item Don't rely on correct @code{#line} support
7233 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7234 diagnoses @code{#line} directives whose line
7235 numbers are greater than 32767.  Nothing in Posix
7236 makes this invalid.  That is why Autoconf stopped issuing
7237 @code{#line} directives.
7238 @end table
7240 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7241 @acindex{PROG_CC}
7242 @evindex CC
7243 @evindex CFLAGS
7244 @ovindex CC
7245 @ovindex CFLAGS
7246 @caindex prog_cc_c89
7247 Determine a C compiler to use.  If @code{CC} is not already set in the
7248 environment, check for @code{gcc} and @code{cc}, then for other C
7249 compilers.  Set output variable @code{CC} to the name of the compiler
7250 found.
7252 This macro may, however, be invoked with an optional first argument
7253 which, if specified, must be a blank-separated list of C compilers to
7254 search for.  This just gives the user an opportunity to specify an
7255 alternative search list for the C compiler.  For example, if you didn't
7256 like the default order, then you could invoke @code{AC_PROG_CC} like
7257 this:
7259 @example
7260 AC_PROG_CC([gcc cl cc])
7261 @end example
7263 If the C compiler does not handle function prototypes correctly by
7264 default, try to add an option to output variable @code{CC} to make it
7265 so.  This macro tries various options that select standard-conformance
7266 modes on various systems.
7268 After calling this macro you can check whether the C compiler has been
7269 set to accept ANSI C89 (ISO C90); if not, the shell
7270 variable
7271 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
7272 @code{AC_C_PROTOTYPES} below.
7274 If using the GNU C compiler, set shell variable @code{GCC} to
7275 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7276 it to @option{-g -O2} for the GNU C compiler (@option{-O2} on systems
7277 where GCC does not accept @option{-g}), or @option{-g} for
7278 other compilers.  If your package does not like this default, then it is
7279 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7280 and before @code{AC_PROG_CC} to select an empty default instead.
7282 Many Autoconf macros use a compiler, and thus call
7283 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7284 determined before the body of the outermost @code{AC_DEFUN} macro.
7285 Although @code{AC_PROG_CC} is safe to directly expand multiple times, it
7286 performs certain checks (such as the proper value of @env{EXEEXT}) only
7287 on the first invocation.  Therefore, care must be used when invoking
7288 this macro from within another macro rather than at the top level
7289 (@pxref{Expanded Before Required}).
7290 @end defmac
7292 @anchor{AC_PROG_CC_C_O}
7293 @defmac AC_PROG_CC_C_O
7294 @acindex{PROG_CC_C_O}
7295 @cvindex NO_MINUS_C_MINUS_O
7296 @caindex prog_cc_@var{compiler}_c_o
7297 If the C compiler does not accept the @option{-c} and @option{-o} options
7298 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7299 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7300 the first @code{cc} in the path.  The test fails if one fails.  This
7301 macro was created for GNU Make to choose the default C compilation
7302 rule.
7304 For the compiler @var{compiler}, this macro caches its result in the
7305 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7306 @end defmac
7309 @defmac AC_PROG_CPP
7310 @acindex{PROG_CPP}
7311 @evindex CPP
7312 @ovindex CPP
7313 Set output variable @code{CPP} to a command that runs the
7314 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7315 It is only portable to run @code{CPP} on files with a @file{.c}
7316 extension.
7318 Some preprocessors don't indicate missing include files by the error
7319 status.  For such preprocessors an internal variable is set that causes
7320 other macros to check the standard error from the preprocessor and
7321 consider the test failed if any warnings have been reported.
7322 For most preprocessors, though, warnings do not cause include-file
7323 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7324 @end defmac
7326 @defmac AC_PROG_CPP_WERROR
7327 @acindex{PROG_CPP_WERROR}
7328 @ovindex CPP
7329 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7330 preprocessor as errors even if the preprocessor exit status indicates
7331 success.  This is useful for avoiding headers that generate mandatory
7332 warnings, such as deprecation notices.
7333 @end defmac
7336 The following macros check for C compiler or machine architecture
7337 features.  To check for characteristics not listed here, use
7338 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7339 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7341 @defmac AC_PROG_CC_STDC
7342 @acindex{PROG_CC_STDC}
7343 @caindex prog_cc_stdc
7344 If the C compiler cannot compile ISO Standard C (currently
7345 C99), try to add an option to output variable @code{CC} to make it work.
7346 If the compiler does not support C99, fall back to supporting
7347 ANSI C89 (ISO C90).
7349 After calling this macro you can check whether the C compiler has been
7350 set to accept Standard C; if not, the shell variable
7351 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7352 @end defmac
7354 @defmac AC_PROG_CC_C89
7355 @acindex{PROG_CC_C89}
7356 @caindex prog_cc_c89
7357 If the C compiler is not in ANSI C89 (ISO C90) mode by
7358 default, try to add an option to output variable @code{CC} to make it
7359 so.  This macro tries various options that select ANSI C89 on
7360 some system or another, preferring extended functionality modes over
7361 strict conformance modes.  It considers the compiler to be in
7362 ANSI C89 mode if it handles function prototypes correctly.
7364 After calling this macro you can check whether the C compiler has been
7365 set to accept ANSI C89; if not, the shell variable
7366 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
7368 This macro is called automatically by @code{AC_PROG_CC}.
7369 @end defmac
7371 @defmac AC_PROG_CC_C99
7372 @acindex{PROG_CC_C99}
7373 @caindex prog_cc_c99
7374 If the C compiler is not in C99 mode by default, try to add an
7375 option to output variable @code{CC} to make it so.  This macro tries
7376 various options that select C99 on some system or another, preferring
7377 extended functionality modes over strict conformance modes.  It
7378 considers the compiler to be in C99 mode if it handles @code{_Bool},
7379 @code{//} comments, flexible array members, @code{inline}, signed and
7380 unsigned @code{long long int}, mixed code and declarations, named
7381 initialization of structs,
7382 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
7383 in @code{for} loops, and variable length arrays.
7385 After calling this macro you can check whether the C compiler has been
7386 set to accept C99; if not, the shell variable
7387 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
7388 @end defmac
7390 @defmac AC_C_BACKSLASH_A
7391 @acindex{C_BACKSLASH_A}
7392 @cvindex HAVE_C_BACKSLASH_A
7393 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7394 @samp{\a}.
7396 This macro is obsolescent, as current C compilers understand @samp{\a}.
7397 New programs need not use this macro.
7398 @end defmac
7400 @anchor{AC_C_BIGENDIAN}
7401 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7402   @ovar{action-if-unknown}, @ovar{action-if-universal})
7403 @acindex{C_BIGENDIAN}
7404 @cvindex WORDS_BIGENDIAN
7405 @cindex Endianness
7406 If words are stored with the most significant byte first (like Motorola
7407 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7408 the least significant byte first (like Intel and VAX CPUs), execute
7409 @var{action-if-false}.
7411 This macro runs a test-case if endianness cannot be determined from the
7412 system header files.  When cross-compiling, the test-case is not run but
7413 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7414 the latter case fails to determine the byte sex of the host system.
7416 In some cases a single run of a compiler can generate code for multiple
7417 architectures.  This can happen, for example, when generating Mac OS X
7418 universal binary files, which work on both PowerPC and Intel
7419 architectures.  In this case, the different variants might be for
7420 different architectures whose endiannesses differ.  If
7421 @command{configure} detects this, it executes @var{action-if-universal}
7422 instead of @var{action-if-unknown}.
7424 The default for @var{action-if-true} is to define
7425 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7426 nothing.  The default for @var{action-if-unknown} is to
7427 abort configure and tell the installer how to bypass this test.
7428 And finally, the default for @var{action-if-universal} is to ensure that
7429 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7430 detected and the current code is big-endian; this default works only if
7431 @command{autoheader} is used (@pxref{autoheader Invocation}).
7433 If you use this macro without specifying @var{action-if-universal}, you
7434 should also use @code{AC_CONFIG_HEADERS}; otherwise
7435 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7436 binary files.
7437 @end defmac
7439 @anchor{AC_C_CONST}
7440 @defmac AC_C_CONST
7441 @acindex{C_CONST}
7442 @cvindex const
7443 @caindex c_const
7444 If the C compiler does not fully support the @code{const} keyword,
7445 define @code{const} to be empty.  Some C compilers that do
7446 not define @code{__STDC__} do support @code{const}; some compilers that
7447 define @code{__STDC__} do not completely support @code{const}.  Programs
7448 can simply use @code{const} as if every C compiler supported it; for
7449 those that don't, the makefile or configuration header file
7450 defines it as empty.
7452 Occasionally installers use a C++ compiler to compile C code, typically
7453 because they lack a C compiler.  This causes problems with @code{const},
7454 because C and C++ treat @code{const} differently.  For example:
7456 @example
7457 const int foo;
7458 @end example
7460 @noindent
7461 is valid in C but not in C++.  These differences unfortunately cannot be
7462 papered over by defining @code{const} to be empty.
7464 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7465 as this generally yields better results in practice.  However, using a
7466 C++ compiler to compile C code is not recommended or supported, and
7467 installers who run into trouble in this area should get a C compiler
7468 like GCC to compile their C code.
7470 This macro caches its result in the @code{ac_cv_c_const} variable.
7472 This macro is obsolescent, as current C compilers support @code{const}.
7473 New programs need not use this macro.
7474 @end defmac
7476 @defmac AC_C_RESTRICT
7477 @acindex{C_RESTRICT}
7478 @cvindex restrict
7479 @caindex c_restrict
7480 If the C compiler recognizes a variant spelling for the @code{restrict}
7481 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7482 then define @code{restrict} to that; this is more likely to do the right
7483 thing with compilers that support language variants where plain
7484 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7485 recognizes the @code{restrict} keyword, don't do anything.
7486 Otherwise, define @code{restrict} to be empty.
7487 Thus, programs may simply use @code{restrict} as if every C compiler
7488 supported it; for those that do not, the makefile
7489 or configuration header defines it away.
7491 Although support in C++ for the @code{restrict} keyword is not
7492 required, several C++ compilers do accept the keyword.
7493 This macro works for them, too.
7495 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7496 if @code{restrict} is not supported, and a supported spelling otherwise.
7497 @end defmac
7499 @defmac AC_C_VOLATILE
7500 @acindex{C_VOLATILE}
7501 @cvindex volatile
7502 If the C compiler does not understand the keyword @code{volatile},
7503 define @code{volatile} to be empty.  Programs can simply use
7504 @code{volatile} as if every C compiler supported it; for those that do
7505 not, the makefile or configuration header defines it as
7506 empty.
7508 If the correctness of your program depends on the semantics of
7509 @code{volatile}, simply defining it to be empty does, in a sense, break
7510 your code.  However, given that the compiler does not support
7511 @code{volatile}, you are at its mercy anyway.  At least your
7512 program compiles, when it wouldn't before.
7513 @xref{Volatile Objects}, for more about @code{volatile}.
7515 In general, the @code{volatile} keyword is a standard C feature, so
7516 you might expect that @code{volatile} is available only when
7517 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7518 support volatile, but does not define @code{__STDC__}.
7520 This macro is obsolescent, as current C compilers support @code{volatile}.
7521 New programs need not use this macro.
7522 @end defmac
7524 @anchor{AC_C_INLINE}
7525 @defmac AC_C_INLINE
7526 @acindex{C_INLINE}
7527 @cvindex inline
7528 If the C compiler supports the keyword @code{inline}, do nothing.
7529 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7530 if it accepts one of those, otherwise define @code{inline} to be empty.
7531 @end defmac
7533 @anchor{AC_C_CHAR_UNSIGNED}
7534 @defmac AC_C_CHAR_UNSIGNED
7535 @acindex{C_CHAR_UNSIGNED}
7536 @cvindex __CHAR_UNSIGNED__
7537 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7538 unless the C compiler predefines it.
7540 These days, using this macro is not necessary.  The same information can
7541 be determined by this portable alternative, thus avoiding the use of
7542 preprocessor macros in the namespace reserved for the implementation.
7544 @example
7545 #include <limits.h>
7546 #if CHAR_MIN == 0
7547 # define CHAR_UNSIGNED 1
7548 #endif
7549 @end example
7550 @end defmac
7552 @defmac AC_C_STRINGIZE
7553 @acindex{C_STRINGIZE}
7554 @cvindex HAVE_STRINGIZE
7555 If the C preprocessor supports the stringizing operator, define
7556 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7557 found in macros such as this:
7559 @example
7560 #define x(y) #y
7561 @end example
7563 This macro is obsolescent, as current C compilers support the
7564 stringizing operator.  New programs need not use this macro.
7565 @end defmac
7567 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7568 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7569 @cvindex FLEXIBLE_ARRAY_MEMBER
7570 If the C compiler supports flexible array members, define
7571 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7572 That way, a declaration like this:
7574 @example
7575 struct s
7576   @{
7577     size_t n_vals;
7578     double val[FLEXIBLE_ARRAY_MEMBER];
7579   @};
7580 @end example
7582 @noindent
7583 will let applications use the ``struct hack'' even with compilers that
7584 do not support flexible array members.  To allocate and use such an
7585 object, you can use code like this:
7587 @example
7588 size_t i;
7589 size_t n = compute_value_count ();
7590 struct s *p =
7591    malloc (offsetof (struct s, val)
7592            + n * sizeof (double));
7593 p->n_vals = n;
7594 for (i = 0; i < n; i++)
7595   p->val[i] = compute_value (i);
7596 @end example
7597 @end defmac
7599 @defmac AC_C_VARARRAYS
7600 @acindex{C_VARARRAYS}
7601 @cvindex HAVE_C_VARARRAYS
7602 If the C compiler supports variable-length arrays, define
7603 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7604 storage duration whose length is determined at run time, when the array
7605 is declared.
7606 @end defmac
7608 @defmac AC_C_TYPEOF
7609 @acindex{C_TYPEOF}
7610 @cvindex HAVE_TYPEOF
7611 @cvindex typeof
7612 If the C compiler supports GCC's @code{typeof} syntax either
7613 directly or
7614 through a different spelling of the keyword (e.g., @code{__typeof__}),
7615 define @code{HAVE_TYPEOF}.  If the support is available only through a
7616 different spelling, define @code{typeof} to that spelling.
7617 @end defmac
7619 @defmac AC_C_PROTOTYPES
7620 @acindex{C_PROTOTYPES}
7621 @cvindex PROTOTYPES
7622 @cvindex __PROTOTYPES
7623 @cvindex PARAMS
7624 If function prototypes are understood by the compiler (as determined by
7625 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7626 Defining @code{__PROTOTYPES} is for the benefit of
7627 header files that cannot use macros that infringe on user name space.
7629 This macro is obsolescent, as current C compilers support prototypes.
7630 New programs need not use this macro.
7631 @end defmac
7633 @anchor{AC_PROG_GCC_TRADITIONAL}
7634 @defmac AC_PROG_GCC_TRADITIONAL
7635 @acindex{PROG_GCC_TRADITIONAL}
7636 @ovindex CC
7637 Add @option{-traditional} to output variable @code{CC} if using the
7638 GNU C compiler and @code{ioctl} does not work properly without
7639 @option{-traditional}.  That usually happens when the fixed header files
7640 have not been installed on an old system.
7642 This macro is obsolescent, since current versions of the GNU C
7643 compiler fix the header files automatically when installed.
7644 @end defmac
7647 @node C++ Compiler
7648 @subsection C++ Compiler Characteristics
7651 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7652 @acindex{PROG_CXX}
7653 @evindex CXX
7654 @evindex CXXFLAGS
7655 @ovindex CXX
7656 @ovindex CXXFLAGS
7657 Determine a C++ compiler to use.  Check whether the environment variable
7658 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7659 variable @code{CXX} to its value.
7661 Otherwise, if the macro is invoked without an argument, then search for
7662 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7663 then other names).  If none of those checks succeed, then as a last
7664 resort set @code{CXX} to @code{g++}.
7666 This macro may, however, be invoked with an optional first argument
7667 which, if specified, must be a blank-separated list of C++ compilers to
7668 search for.  This just gives the user an opportunity to specify an
7669 alternative search list for the C++ compiler.  For example, if you
7670 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7671 like this:
7673 @example
7674 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7675 @end example
7677 If using the GNU C++ compiler, set shell variable @code{GXX} to
7678 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7679 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7680 systems where G++ does not accept @option{-g}), or @option{-g} for other
7681 compilers.  If your package does not like this default, then it is
7682 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7683 and before @code{AC_PROG_CXX} to select an empty default instead.
7685 @end defmac
7687 @defmac AC_PROG_CXXCPP
7688 @acindex{PROG_CXXCPP}
7689 @evindex CXXCPP
7690 @ovindex CXXCPP
7691 Set output variable @code{CXXCPP} to a command that runs the C++
7692 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7693 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7694 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7696 Some preprocessors don't indicate missing include files by the error
7697 status.  For such preprocessors an internal variable is set that causes
7698 other macros to check the standard error from the preprocessor and
7699 consider the test failed if any warnings have been reported.  However,
7700 it is not known whether such broken preprocessors exist for C++.
7701 @end defmac
7703 @defmac AC_PROG_CXX_C_O
7704 @acindex{PROG_CXX_C_O}
7705 @cvindex CXX_NO_MINUS_C_MINUS_O
7706 Test whether the C++ compiler accepts the options @option{-c} and
7707 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7708 if it does not.
7709 @end defmac
7712 @node Objective C Compiler
7713 @subsection Objective C Compiler Characteristics
7716 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7717 @acindex{PROG_OBJC}
7718 @evindex OBJC
7719 @evindex OBJCFLAGS
7720 @ovindex OBJC
7721 @ovindex OBJCFLAGS
7722 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7723 set in the environment, check for Objective C compilers.  Set output
7724 variable @code{OBJC} to the name of the compiler found.
7726 This macro may, however, be invoked with an optional first argument
7727 which, if specified, must be a blank-separated list of Objective C compilers to
7728 search for.  This just gives the user an opportunity to specify an
7729 alternative search list for the Objective C compiler.  For example, if you
7730 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7731 like this:
7733 @example
7734 AC_PROG_OBJC([gcc objcc objc])
7735 @end example
7737 If using the GNU Objective C compiler, set shell variable
7738 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7739 already set, set it to @option{-g -O2} for the GNU Objective C
7740 compiler (@option{-O2} on systems where @command{gcc} does not accept
7741 @option{-g}), or @option{-g} for other compilers.
7742 @end defmac
7744 @defmac AC_PROG_OBJCPP
7745 @acindex{PROG_OBJCPP}
7746 @evindex OBJCPP
7747 @ovindex OBJCPP
7748 Set output variable @code{OBJCPP} to a command that runs the Objective C
7749 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7750 @end defmac
7753 @node Objective C++ Compiler
7754 @subsection Objective C++ Compiler Characteristics
7757 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7758 @acindex{PROG_OBJCXX}
7759 @evindex OBJCXX
7760 @evindex OBJCXXFLAGS
7761 @ovindex OBJCXX
7762 @ovindex OBJCXXFLAGS
7763 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7764 set in the environment, check for Objective C++ compilers.  Set output
7765 variable @code{OBJCXX} to the name of the compiler found.
7767 This macro may, however, be invoked with an optional first argument
7768 which, if specified, must be a blank-separated list of Objective C++ compilers
7769 to search for.  This just gives the user an opportunity to specify an
7770 alternative search list for the Objective C++ compiler.  For example, if you
7771 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7772 like this:
7774 @example
7775 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7776 @end example
7778 If using the GNU Objective C++ compiler, set shell variable
7779 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7780 already set, set it to @option{-g -O2} for the GNU Objective C++
7781 compiler (@option{-O2} on systems where @command{gcc} does not accept
7782 @option{-g}), or @option{-g} for other compilers.
7783 @end defmac
7785 @defmac AC_PROG_OBJCXXCPP
7786 @acindex{PROG_OBJCXXCPP}
7787 @evindex OBJCXXCPP
7788 @ovindex OBJCXXCPP
7789 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7790 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7791 @end defmac
7794 @node Erlang Compiler and Interpreter
7795 @subsection Erlang Compiler and Interpreter Characteristics
7796 @cindex Erlang
7798 Autoconf defines the following macros for determining paths to the essential
7799 Erlang/OTP programs:
7801 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7802 @acindex{ERLANG_PATH_ERLC}
7803 @evindex ERLC
7804 @evindex ERLCFLAGS
7805 @ovindex ERLC
7806 @ovindex ERLCFLAGS
7807 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7808 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7809 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7810 is not set in the environment, set it to an empty value.
7812 The two optional arguments have the same meaning as the two last arguments of
7813 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7814 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7815 directory:
7817 @example
7818 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7819 @end example
7820 @end defmac
7822 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7823 @acindex{ERLANG_NEED_ERLC}
7824 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7825 error message and exits the @command{configure} script if the @command{erlc}
7826 program is not found.
7827 @end defmac
7829 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7830 @acindex{ERLANG_PATH_ERL}
7831 @evindex ERL
7832 @ovindex ERL
7833 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7834 set in the
7835 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7836 complete path of the interpreter command found.
7838 The two optional arguments have the same meaning as the two last arguments of
7839 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7840 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7841 directory:
7843 @example
7844 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7845 @end example
7846 @end defmac
7848 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7849 @acindex{ERLANG_NEED_ERL}
7850 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7851 error message and exits the @command{configure} script if the @command{erl}
7852 program is not found.
7853 @end defmac
7856 @node Fortran Compiler
7857 @subsection Fortran Compiler Characteristics
7858 @cindex Fortran
7859 @cindex F77
7861 The Autoconf Fortran support is divided into two categories: legacy
7862 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7863 The former are intended for traditional Fortran 77 code, and have output
7864 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7865 are for newer programs that can (or must) compile under the newer
7866 Fortran standards, and have output variables like @code{FC},
7867 @code{FCFLAGS}, and @code{FCLIBS}.
7869 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7870 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7871 @code{FC} and @code{F77} macros behave almost identically, and so they
7872 are documented together in this section.
7875 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7876 @acindex{PROG_F77}
7877 @evindex F77
7878 @evindex FFLAGS
7879 @ovindex F77
7880 @ovindex FFLAGS
7881 @caindex f77_compiler_gnu
7882 @caindex prog_f77_g
7883 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7884 set in the environment, then check for @code{g77} and @code{f77}, and
7885 then some other names.  Set the output variable @code{F77} to the name
7886 of the compiler found.
7888 This macro may, however, be invoked with an optional first argument
7889 which, if specified, must be a blank-separated list of Fortran 77
7890 compilers to search for.  This just gives the user an opportunity to
7891 specify an alternative search list for the Fortran 77 compiler.  For
7892 example, if you didn't like the default order, then you could invoke
7893 @code{AC_PROG_F77} like this:
7895 @example
7896 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7897 @end example
7899 If using @code{g77} (the GNU Fortran 77 compiler), then
7900 set the shell variable @code{G77} to @samp{yes}.
7901 If the output variable @code{FFLAGS} was not already set in the
7902 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7903 where @code{g77} does not accept @option{-g}).  Otherwise, set
7904 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7906 The result of the GNU test is cached in the
7907 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7908 @code{ac_cv_prog_f77_g} variable.
7909 @end defmac
7911 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7912 @acindex{PROG_FC}
7913 @evindex FC
7914 @evindex FCFLAGS
7915 @ovindex FC
7916 @ovindex FCFLAGS
7917 @caindex fc_compiler_gnu
7918 @caindex prog_fc_g
7919 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7920 the environment, then @code{dialect} is a hint to indicate what Fortran
7921 dialect to search for; the default is to search for the newest available
7922 dialect.  Set the output variable @code{FC} to the name of the compiler
7923 found.
7925 By default, newer dialects are preferred over older dialects, but if
7926 @code{dialect} is specified then older dialects are preferred starting
7927 with the specified dialect.  @code{dialect} can currently be one of
7928 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7929 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7930 and no attempt is made to guarantee that a particular language standard
7931 is actually supported.  Thus, it is preferable that you avoid the
7932 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7933 the latest Fortran standard.
7935 This macro may, alternatively, be invoked with an optional first argument
7936 which, if specified, must be a blank-separated list of Fortran
7937 compilers to search for, just as in @code{AC_PROG_F77}.
7939 If the output variable @code{FCFLAGS} was not already set in the
7940 environment, then set it to @option{-g -02} for GNU @code{g77} (or
7941 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7942 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7944 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7945 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7946 variable.
7947 @end defmac
7949 @defmac AC_PROG_F77_C_O
7950 @defmacx AC_PROG_FC_C_O
7951 @acindex{PROG_F77_C_O}
7952 @acindex{PROG_FC_C_O}
7953 @cvindex F77_NO_MINUS_C_MINUS_O
7954 @cvindex FC_NO_MINUS_C_MINUS_O
7955 @caindex prog_f77_c_o
7956 @caindex prog_fc_c_o
7957 Test whether the Fortran compiler accepts the options @option{-c} and
7958 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7959 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7961 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7962 @code{ac_cv_prog_fc_c_o} variable, respectively.
7963 @end defmac
7965 The following macros check for Fortran compiler characteristics.
7966 To check for characteristics not listed here, use
7967 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7968 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7969 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7970 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7973 @defmac AC_F77_LIBRARY_LDFLAGS
7974 @defmacx AC_FC_LIBRARY_LDFLAGS
7975 @acindex{F77_LIBRARY_LDFLAGS}
7976 @ovindex FLIBS
7977 @acindex{FC_LIBRARY_LDFLAGS}
7978 @ovindex FCLIBS
7979 @caindex prog_f77_v
7980 @caindex prog_fc_v
7981 @caindex f77_libs
7982 @caindex fc_libs
7983 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7984 @dfn{Fortran intrinsic and runtime libraries} that are required to
7985 successfully link a Fortran program or shared library.  The output
7986 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7987 should be included after @code{LIBS} when linking).
7989 This macro is intended to be used in those situations when it is
7990 necessary to mix, e.g., C++ and Fortran source code in a single
7991 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7992 automake, GNU Automake}).
7994 For example, if object files from a C++ and Fortran compiler must be
7995 linked together, then the C++ compiler/linker must be used for linking
7996 (since special C++-ish things need to happen at link time like calling
7997 global constructors, instantiating templates, enabling exception
7998 support, etc.).
8000 However, the Fortran intrinsic and runtime libraries must be linked in
8001 as well, but the C++ compiler/linker doesn't know by default how to add
8002 these Fortran 77 libraries.  Hence, this macro was created to determine
8003 these Fortran libraries.
8005 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8006 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
8007 link C/C++ with Fortran; see below.  Further, it is highly recommended
8008 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
8009 because the complex defines that the function wrapper macros create
8010 may not work with C/C++ compiler drivers.
8012 These macros internally compute the flag needed to verbose linking
8013 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
8014 variables, respectively.  The computed linker flags are cached in
8015 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
8016 @end defmac
8018 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
8019   AC_MSG_FAILURE})
8020 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @dvar{action-if-not-found, @
8021   AC_MSG_FAILURE})
8022 @acindex{F77_DUMMY_MAIN}
8023 @cvindex F77_DUMMY_MAIN
8024 @acindex{FC_DUMMY_MAIN}
8025 @cvindex FC_DUMMY_MAIN
8026 @caindex f77_dummy_main
8027 @caindex fc_dummy_main
8028 With many compilers, the Fortran libraries detected by
8029 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8030 their own @code{main} entry function that initializes things like
8031 Fortran I/O, and which then calls a user-provided entry function named
8032 (say) @code{MAIN__} to run the user's program.  The
8033 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8034 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8035 this interaction.
8037 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8038 one prefers to provide one's own @code{main} and skip the Fortran
8039 library initializations.  In this case, however, one may still need to
8040 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8041 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8042 detects whether any such routine is @emph{required} for linking, and
8043 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8044 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8045 was found, and @code{none} when no such dummy main is needed.
8047 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8048 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8049 @emph{if} it is required.  @var{action-if-not-found} defaults to
8050 exiting with an error.
8052 In order to link with Fortran routines, the user's C/C++ program should
8053 then include the following code to define the dummy main if it is
8054 needed:
8056 @example
8057 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8058 #ifdef F77_DUMMY_MAIN
8059 #  ifdef __cplusplus
8060      extern "C"
8061 #  endif
8062    int F77_DUMMY_MAIN () @{ return 1; @}
8063 #endif
8064 @end example
8066 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8068 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8069 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8070 explicitly unless one wants to change the default actions.
8072 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8073 @code{ac_cv_fc_dummy_main} variable, respectively.
8074 @end defmac
8076 @defmac AC_F77_MAIN
8077 @defmacx AC_FC_MAIN
8078 @acindex{F77_MAIN}
8079 @cvindex F77_MAIN
8080 @acindex{FC_MAIN}
8081 @cvindex FC_MAIN
8082 @caindex f77_main
8083 @caindex fc_main
8084 As discussed above, many Fortran libraries allow you to provide an entry
8085 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8086 is then called by a @code{main} function in the Fortran libraries that
8087 initializes things like Fortran I/O@.  The
8088 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8089 @emph{possible} to utilize such an alternate main function, and defines
8090 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8091 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8092 simply defined to @code{main}.)
8094 Thus, when calling Fortran routines from C that perform things like I/O,
8095 one should use this macro and declare the "main" function like so:
8097 @example
8098 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8099 #ifdef __cplusplus
8100   extern "C"
8101 #endif
8102 int F77_MAIN (int argc, char *argv[]);
8103 @end example
8105 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8107 The result of this macro is cached in the @code{ac_cv_f77_main} or
8108 @code{ac_cv_fc_main} variable, respectively.
8109 @end defmac
8111 @defmac AC_F77_WRAPPERS
8112 @defmacx AC_FC_WRAPPERS
8113 @acindex{F77_WRAPPERS}
8114 @cvindex F77_FUNC
8115 @cvindex F77_FUNC_
8116 @acindex{FC_WRAPPERS}
8117 @cvindex FC_FUNC
8118 @cvindex FC_FUNC_
8119 @caindex f77_mangling
8120 @caindex fc_mangling
8121 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8122 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8123 mangle the names of C/C++ identifiers, and identifiers with underscores,
8124 respectively, so that they match the name-mangling scheme used by the
8125 Fortran compiler.
8127 Fortran is case-insensitive, and in order to achieve this the Fortran
8128 compiler converts all identifiers into a canonical case and format.  To
8129 call a Fortran subroutine from C or to write a C function that is
8130 callable from Fortran, the C program must explicitly use identifiers in
8131 the format expected by the Fortran compiler.  In order to do this, one
8132 simply wraps all C identifiers in one of the macros provided by
8133 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8134 you have the following Fortran 77 subroutine:
8136 @example
8137 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8138       subroutine foobar (x, y)
8139       double precision x, y
8140       y = 3.14159 * x
8141       return
8142       end
8143 @end example
8145 You would then declare its prototype in C or C++ as:
8147 @example
8148 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8149 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8150 #ifdef __cplusplus
8151 extern "C"  /* prevent C++ name mangling */
8152 #endif
8153 void FOOBAR_F77 (double *x, double *y);
8154 @end example
8156 Note that we pass both the lowercase and uppercase versions of the
8157 function name to @code{F77_FUNC} so that it can select the right one.
8158 Note also that all parameters to Fortran 77 routines are passed as
8159 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8160 Automake}).
8162 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8164 Although Autoconf tries to be intelligent about detecting the
8165 name-mangling scheme of the Fortran compiler, there may be Fortran
8166 compilers that it doesn't support yet.  In this case, the above code
8167 generates a compile-time error, but some other behavior
8168 (e.g., disabling Fortran-related features) can be induced by checking
8169 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8171 Now, to call that routine from a C program, we would do something like:
8173 @example
8174 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8176     double x = 2.7183, y;
8177     FOOBAR_F77 (&x, &y);
8179 @end example
8181 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8182 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8183 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8184 because some Fortran compilers mangle names differently if they contain
8185 an underscore.
8187 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8188 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8189 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8190 @end defmac
8192 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8193 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8194 @acindex{F77_FUNC}
8195 @acindex{FC_FUNC}
8196 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8197 hold the mangled version @var{name} according to the rules of the
8198 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8199 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8200 supplied, the shell variable is simply @var{name}.  The purpose of
8201 this macro is to give the caller a way to access the name-mangling
8202 information other than through the C preprocessor as above, for example,
8203 to call Fortran routines from some language other than C/C++.
8204 @end defmac
8206 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8207   @dvar{action-if-failure, AC_MSG_FAILURE})
8208 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8209   @dvar{action-if-failure, AC_MSG_FAILURE})
8210 @acindex{FC_SRCEXT}
8211 @acindex{FC_PP_SRCEXT}
8212 @caindex fc_srcext_@var{ext}
8213 @caindex fc_pp_srcext_@var{ext}
8214 By default, the @code{FC} macros perform their tests using a @file{.f}
8215 extension for source-code files.  Some compilers, however, only enable
8216 newer language features for appropriately named files, e.g., Fortran 90
8217 features only for @file{.f90} files, or preprocessing only with
8218 @file{.F} files or maybe other upper-case extensions.  On the other
8219 hand, some other compilers expect all source files to end in @file{.f}
8220 and require special flags to support other file name extensions.  The
8221 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8222 issues.
8224 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8225 accept files ending with the extension @file{.@var{ext}} (i.e.,
8226 @var{ext} does @emph{not} contain the dot).  If any special compiler
8227 flags are needed for this, it stores them in the output variable
8228 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8229 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8230 @code{AC_FC_PP_SRCEXT} is called another time).
8232 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8233 @file{.f90} extension in future tests, and it would set the
8234 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8235 to compile such files.
8237 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8238 compiler to preprocess and compile files with the extension
8239 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8240 preprocessing are provided, the former is preferred, as the latter may
8241 treat continuation lines, @code{//} tokens, and white space differently
8242 from what some Fortran dialects expect.  Conversely, if you do not want
8243 files to be preprocessed, use only lower-case characters in the file
8244 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8245 are stored in the @code{FCFLAGS_@var{ext}} variable.
8247 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8248 into @code{FCFLAGS}, for two reasons based on the limitations of some
8249 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8250 time, so files with different extensions must be compiled separately.
8251 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8252 the source-code file name when compiling.  So, continuing the example
8253 above, you might compile a @file{foo.f90} file in your makefile with the
8254 command:
8256 @example
8257 foo.o: foo.f90
8258        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8259 @end example
8261 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8262 files with the @var{ext} extension, it calls @var{action-if-success}
8263 (defaults to nothing).  If it fails, and cannot find a way to make the
8264 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8265 (defaults to exiting with an error message).
8267 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8268 results in @code{ac_cv_fc_srcext_@var{ext}} and
8269 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8270 @end defmac
8272 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @dvar{action-if-failure, @
8273   AC_MSG_FAILURE})
8274 @acindex{FC_PP_DEFINE}
8275 @caindex fc_pp_define
8277 Find a flag to specify defines for preprocessed Fortran.  Not all
8278 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8279 the result and call @var{action-if-success} (defaults to nothing) if
8280 successful, and @var{action-if-failure} (defaults to failing with an
8281 error message) if not.
8283 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8284 to preprocess a @file{conftest.F} file, but restores a previously used
8285 Fortran source file extension afterwards again.
8287 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8288 variable.
8289 @end defmac
8291 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8292   AC_MSG_FAILURE})
8293 @acindex{FC_FREEFORM}
8294 @caindex fc_freeform
8296 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8297 source code (as opposed to the older fixed-format style from Fortran
8298 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8300 This macro is most important if you are using the default @file{.f}
8301 extension, since many compilers interpret this extension as indicating
8302 fixed-format source unless an additional flag is supplied.  If you
8303 specify a different extension with @code{AC_FC_SRCEXT}, such as
8304 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8305 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8306 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8307 the compiler assume Fortran 77 by default, however.
8309 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8310 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8311 calls @var{action-if-failure} (defaults to exiting with an error
8312 message).
8314 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8315 the @code{ac_cv_fc_freeform} variable.
8316 @end defmac
8318 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @dvar{action-if-failure, @
8319   AC_MSG_FAILURE})
8320 @acindex{FC_FIXEDFORM}
8321 @caindex fc_fixedform
8323 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8324 fixed-format source code (as opposed to free-format style).  If
8325 necessary, it may add some additional flags to @code{FCFLAGS}.
8327 This macro is needed for some compilers alias names like @command{xlf95}
8328 which assume free-form source code by default, and in case you want to
8329 use fixed-form source with an extension like @file{.f90} which many
8330 compilers interpret as free-form by default.  If you specify a different
8331 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8332 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8333 @code{FCFLAGS}.
8335 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8336 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8337 calls @var{action-if-failure} (defaults to exiting with an error
8338 message).
8340 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8341 the @code{ac_cv_fc_fixedform} variable.
8342 @end defmac
8344 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8345   @dvar{action-if-failure, AC_MSG_FAILURE})
8346 @acindex{FC_LINE_LENGTH}
8347 @caindex fc_line_length
8349 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8350 code lines.  The @var{length} argument may be given as 80, 132, or
8351 unlimited, and defaults to 132.  Note that line lengths above 254
8352 columns are not portable, and some compilers do not accept more than 132
8353 columns at least for fixed format source.  If necessary, it may add some
8354 additional flags to @code{FCFLAGS}.
8356 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8357 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8358 calls @var{action-if-failure} (defaults to exiting with an error
8359 message).
8361 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8362 the @code{ac_cv_fc_line_length} variable.
8363 @end defmac
8365 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8366   @dvar{action-if-failure, AC_MSG_FAILURE})
8367 @acindex{FC_CHECK_BOUNDS}
8368 @caindex fc_check_bounds
8370 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8371 in the Fortran compiler.  If successful, the @var{action-if-success}
8372 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8373 @var{action-if-failure} is called, which defaults to failing with an error
8374 message.  The macro currently requires Fortran 90 or a newer dialect.
8376 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8377 variable.
8378 @end defmac
8380 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8381   @dvar{action-if-failure, AC_MSG_FAILURE})
8382 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8383   @dvar{action-if-failure, AC_MSG_FAILURE})
8384 @acindex{F77_IMPLICIT_NONE}
8385 @acindex{FC_IMPLICIT_NONE}
8386 @caindex f77_implicit_none
8387 @caindex fc_implicit_none
8389 Try to disallow implicit declarations in the Fortran compiler.  If
8390 successful, @var{action-if-success} is called and any needed flags
8391 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8392 @var{action-if-failure} is called, which defaults to failing with an error
8393 message.
8395 The result of these macros are cached in the
8396 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8397 variables, respectively.
8398 @end defmac
8400 @defmac AC_FC_MODULE_EXTENSION
8401 @acindex{FC_MODULE_EXTENSION}
8402 @caindex fc_module_ext
8403 @ovindex FC_MODEXT
8405 Find the Fortran 90 module file name extension.  Most Fortran 90
8406 compilers store module information in files separate from the object
8407 files.  The module files are usually named after the name of the module
8408 rather than the source file name, with characters possibly turned to
8409 upper case, plus an extension, often @file{.mod}.
8411 Not all compilers use module files at all, or by default.  The Cray
8412 Fortran compiler requires @option{-e m} in order to store and search
8413 module information in @file{.mod} files rather than in object files.
8414 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8415 indicate how module information is stored.
8417 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8418 without the leading dot, and stores that in the @code{FC_MODEXT}
8419 variable.  If the compiler does not produce module files, or the
8420 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8421 the result of this macro may be used in cleanup @command{make} rules as
8422 follows:
8424 @example
8425 clean-modules:
8426         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8427 @end example
8429 The extension, or @samp{unknown}, is cached in the
8430 @code{ac_cv_fc_module_ext} variable.
8431 @end defmac
8433 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-sucess}, @
8434   @dvar{action-if-failure, AC_MSG_FAILURE})
8435 @acindex{FC_MODULE_FLAG}
8436 @caindex fc_module_flag
8437 @ovindex FC_MODINC
8438 @ovindex ac_empty
8440 Find the compiler flag to include Fortran 90 module information from
8441 another directory, and store that in the @code{FC_MODINC} variable.
8442 Call @var{action-if-success} (defaults to nothing) if successful, and
8443 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8444 to exiting with an error message) if not.
8446 Most Fortran 90 compilers provide a way to specify module directories.
8447 Some have separate flags for the directory to write module files to,
8448 and directories to search them in, whereas others only allow writing to
8449 the current directory or to the first directory specified in the include
8450 path.  Further, with some compilers, the module search path and the
8451 preprocessor search path can only be modified with the same flag.  Thus,
8452 for portability, write module files to the current directory only and
8453 list that as first directory in the search path.
8455 There may be no whitespace between @code{FC_MODINC} and the following
8456 directory name, but @code{FC_MODINC} may contain trailing white space.
8457 For example, if you use Automake and would like to search @file{../lib}
8458 for module files, you can use the following:
8460 @example
8461 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8462 @end example
8464 Inside @command{configure} tests, you can use:
8466 @example
8467 if test -n "$FC_MODINC"; then
8468   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8470 @end example
8472 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8473 The substituted value of @code{FC_MODINC} may refer to the
8474 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8475 the significant trailing whitespace in a @file{Makefile}.
8476 @end defmac
8478 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-sucess}, @
8479   @dvar{action-if-failure, AC_MSG_FAILURE})
8480 @acindex{FC_MODULE_OUTPUT_FLAG}
8481 @caindex fc_module_output_flag
8482 @ovindex FC_MODOUT
8484 Find the compiler flag to write Fortran 90 module information to
8485 another directory, and store that in the @code{FC_MODOUT} variable.
8486 Call @var{action-if-success} (defaults to nothing) if successful, and
8487 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8488 to exiting with an error message) if not.
8490 Not all Fortran 90 compilers write module files, and of those that do,
8491 not all allow writing to a directory other than the current one, nor
8492 do all have separate flags for writing and reading; see the description
8493 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8494 another directory, for maximum portability use @code{FC_MODOUT} before
8495 any @code{FC_MODINC} and include both the current directory and the one
8496 you write to in the search path:
8498 @example
8499 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8500 @end example
8502 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8503 The substituted value of @code{FC_MODOUT} may refer to the
8504 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8505 the significant trailing whitespace in a @file{Makefile}.
8506 @end defmac
8509 @node Go Compiler
8510 @subsection Go Compiler Characteristics
8511 @cindex Go
8513 Autoconf provides basic support for the Go programming language when
8514 using the @code{gccgo} compiler (there is currently no support for the
8515 @code{6g} and @code{8g} compilers).
8517 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8518 Find the Go compiler to use.  Check whether the environment variable
8519 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8520 value.
8522 Otherwise, if the macro is invoked without an argument, then search for
8523 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8524 resort set @code{GOC} to @code{gccgo}.
8526 This macro may be invoked with an optional first argument which, if
8527 specified, must be a blank-separated list of Go compilers to search for.
8529 If output variable @code{GOFLAGS} was not already set, set it to
8530 @option{-g -O2}.  If your package does not like this default,
8531 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8532 @end defmac
8535 @node System Services
8536 @section System Services
8538 The following macros check for operating system services or capabilities.
8540 @anchor{AC_PATH_X}
8541 @defmac AC_PATH_X
8542 @acindex{PATH_X}
8543 @evindex XMKMF
8544 @cindex X Window System
8545 Try to locate the X Window System include files and libraries.  If the
8546 user gave the command line options @option{--x-includes=@var{dir}} and
8547 @option{--x-libraries=@var{dir}}, use those directories.
8549 If either or both were not given, get the missing values by running
8550 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8551 environment variable) on a trivial @file{Imakefile} and examining the
8552 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8553 disables this method.
8555 If this method fails to find the X Window System, @command{configure}
8556 looks for the files in several directories where they often reside.
8557 If either method is successful, set the shell variables
8558 @code{x_includes} and @code{x_libraries} to their locations, unless they
8559 are in directories the compiler searches by default.
8561 If both methods fail, or the user gave the command line option
8562 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8563 otherwise set it to the empty string.
8564 @end defmac
8566 @anchor{AC_PATH_XTRA}
8567 @defmac AC_PATH_XTRA
8568 @acindex{PATH_XTRA}
8569 @ovindex X_CFLAGS
8570 @ovindex X_LIBS
8571 @ovindex X_EXTRA_LIBS
8572 @ovindex X_PRE_LIBS
8573 @cvindex X_DISPLAY_MISSING
8574 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8575 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8576 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8577 available.
8579 This macro also checks for special libraries that some systems need in
8580 order to compile X programs.  It adds any that the system needs to
8581 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8582 libraries that need to be linked with before @option{-lX11}, and adds
8583 any found to the output variable @code{X_PRE_LIBS}.
8585 @c This is an incomplete kludge.  Make a real way to do it.
8586 @c If you need to check for other X functions or libraries yourself, then
8587 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8588 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8589 @end defmac
8591 @anchor{AC_SYS_INTERPRETER}
8592 @defmac AC_SYS_INTERPRETER
8593 @acindex{SYS_INTERPRETER}
8594 Check whether the system supports starting scripts with a line of the
8595 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8596 After running this macro, shell code in @file{configure.ac} can check
8597 the shell variable @code{interpval}; it is set to @samp{yes}
8598 if the system supports @samp{#!}, @samp{no} if not.
8599 @end defmac
8601 @defmac AC_SYS_LARGEFILE
8602 @acindex{SYS_LARGEFILE}
8603 @cvindex _FILE_OFFSET_BITS
8604 @cvindex _LARGE_FILES
8605 @ovindex CC
8606 @cindex Large file support
8607 @cindex LFS
8608 Arrange for 64-bit file offsets, known as
8609 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8610 large-file support}.  On some hosts, one must use special compiler
8611 options to build programs that can access large files.  Append any such
8612 options to the output variable @code{CC}.  Define
8613 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8615 Large-file support can be disabled by configuring with the
8616 @option{--disable-largefile} option.
8618 If you use this macro, check that your program works even when
8619 @code{off_t} is wider than @code{long int}, since this is common when
8620 large-file support is enabled.  For example, it is not correct to print
8621 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8622 (long int) X)}.
8624 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8625 replace their C counterparts @code{fseek} and @code{ftell} that do not
8626 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8627 prototypes available when using them and large-file support is
8628 enabled.
8629 @end defmac
8631 @anchor{AC_SYS_LONG_FILE_NAMES}
8632 @defmac AC_SYS_LONG_FILE_NAMES
8633 @acindex{SYS_LONG_FILE_NAMES}
8634 @cvindex HAVE_LONG_FILE_NAMES
8635 If the system supports file names longer than 14 characters, define
8636 @code{HAVE_LONG_FILE_NAMES}.
8637 @end defmac
8639 @defmac AC_SYS_POSIX_TERMIOS
8640 @acindex{SYS_POSIX_TERMIOS}
8641 @cindex Posix termios headers
8642 @cindex termios Posix headers
8643 @caindex sys_posix_termios
8644 Check to see if the Posix termios headers and functions are available on the
8645 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8646 @samp{yes}.  If not, set the variable to @samp{no}.
8647 @end defmac
8649 @node Posix Variants
8650 @section Posix Variants
8652 The following macro makes it possible to use features of Posix that are
8653 extensions to C, as well as platform extensions not defined by Posix.
8655 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8656 @defmac AC_USE_SYSTEM_EXTENSIONS
8657 @acindex{USE_SYSTEM_EXTENSIONS}
8658 @cvindex _ALL_SOURCE
8659 @cvindex _GNU_SOURCE
8660 @cvindex _MINIX
8661 @cvindex _POSIX_1_SOURCE
8662 @cvindex _POSIX_PTHREAD_SEMANTICS
8663 @cvindex _POSIX_SOURCE
8664 @cvindex _TANDEM_SOURCE
8665 @cvindex __EXTENSIONS__
8666 This macro was introduced in Autoconf 2.60.  If possible, enable
8667 extensions to C or Posix on hosts that normally disable the extensions,
8668 typically due to standards-conformance namespace issues.  This should be
8669 called before any macros that run the C compiler.  The following
8670 preprocessor macros are defined where appropriate:
8672 @table @code
8673 @item _GNU_SOURCE
8674 Enable extensions on GNU/Linux.
8675 @item __EXTENSIONS__
8676 Enable general extensions on Solaris.
8677 @item _POSIX_PTHREAD_SEMANTICS
8678 Enable threading extensions on Solaris.
8679 @item _TANDEM_SOURCE
8680 Enable extensions for the HP NonStop platform.
8681 @item _ALL_SOURCE
8682 Enable extensions for AIX 3, and for Interix.
8683 @item _POSIX_SOURCE
8684 Enable Posix functions for Minix.
8685 @item _POSIX_1_SOURCE
8686 Enable additional Posix functions for Minix.
8687 @item _MINIX
8688 Identify Minix platform.  This particular preprocessor macro is
8689 obsolescent, and may be removed in a future release of Autoconf.
8690 @end table
8691 @end defmac
8694 @node Erlang Libraries
8695 @section Erlang Libraries
8696 @cindex Erlang, Library, checking
8698 The following macros check for an installation of Erlang/OTP, and for the
8699 presence of certain Erlang libraries.  All those macros require the
8700 configuration of an Erlang interpreter and an Erlang compiler
8701 (@pxref{Erlang Compiler and Interpreter}).
8703 @defmac AC_ERLANG_SUBST_ERTS_VER
8704 @acindex{ERLANG_SUBST_ERTS_VER}
8705 @ovindex ERLANG_ERTS_VER
8706 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8707 Erlang runtime system (as returned by Erlang's
8708 @code{erlang:system_info(version)} function).  The result of this test
8709 is cached if caching is enabled when running @command{configure}.  The
8710 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8711 for features of specific ERTS versions, but to be used for substituting
8712 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8713 files), as shown below.
8714 @end defmac
8716 @defmac AC_ERLANG_SUBST_ROOT_DIR
8717 @acindex{ERLANG_SUBST_ROOT_DIR}
8718 @ovindex ERLANG_ROOT_DIR
8719 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8720 directory in which Erlang/OTP is installed (as returned by Erlang's
8721 @code{code:root_dir/0} function).  The result of this test is cached if
8722 caching is enabled when running @command{configure}.
8723 @end defmac
8725 @defmac AC_ERLANG_SUBST_LIB_DIR
8726 @acindex{ERLANG_SUBST_LIB_DIR}
8727 @ovindex ERLANG_LIB_DIR
8728 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8729 directory of Erlang/OTP (as returned by Erlang's
8730 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8731 Erlang/OTP library.  The result of this test is cached if caching is enabled
8732 when running @command{configure}.
8733 @end defmac
8735 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8736   @ovar{action-if-not-found})
8737 @acindex{ERLANG_CHECK_LIB}
8738 @ovindex ERLANG_LIB_DIR_@var{library}
8739 @ovindex ERLANG_LIB_VER_@var{library}
8740 Test whether the Erlang/OTP library @var{library} is installed by
8741 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8742 test is cached if caching is enabled when running @command{configure}.
8743 @var{action-if-found} is a list of shell commands to run if the library
8744 is installed; @var{action-if-not-found} is a list of shell commands to
8745 run if it is not.  Additionally, if the library is installed, the output
8746 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8747 library installation directory, and the output variable
8748 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8749 part of the subdirectory name, if it is in the standard form
8750 (@code{@var{library}-@var{version}}).  If the directory name does not
8751 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8752 empty string.  If the library is not installed,
8753 @samp{ERLANG_LIB_DIR_@var{library}} and
8754 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8755 example, to check if library @code{stdlib} is installed:
8757 @example
8758 AC_ERLANG_CHECK_LIB([stdlib],
8759   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8760    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8761   [AC_MSG_ERROR([stdlib was not found!])])
8762 @end example
8764 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8765 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8766 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8767 testing for features of specific versions of libraries or of the Erlang
8768 runtime system.  Those variables are intended to be substituted in
8769 Erlang release resource files (@code{.rel} files).  For instance, to
8770 generate a @file{example.rel} file for an application depending on the
8771 @code{stdlib} library, @file{configure.ac} could contain:
8773 @example
8774 AC_ERLANG_SUBST_ERTS_VER
8775 AC_ERLANG_CHECK_LIB([stdlib],
8776   [],
8777   [AC_MSG_ERROR([stdlib was not found!])])
8778 AC_CONFIG_FILES([example.rel])
8779 @end example
8781 @noindent
8782 The @file{example.rel.in} file used to generate @file{example.rel}
8783 should contain:
8785 @example
8786 @{release,
8787     @{"@@PACKAGE@@", "@@VERSION@@"@},
8788     @{erts, "@@ERLANG_ERTS_VER@@"@},
8789     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8790      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8791 @end example
8792 @end defmac
8794 In addition to the above macros, which test installed Erlang libraries, the
8795 following macros determine the paths to the directories into which newly built
8796 Erlang libraries are to be installed:
8798 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8799 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8800 @ovindex ERLANG_INSTALL_LIB_DIR
8802 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8803 which every built Erlang library should be installed in a separate
8804 subdirectory.
8805 If this variable is not set in the environment when @command{configure} runs,
8806 its default value is @code{$@{libdir@}/erlang/lib}.
8807 @end defmac
8809 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8810 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8811 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8813 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8814 directory into which the built Erlang library @var{library} version
8815 @var{version} should be installed.  If this variable is not set in the
8816 environment when @command{configure} runs, its default value is
8817 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8818 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8819 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8820 @end defmac
8826 @c ========================================================= Writing Tests
8828 @node Writing Tests
8829 @chapter Writing Tests
8831 If the existing feature tests don't do something you need, you have to
8832 write new ones.  These macros are the building blocks.  They provide
8833 ways for other macros to check whether various kinds of features are
8834 available and report the results.
8836 This chapter contains some suggestions and some of the reasons why the
8837 existing tests are written the way they are.  You can also learn a lot
8838 about how to write Autoconf tests by looking at the existing ones.  If
8839 something goes wrong in one or more of the Autoconf tests, this
8840 information can help you understand the assumptions behind them, which
8841 might help you figure out how to best solve the problem.
8843 These macros check the output of the compiler system of the current
8844 language (@pxref{Language Choice}).  They do not cache the results of
8845 their tests for future use (@pxref{Caching Results}), because they don't
8846 know enough about the information they are checking for to generate a
8847 cache variable name.  They also do not print any messages, for the same
8848 reason.  The checks for particular kinds of features call these macros
8849 and do cache their results and print messages about what they're
8850 checking for.
8852 When you write a feature test that could be applicable to more than one
8853 software package, the best thing to do is encapsulate it in a new macro.
8854 @xref{Writing Autoconf Macros}, for how to do that.
8856 @menu
8857 * Language Choice::             Selecting which language to use for testing
8858 * Writing Test Programs::       Forging source files for compilers
8859 * Running the Preprocessor::    Detecting preprocessor symbols
8860 * Running the Compiler::        Detecting language or header features
8861 * Running the Linker::          Detecting library features
8862 * Runtime::                     Testing for runtime features
8863 * Systemology::                 A zoology of operating systems
8864 * Multiple Cases::              Tests for several possible values
8865 @end menu
8867 @node Language Choice
8868 @section Language Choice
8869 @cindex Language
8871 Autoconf-generated @command{configure} scripts check for the C compiler and
8872 its features by default.  Packages that use other programming languages
8873 (maybe more than one, e.g., C and C++) need to test features of the
8874 compilers for the respective languages.  The following macros determine
8875 which programming language is used in the subsequent tests in
8876 @file{configure.ac}.
8878 @anchor{AC_LANG}
8879 @defmac AC_LANG (@var{language})
8880 @acindex{LANG}
8881 Do compilation tests using the compiler, preprocessor, and file
8882 extensions for the specified @var{language}.
8884 Supported languages are:
8886 @table @samp
8887 @item C
8888 Do compilation tests using @code{CC} and @code{CPP} and use extension
8889 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8890 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8892 @item C++
8893 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8894 extension @file{.C} for test programs.  Use compilation flags:
8895 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8896 @code{CXXFLAGS} with @code{CXX}.
8898 @item Fortran 77
8899 Do compilation tests using @code{F77} and use extension @file{.f} for
8900 test programs.  Use compilation flags: @code{FFLAGS}.
8902 @item Fortran
8903 Do compilation tests using @code{FC} and use extension @file{.f} (or
8904 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8905 compilation flags: @code{FCFLAGS}.
8907 @item Erlang
8908 @ovindex ERLC
8909 @ovindex ERL
8910 @ovindex ERLCFLAGS
8911 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8912 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8914 @item Objective C
8915 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8916 extension @file{.m} for test programs.  Use compilation flags:
8917 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8918 @code{OBJCFLAGS} with @code{OBJC}.
8920 @item Objective C++
8921 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8922 extension @file{.mm} for test programs.  Use compilation flags:
8923 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8924 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8926 @item Go
8927 Do compilation tests using @code{GOC} and use extension @file{.go} for
8928 test programs.  Use compilation flags @code{GOFLAGS}.
8929 @end table
8930 @end defmac
8932 @anchor{AC_LANG_PUSH}
8933 @defmac AC_LANG_PUSH (@var{language})
8934 @acindex{LANG_PUSH}
8935 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8936 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8937 in macros that need to temporarily switch to a particular language.
8938 @end defmac
8940 @defmac AC_LANG_POP (@ovar{language})
8941 @acindex{LANG_POP}
8942 Select the language that is saved on the top of the stack, as set by
8943 @code{AC_LANG_PUSH}, and remove it from the stack.
8945 If given, @var{language} specifies the language we just @emph{quit}.  It
8946 is a good idea to specify it when it's known (which should be the
8947 case@dots{}), since Autoconf detects inconsistencies.
8949 @example
8950 AC_LANG_PUSH([Fortran 77])
8951 # Perform some tests on Fortran 77.
8952 # @dots{}
8953 AC_LANG_POP([Fortran 77])
8954 @end example
8955 @end defmac
8957 @defmac AC_LANG_ASSERT (@var{language})
8958 @acindex{LANG_ASSERT}
8959 Check statically that the current language is @var{language}.
8960 You should use this in your language specific macros
8961 to avoid that they be called with an inappropriate language.
8963 This macro runs only at @command{autoconf} time, and incurs no cost at
8964 @command{configure} time.  Sadly enough and because Autoconf is a two
8965 layer language @footnote{Because M4 is not aware of Sh code,
8966 especially conditionals, some optimizations that look nice statically
8967 may produce incorrect results at runtime.}, the macros
8968 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8969 therefore as much as possible you ought to avoid using them to wrap
8970 your code, rather, require from the user to run the macro with a
8971 correct current language, and check it with @code{AC_LANG_ASSERT}.
8972 And anyway, that may help the user understand she is running a Fortran
8973 macro while expecting a result about her Fortran 77 compiler@enddots{}
8974 @end defmac
8977 @defmac AC_REQUIRE_CPP
8978 @acindex{REQUIRE_CPP}
8979 Ensure that whichever preprocessor would currently be used for tests has
8980 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8981 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8982 depending on which language is current.
8983 @end defmac
8986 @node Writing Test Programs
8987 @section Writing Test Programs
8989 Autoconf tests follow a common scheme: feed some program with some
8990 input, and most of the time, feed a compiler with some source file.
8991 This section is dedicated to these source samples.
8993 @menu
8994 * Guidelines::                  General rules for writing test programs
8995 * Test Functions::              Avoiding pitfalls in test programs
8996 * Generating Sources::          Source program boilerplate
8997 @end menu
8999 @node Guidelines
9000 @subsection Guidelines for Test Programs
9002 The most important rule to follow when writing testing samples is:
9004 @center @emph{Look for realism.}
9006 This motto means that testing samples must be written with the same
9007 strictness as real programs are written.  In particular, you should
9008 avoid ``shortcuts'' and simplifications.
9010 Don't just play with the preprocessor if you want to prepare a
9011 compilation.  For instance, using @command{cpp} to check whether a header is
9012 functional might let your @command{configure} accept a header which
9013 causes some @emph{compiler} error.  Do not hesitate to check a header with
9014 other headers included before, especially required headers.
9016 Make sure the symbols you use are properly defined, i.e., refrain from
9017 simply declaring a function yourself instead of including the proper
9018 header.
9020 Test programs should not write to standard output.  They
9021 should exit with status 0 if the test succeeds, and with status 1
9022 otherwise, so that success
9023 can be distinguished easily from a core dump or other failure;
9024 segmentation violations and other failures produce a nonzero exit
9025 status.  Unless you arrange for @code{exit} to be declared, test
9026 programs should @code{return}, not @code{exit}, from @code{main},
9027 because on many systems @code{exit} is not declared by default.
9029 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9030 preprocessor macros defined by tests that have already run.  For
9031 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9032 @file{configure.ac} you can have a test program that includes
9033 @file{stdbool.h} conditionally:
9035 @example
9036 @group
9037 #ifdef HAVE_STDBOOL_H
9038 # include <stdbool.h>
9039 #endif
9040 @end group
9041 @end example
9043 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9044 work with any standard C compiler.  Some developers prefer @code{#if}
9045 because it is easier to read, while others prefer @code{#ifdef} because
9046 it avoids diagnostics with picky compilers like GCC with the
9047 @option{-Wundef} option.
9049 If a test program needs to use or create a data file, give it a name
9050 that starts with @file{conftest}, such as @file{conftest.data}.  The
9051 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9052 after running test programs and if the script is interrupted.
9054 @node Test Functions
9055 @subsection Test Functions
9057 These days it's safe to assume support for function prototypes
9058 (introduced in C89).
9060 Functions that test programs declare should also be conditionalized for
9061 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9062 include any header files containing clashing prototypes.
9064 @example
9065 #ifdef __cplusplus
9066 extern "C"
9067 #endif
9068 void *valloc (size_t);
9069 @end example
9071 If a test program calls a function with invalid parameters (just to see
9072 whether it exists), organize the program to ensure that it never invokes
9073 that function.  You can do this by calling it in another function that is
9074 never invoked.  You can't do it by putting it after a call to
9075 @code{exit}, because GCC version 2 knows that @code{exit}
9076 never returns
9077 and optimizes out any code that follows it in the same block.
9079 If you include any header files, be sure to call the functions
9080 relevant to them with the correct number of arguments, even if they are
9081 just 0, to avoid compilation errors due to prototypes.  GCC
9082 version 2
9083 has internal prototypes for several functions that it automatically
9084 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9085 them, either pass them the correct number of arguments or redeclare them
9086 with a different return type (such as @code{char}).
9089 @node Generating Sources
9090 @subsection Generating Sources
9092 Autoconf provides a set of macros that can be used to generate test
9093 source files.  They are written to be language generic, i.e., they
9094 actually depend on the current language (@pxref{Language Choice}) to
9095 ``format'' the output properly.
9098 @defmac AC_LANG_CONFTEST (@var{source})
9099 @acindex{LANG_CONFTEST}
9100 Save the @var{source} text in the current test source file:
9101 @file{conftest.@var{extension}} where the @var{extension} depends on the
9102 current language.  As of Autoconf 2.63b, the source file also contains
9103 the results of all of the @code{AC_DEFINE} performed so far.
9105 Note that the @var{source} is evaluated exactly once, like regular
9106 Autoconf macro arguments, and therefore (i) you may pass a macro
9107 invocation, (ii) if not, be sure to double quote if needed.
9109 This macro issues a warning during @command{autoconf} processing if
9110 @var{source} does not include an expansion of the macro
9111 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9112 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9114 This macro is seldom called directly, but is used under the hood by more
9115 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9116 @end defmac
9118 @defmac AC_LANG_DEFINES_PROVIDED
9119 @acindex{LANG_DEFINES_PROVIDED}
9120 This macro is called as a witness that the file
9121 @file{conftest.@var{extension}} appropriate for the current language is
9122 complete, including all previously determined results from
9123 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9124 you have a compelling reason to write a conftest file without using
9125 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9126 @code{AC_LANG_CONFTEST}.
9127 @end defmac
9129 @defmac AC_LANG_SOURCE (@var{source})
9130 @acindex{LANG_SOURCE}
9131 Expands into the @var{source}, with the definition of
9132 all the @code{AC_DEFINE} performed so far.  This macro includes an
9133 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9135 In many cases, you may find it more convenient to use the wrapper
9136 @code{AC_LANG_PROGRAM}.
9137 @end defmac
9139 For instance, executing (observe the double quotation!):
9141 @example
9142 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9143 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9144         [http://www.example.org/])
9145 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9146   [Greetings string.])
9147 AC_LANG([C])
9148 AC_LANG_CONFTEST(
9149    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9150 gcc -E -dD conftest.c
9151 @end example
9153 @noindent
9154 on a system with @command{gcc} installed, results in:
9156 @example
9157 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9158 @dots{}
9159 # 1 "conftest.c"
9161 #define PACKAGE_NAME "Hello"
9162 #define PACKAGE_TARNAME "hello"
9163 #define PACKAGE_VERSION "1.0"
9164 #define PACKAGE_STRING "Hello 1.0"
9165 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9166 #define PACKAGE_URL "http://www.example.org/"
9167 #define HELLO_WORLD "Hello, World\n"
9169 const char hw[] = "Hello, World\n";
9170 @end example
9172 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9173 definitions are not automatically translated into constants in the
9174 source code by this macro.
9176 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9177 @acindex{LANG_PROGRAM}
9178 Expands into a source file which consists of the @var{prologue}, and
9179 then @var{body} as body of the main function (e.g., @code{main} in
9180 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9181 available.
9182 @end defmac
9184 For instance:
9186 @example
9187 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9188 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9189         [http://www.example.org/])
9190 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9191   [Greetings string.])
9192 AC_LANG_CONFTEST(
9193 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9194                  [[fputs (hw, stdout);]])])
9195 gcc -E -dD conftest.c
9196 @end example
9198 @noindent
9199 on a system with @command{gcc} installed, results in:
9201 @example
9202 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9203 @dots{}
9204 # 1 "conftest.c"
9206 #define PACKAGE_NAME "Hello"
9207 #define PACKAGE_TARNAME "hello"
9208 #define PACKAGE_VERSION "1.0"
9209 #define PACKAGE_STRING "Hello 1.0"
9210 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9211 #define PACKAGE_URL "http://www.example.org/"
9212 #define HELLO_WORLD "Hello, World\n"
9214 const char hw[] = "Hello, World\n";
9216 main ()
9218 fputs (hw, stdout);
9219   ;
9220   return 0;
9222 @end example
9224 In Erlang tests, the created source file is that of an Erlang module called
9225 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9226 at least
9227 one @code{start/0} function, which is called to perform the test.  The
9228 @var{prologue} is optional code that is inserted between the module header and
9229 the @code{start/0} function definition.  @var{body} is the body of the
9230 @code{start/0} function without the final period (@pxref{Runtime}, about
9231 constraints on this function's behavior).
9233 For instance:
9235 @example
9236 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9237 AC_LANG(Erlang)
9238 AC_LANG_CONFTEST(
9239 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9240                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9241 cat conftest.erl
9242 @end example
9244 @noindent
9245 results in:
9247 @example
9248 -module(conftest).
9249 -export([start/0]).
9250 -define(HELLO_WORLD, "Hello, world!").
9251 start() ->
9252 io:format("~s~n", [?HELLO_WORLD])
9254 @end example
9256 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9257 @acindex{LANG_CALL}
9258 Expands into a source file which consists of the @var{prologue}, and
9259 then a call to the @var{function} as body of the main function (e.g.,
9260 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9261 of the latter are available.
9263 This function will probably be replaced in the future by a version
9264 which would enable specifying the arguments.  The use of this macro is
9265 not encouraged, as it violates strongly the typing system.
9267 This macro cannot be used for Erlang tests.
9268 @end defmac
9270 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9271 @acindex{LANG_FUNC_LINK_TRY}
9272 Expands into a source file which uses the @var{function} in the body of
9273 the main function (e.g., @code{main} in C).  Since it uses
9274 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9276 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9277 It is considered to be severely broken, and in the future will be
9278 removed in favor of actual function calls (with properly typed
9279 arguments).
9281 This macro cannot be used for Erlang tests.
9282 @end defmac
9284 @node Running the Preprocessor
9285 @section Running the Preprocessor
9287 Sometimes one might need to run the preprocessor on some source file.
9288 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9289 your project, not merely run the preprocessor on it; therefore you
9290 certainly want to run the compiler, not the preprocessor.  Resist the
9291 temptation of following the easiest path.
9293 Nevertheless, if you need to run the preprocessor, then use
9294 @code{AC_PREPROC_IFELSE}.
9296 The macros described in this section cannot be used for tests in Erlang,
9297 Fortran, or Go, since those languages require no preprocessor.
9299 @anchor{AC_PREPROC_IFELSE}
9300 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9301   @ovar{action-if-false})
9302 @acindex{PREPROC_IFELSE}
9303 Run the preprocessor of the current language (@pxref{Language Choice})
9304 on the @var{input}, run the shell commands @var{action-if-true} on
9305 success, @var{action-if-false} otherwise.  The @var{input} can be made
9306 by @code{AC_LANG_PROGRAM} and friends.
9308 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9309 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9310 preprocessors.
9312 It is customary to report unexpected failures with
9313 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9314 the preprocessed output in the file @file{conftest.i}.
9315 @end defmac
9317 For instance:
9319 @example
9320 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9321 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9322   [Greetings string.])
9323 AC_PREPROC_IFELSE(
9324    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9325                     [[fputs (hw, stdout);]])],
9326    [AC_MSG_RESULT([OK])],
9327    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9328 @end example
9330 @noindent
9331 results in:
9333 @example
9334 checking for gcc... gcc
9335 checking for C compiler default output file name... a.out
9336 checking whether the C compiler works... yes
9337 checking whether we are cross compiling... no
9338 checking for suffix of executables...
9339 checking for suffix of object files... o
9340 checking whether we are using the GNU C compiler... yes
9341 checking whether gcc accepts -g... yes
9342 checking for gcc option to accept ISO C89... none needed
9343 checking how to run the C preprocessor... gcc -E
9345 @end example
9347 @sp 1
9349 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9350 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9351 it impossible to use it to elaborate sources.  You are encouraged to
9352 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9353 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9354 to run the @emph{preprocessor} and not the compiler?
9356 @anchor{AC_EGREP_HEADER}
9357 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9358   @var{action-if-found}, @ovar{action-if-not-found})
9359 @acindex{EGREP_HEADER}
9360 If the output of running the preprocessor on the system header file
9361 @var{header-file} matches the extended regular expression
9362 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9363 execute @var{action-if-not-found}.
9364 @end defmac
9366 @anchor{AC_EGREP_CPP}
9367 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9368   @ovar{action-if-found}, @ovar{action-if-not-found})
9369 @acindex{EGREP_CPP}
9370 @var{program} is the text of a C or C++ program, on which shell
9371 variable, back quote, and backslash substitutions are performed.  If the
9372 output of running the preprocessor on @var{program} matches the
9373 extended regular expression @var{pattern}, execute shell commands
9374 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9375 @end defmac
9379 @node Running the Compiler
9380 @section Running the Compiler
9382 To check for a syntax feature of the current language's (@pxref{Language
9383 Choice}) compiler, such as whether it recognizes a certain keyword, or
9384 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9385 to compile a small program that uses that feature.
9387 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9388   @ovar{action-if-false})
9389 @acindex{COMPILE_IFELSE}
9390 Run the compiler and compilation flags of the current language
9391 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9392 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9393 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9395 It is customary to report unexpected failures with
9396 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9397 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9398 Linker}).  If needed, @var{action-if-true} can further access the
9399 just-compiled object file @file{conftest.$OBJEXT}.
9401 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9402 current language, which means that if the compiler has not yet been
9403 determined, the compiler determination will be made prior to the body of
9404 the outermust @code{AC_DEFUN} macro that triggered this macro to
9405 expand (@pxref{Expanded Before Required}).
9406 @end defmac
9408 @ovindex ERL
9409 For tests in Erlang, the @var{input} must be the source code of a module named
9410 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9411 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9412 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9413 to ensure that the Erlang module has the right name.
9415 @node Running the Linker
9416 @section Running the Linker
9418 To check for a library, a function, or a global variable, Autoconf
9419 @command{configure} scripts try to compile and link a small program that
9420 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9421 @code{ar} on the C library to try to figure out which functions are
9422 available.  Trying to link with the function is usually a more reliable
9423 approach because it avoids dealing with the variations in the options
9424 and output formats of @code{nm} and @code{ar} and in the location of the
9425 standard libraries.  It also allows configuring for cross-compilation or
9426 checking a function's runtime behavior if needed.  On the other hand,
9427 it can be slower than scanning the libraries once, but accuracy is more
9428 important than speed.
9430 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9431 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9432 to check for libraries (@pxref{Libraries}), by adding the library being
9433 checked for to @code{LIBS} temporarily and trying to link a small
9434 program.
9436 @anchor{AC_LINK_IFELSE}
9437 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9438   @ovar{action-if-false})
9439 @acindex{LINK_IFELSE}
9440 Run the compiler (and compilation flags) and the linker of the current
9441 language (@pxref{Language Choice}) on the @var{input}, run the shell
9442 commands @var{action-if-true} on success, @var{action-if-false}
9443 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9444 friends.  If needed, @var{action-if-true} can further access the
9445 just-linked program file @file{conftest$EXEEXT}.
9447 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9448 current compilation flags.
9450 It is customary to report unexpected failures with
9451 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9452 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9453 @end defmac
9455 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9456 programs are interpreted and do not require linking.
9460 @node Runtime
9461 @section Checking Runtime Behavior
9463 Sometimes you need to find out how a system performs at runtime, such
9464 as whether a given function has a certain capability or bug.  If you
9465 can, make such checks when your program runs instead of when it is
9466 configured.  You can check for things like the machine's endianness when
9467 your program initializes itself.
9469 If you really need to test for a runtime behavior while configuring,
9470 you can write a test program to determine the result, and compile and
9471 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9472 possible, because this prevents people from configuring your package for
9473 cross-compiling.
9475 @anchor{AC_RUN_IFELSE}
9476 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9477   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9478 @acindex{RUN_IFELSE}
9479 If @var{program} compiles and links successfully and returns an exit
9480 status of 0 when executed, run shell commands @var{action-if-true}.
9481 Otherwise, run shell commands @var{action-if-false}.
9483 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9484 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9485 compilation flags of the current language (@pxref{Language Choice}).
9486 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9487 for further testing.
9489 In the @var{action-if-false} section, the failing exit status is
9490 available in the shell variable @samp{$?}.  This exit status might be
9491 that of a failed compilation, or it might be that of a failed program
9492 execution.
9494 If the compiler being used does not produce executables that run on the
9495 system where @command{configure} is being run, then the test program is
9496 not run.  If the optional shell commands @var{action-if-cross-compiling}
9497 are given, those commands are run instead; typically these commands
9498 provide pessimistic defaults that allow cross-compilation to work even
9499 if the guess was wrong.  If the fourth argument is empty or omitted, but
9500 cross-compilation is detected, then @command{configure} prints an error
9501 message and exits.  If you want your package to be useful in a
9502 cross-compilation scenario, you @emph{should} provide a non-empty
9503 @var{action-if-cross-compiling} clause, as well as wrap the
9504 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9505 (@pxref{Caching Results}) which allows the user to override the
9506 pessimistic default if needed.
9508 It is customary to report unexpected failures with
9509 @code{AC_MSG_FAILURE}.
9510 @end defmac
9512 @command{autoconf} prints a warning message when creating
9513 @command{configure} each time it encounters a call to
9514 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9515 given.  If you are not concerned about users configuring your package
9516 for cross-compilation, you may ignore the warning.  A few of the macros
9517 distributed with Autoconf produce this warning message; but if this is a
9518 problem for you, please report it as a bug, along with an appropriate
9519 pessimistic guess to use instead.
9521 To configure for cross-compiling you can also choose a value for those
9522 parameters based on the canonical system name (@pxref{Manual
9523 Configuration}).  Alternatively, set up a test results cache file with
9524 the correct values for the host system (@pxref{Caching Results}).
9526 @ovindex cross_compiling
9527 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9528 in other macros, including a few of the ones that come with Autoconf,
9529 you can test whether the shell variable @code{cross_compiling} is set to
9530 @samp{yes}, and then use an alternate method to get the results instead
9531 of calling the macros.
9533 It is also permissible to temporarily assign to @code{cross_compiling}
9534 in order to force tests to behave as though they are in a
9535 cross-compilation environment, particularly since this provides a way to
9536 test your @var{action-if-cross-compiling} even when you are not using a
9537 cross-compiler.
9539 @example
9540 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9541 # to use the slow link-only method
9542 save_cross_compiling=$cross_compiling
9543 cross_compiling=yes
9544 AC_COMPUTE_INT([@dots{}])
9545 cross_compiling=$save_cross_compiling
9546 @end example
9548 A C or C++ runtime test should be portable.
9549 @xref{Portable C and C++}.
9551 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9552 function: the given status code is used to determine the success of the test
9553 (status is @code{0}) or its failure (status is different than @code{0}), as
9554 explained above.  It must be noted that data output through the standard output
9555 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9556 Therefore, if a test must output configuration information, it is recommended
9557 to create and to output data into the temporary file named @file{conftest.out},
9558 using the functions of module @code{file}.  The @code{conftest.out} file is
9559 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9560 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9561 macro is:
9563 @example
9564 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9565 AC_ERLANG_NEED_ERL
9566 AC_LANG(Erlang)
9567 AC_RUN_IFELSE(
9568   [AC_LANG_PROGRAM([], [dnl
9569     file:write_file("conftest.out", code:lib_dir()),
9570     halt(0)])],
9571   [echo "code:lib_dir() returned: `cat conftest.out`"],
9572   [AC_MSG_FAILURE([test Erlang program execution failed])])
9573 @end example
9576 @node Systemology
9577 @section Systemology
9578 @cindex Systemology
9580 This section aims at presenting some systems and pointers to
9581 documentation.  It may help you addressing particular problems reported
9582 by users.
9584 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9585 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
9586 operating system}.
9588 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9589 contains a table correlating the features of various Posix-conforming
9590 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9591 simplified diagram of how many Unix systems were derived from each
9592 other.
9594 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9595 provides some variants of traditional implementations of Unix utilities.
9597 @table @asis
9598 @item Darwin
9599 @cindex Darwin
9600 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9601 case-preserving, but case insensitive.  This can cause nasty problems,
9602 since for instance the installation attempt for a package having an
9603 @file{INSTALL} file can result in @samp{make install} report that
9604 nothing was to be done!
9606 That's all dependent on whether the file system is a UFS (case
9607 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9608 install the OS on HFS+.  Unfortunately, there are some pieces of
9609 software which really need to be built on UFS@.  We may want to rebuild
9610 Darwin to have both UFS and HFS+ available (and put the /local/build
9611 tree on the UFS).
9613 @item QNX 4.25
9614 @cindex QNX 4.25
9615 @c FIXME: Please, if you feel like writing something more precise,
9616 @c it'd be great.  In particular, I can't understand the difference with
9617 @c QNX Neutrino.
9618 QNX is a realtime operating system running on Intel architecture
9619 meant to be scalable from the small embedded systems to the hundred
9620 processor super-computer.  It claims to be Posix certified.  More
9621 information is available on the
9622 @uref{http://@/www.qnx.com/, QNX home page}.
9624 @item Tru64
9625 @cindex Tru64
9626 @uref{http://@/h30097.www3.hp.com/@/docs/,
9627 Documentation of several versions of Tru64} is available in different
9628 formats.
9630 @item Unix version 7
9631 @cindex Unix version 7
9632 @cindex V7
9633 Officially this was called the ``Seventh Edition'' of ``the UNIX
9634 time-sharing system'' but we use the more-common name ``Unix version 7''.
9635 Documentation is available in the
9636 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9637 Previous versions of Unix are called ``Unix version 6'', etc., but
9638 they were not as widely used.
9639 @end table
9642 @node Multiple Cases
9643 @section Multiple Cases
9645 Some operations are accomplished in several possible ways, depending on
9646 the OS variant.  Checking for them essentially requires a ``case
9647 statement''.  Autoconf does not directly provide one; however, it is
9648 easy to simulate by using a shell variable to keep track of whether a
9649 way to perform the operation has been found yet.
9651 Here is an example that uses the shell variable @code{fstype} to keep
9652 track of whether the remaining cases need to be checked.  Note that
9653 since the value of @code{fstype} is under our control, we don't have to
9654 use the longer @samp{test "x$fstype" = xno}.
9656 @example
9657 @group
9658 AC_MSG_CHECKING([how to get file system type])
9659 fstype=no
9660 # The order of these tests is important.
9661 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9662 #include <sys/fstyp.h>]])],
9663                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9664                      [Define if statvfs exists.])
9665                    fstype=SVR4])
9666 if test $fstype = no; then
9667   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9668 #include <sys/fstyp.h>]])],
9669                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9670                      [Define if USG statfs.])
9671                    fstype=SVR3])
9673 if test $fstype = no; then
9674   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9675 #include <sys/vmount.h>]])]),
9676                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9677                      [Define if AIX statfs.])
9678                    fstype=AIX])
9680 # (more cases omitted here)
9681 AC_MSG_RESULT([$fstype])
9682 @end group
9683 @end example
9685 @c ====================================================== Results of Tests.
9687 @node Results
9688 @chapter Results of Tests
9690 Once @command{configure} has determined whether a feature exists, what can
9691 it do to record that information?  There are four sorts of things it can
9692 do: define a C preprocessor symbol, set a variable in the output files,
9693 save the result in a cache file for future @command{configure} runs, and
9694 print a message letting the user know the result of the test.
9696 @menu
9697 * Defining Symbols::            Defining C preprocessor symbols
9698 * Setting Output Variables::    Replacing variables in output files
9699 * Special Chars in Variables::  Characters to beware of in variables
9700 * Caching Results::             Speeding up subsequent @command{configure} runs
9701 * Printing Messages::           Notifying @command{configure} users
9702 @end menu
9704 @node Defining Symbols
9705 @section Defining C Preprocessor Symbols
9707 A common action to take in response to a feature test is to define a C
9708 preprocessor symbol indicating the results of the test.  That is done by
9709 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9711 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9712 into the output variable @code{DEFS}, which contains an option
9713 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9714 Autoconf version 1, there is no variable @code{DEFS} defined while
9715 @command{configure} is running.  To check whether Autoconf macros have
9716 already defined a certain C preprocessor symbol, test the value of the
9717 appropriate cache variable, as in this example:
9719 @example
9720 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9721                           [Define if vprintf exists.])])
9722 if test "x$ac_cv_func_vprintf" != xyes; then
9723   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9724                             [Define if _doprnt exists.])])
9726 @end example
9728 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9729 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9730 correct values into @code{#define} statements in a template file.
9731 @xref{Configuration Headers}, for more information about this kind of
9732 output.
9734 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9735 @defmacx AC_DEFINE (@var{variable})
9736 @cvindex @var{variable}
9737 @acindex{DEFINE}
9738 Define @var{variable} to @var{value} (verbatim), by defining a C
9739 preprocessor macro for @var{variable}.  @var{variable} should be a C
9740 identifier, optionally suffixed by a parenthesized argument list to
9741 define a C preprocessor macro with arguments.  The macro argument list,
9742 if present, should be a comma-separated list of C identifiers, possibly
9743 terminated by an ellipsis @samp{...} if C99 syntax is employed.
9744 @var{variable} should not contain comments, white space, trigraphs,
9745 backslash-newlines, universal character names, or non-ASCII
9746 characters.
9748 @var{value} may contain backslash-escaped newlines, which will be
9749 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9750 via @code{@@DEFS@@} (with no effect on the compilation, since the
9751 preprocessor sees only one line in the first place).  @var{value} should
9752 not contain raw newlines.  If you are not using
9753 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9754 characters, as @command{make} tends to eat them.  To use a shell
9755 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9757 @var{description} is only useful if you are using
9758 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9759 the generated @file{config.h.in} as the comment before the macro define.
9760 The following example defines the C preprocessor variable
9761 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9763 @example
9764 AC_DEFINE([EQUATION], ["$a > $b"],
9765   [Equation string.])
9766 @end example
9768 If neither @var{value} nor @var{description} are given, then
9769 @var{value} defaults to 1 instead of to the empty string.  This is for
9770 backwards compatibility with older versions of Autoconf, but this usage
9771 is obsolescent and may be withdrawn in future versions of Autoconf.
9773 If the @var{variable} is a literal string, it is passed to
9774 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9776 If multiple @code{AC_DEFINE} statements are executed for the same
9777 @var{variable} name (not counting any parenthesized argument list),
9778 the last one wins.
9779 @end defmac
9781 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9782 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9783 @acindex{DEFINE_UNQUOTED}
9784 @cvindex @var{variable}
9785 Like @code{AC_DEFINE}, but three shell expansions are
9786 performed---once---on @var{variable} and @var{value}: variable expansion
9787 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9788 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9789 characters in the value have no
9790 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9791 @var{variable} or @var{value} is a shell variable.  Examples:
9793 @example
9794 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9795   [Configuration machine file.])
9796 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9797   [getgroups return type.])
9798 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9799   [Translated header name.])
9800 @end example
9801 @end defmac
9803 Due to a syntactical bizarreness of the Bourne shell, do not use
9804 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9805 calls from other macro calls or shell code; that can cause syntax errors
9806 in the resulting @command{configure} script.  Use either blanks or
9807 newlines.  That is, do this:
9809 @example
9810 AC_CHECK_HEADER([elf.h],
9811   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9812 @end example
9814 @noindent
9815 or this:
9817 @example
9818 AC_CHECK_HEADER([elf.h],
9819   [AC_DEFINE([SVR4], [1], [System V Release 4])
9820    LIBS="-lelf $LIBS"])
9821 @end example
9823 @noindent
9824 instead of this:
9826 @example
9827 AC_CHECK_HEADER([elf.h],
9828   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9829 @end example
9831 @node Setting Output Variables
9832 @section Setting Output Variables
9833 @cindex Output variables
9835 Another way to record the results of tests is to set @dfn{output
9836 variables}, which are shell variables whose values are substituted into
9837 files that @command{configure} outputs.  The two macros below create new
9838 output variables.  @xref{Preset Output Variables}, for a list of output
9839 variables that are always available.
9841 @defmac AC_SUBST (@var{variable}, @ovar{value})
9842 @acindex{SUBST}
9843 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9844 substitute the variable @var{variable} into output files (typically one
9845 or more makefiles).  This means that @code{AC_OUTPUT}
9846 replaces instances of @samp{@@@var{variable}@@} in input files with the
9847 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9848 is called.  The value can contain any non-@code{NUL} character, including
9849 newline.  If you are using Automake 1.11 or newer, for newlines in values
9850 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9851 @command{automake} from adding a line @code{@var{variable} =
9852 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9853 Automake, automake, Other things Automake recognizes}).
9855 Variable occurrences should not overlap: e.g., an input file should
9856 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9857 are variable names.
9858 The substituted value is not rescanned for more output variables;
9859 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9860 literally into the output file.  (The algorithm uses the special marker
9861 @code{|#_!!_#|} internally, so neither the substituted value nor the
9862 output file may contain @code{|#_!!_#|}.)
9864 If @var{value} is given, in addition assign it to @var{variable}.
9866 The string @var{variable} is passed to @code{m4_pattern_allow}
9867 (@pxref{Forbidden Patterns}).
9868 @end defmac
9870 @defmac AC_SUBST_FILE (@var{variable})
9871 @acindex{SUBST_FILE}
9872 Another way to create an output variable from a shell variable.  Make
9873 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9874 named by shell variable @var{variable} into output files.  This means
9875 that @code{AC_OUTPUT} replaces instances of
9876 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9877 with the contents of the file that the shell variable @var{variable}
9878 names when @code{AC_OUTPUT} is called.  Set the variable to
9879 @file{/dev/null} for cases that do not have a file to insert.
9880 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9881 line by itself, optionally surrounded by spaces and tabs.  The
9882 substitution replaces the whole line, including the spaces, tabs, and
9883 the terminating newline.
9885 This macro is useful for inserting makefile fragments containing
9886 special dependencies or other @command{make} directives for particular host
9887 or target types into makefiles.  For example, @file{configure.ac}
9888 could contain:
9890 @example
9891 AC_SUBST_FILE([host_frag])
9892 host_frag=$srcdir/conf/sun4.mh
9893 @end example
9895 @noindent
9896 and then a @file{Makefile.in} could contain:
9898 @example
9899 @@host_frag@@
9900 @end example
9902 The string @var{variable} is passed to @code{m4_pattern_allow}
9903 (@pxref{Forbidden Patterns}).
9904 @end defmac
9906 @cindex Precious Variable
9907 @cindex Variable, Precious
9908 Running @command{configure} in varying environments can be extremely
9909 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9910 ./configure}, then the cache, @file{config.h}, and many other output
9911 files depend upon @command{bizarre-cc} being the C compiler.  If
9912 for some reason the user runs @command{./configure} again, or if it is
9913 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9914 and @pxref{config.status Invocation}), then the configuration can be
9915 inconsistent, composed of results depending upon two different
9916 compilers.
9918 Environment variables that affect this situation, such as @samp{CC}
9919 above, are called @dfn{precious variables}, and can be declared as such
9920 by @code{AC_ARG_VAR}.
9922 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9923 @acindex{ARG_VAR}
9924 Declare @var{variable} is a precious variable, and include its
9925 @var{description} in the variable section of @samp{./configure --help}.
9927 Being precious means that
9928 @itemize @minus
9929 @item
9930 @var{variable} is substituted via @code{AC_SUBST}.
9932 @item
9933 The value of @var{variable} when @command{configure} was launched is
9934 saved in the cache, including if it was not specified on the command
9935 line but via the environment.  Indeed, while @command{configure} can
9936 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9937 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9938 which, unfortunately, is what most users do.
9940 We emphasize that it is the @emph{initial} value of @var{variable} which
9941 is saved, not that found during the execution of @command{configure}.
9942 Indeed, specifying @samp{./configure FOO=foo} and letting
9943 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9944 different things.
9946 @item
9947 @var{variable} is checked for consistency between two
9948 @command{configure} runs.  For instance:
9950 @example
9951 $ @kbd{./configure --silent --config-cache}
9952 $ @kbd{CC=cc ./configure --silent --config-cache}
9953 configure: error: `CC' was not set in the previous run
9954 configure: error: changes in the environment can compromise \
9955 the build
9956 configure: error: run `make distclean' and/or \
9957 `rm config.cache' and start over
9958 @end example
9960 @noindent
9961 and similarly if the variable is unset, or if its content is changed.
9962 If the content has white space changes only, then the error is degraded
9963 to a warning only, but the old value is reused.
9965 @item
9966 @var{variable} is kept during automatic reconfiguration
9967 (@pxref{config.status Invocation}) as if it had been passed as a command
9968 line argument, including when no cache is used:
9970 @example
9971 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9972 $ @kbd{./config.status --recheck}
9973 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9974   CC=/usr/bin/cc  --no-create --no-recursion
9975 @end example
9976 @end itemize
9977 @end defmac
9979 @node Special Chars in Variables
9980 @section Special Characters in Output Variables
9981 @cindex Output variables, special characters in
9983 Many output variables are intended to be evaluated both by
9984 @command{make} and by the shell.  Some characters are expanded
9985 differently in these two contexts, so to avoid confusion these
9986 variables' values should not contain any of the following characters:
9988 @example
9989 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9990 @end example
9992 Also, these variables' values should neither contain newlines, nor start
9993 with @samp{~}, nor contain white space or @samp{:} immediately followed
9994 by @samp{~}.  The values can contain nonempty sequences of white space
9995 characters like tabs and spaces, but each such sequence might
9996 arbitrarily be replaced by a single space during substitution.
9998 These restrictions apply both to the values that @command{configure}
9999 computes, and to the values set directly by the user.  For example, the
10000 following invocations of @command{configure} are problematic, since they
10001 attempt to use special characters within @code{CPPFLAGS} and white space
10002 within @code{$(srcdir)}:
10004 @example
10005 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10007 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10008 @end example
10010 @node Caching Results
10011 @section Caching Results
10012 @cindex Cache
10014 To avoid checking for the same features repeatedly in various
10015 @command{configure} scripts (or in repeated runs of one script),
10016 @command{configure} can optionally save the results of many checks in a
10017 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10018 runs with caching enabled and finds a cache file, it reads the results
10019 of previous runs from the cache and avoids rerunning those checks.  As a
10020 result, @command{configure} can then run much faster than if it had to
10021 perform all of the checks every time.
10023 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10024 @acindex{CACHE_VAL}
10025 Ensure that the results of the check identified by @var{cache-id} are
10026 available.  If the results of the check were in the cache file that was
10027 read, and @command{configure} was not given the @option{--quiet} or
10028 @option{--silent} option, print a message saying that the result was
10029 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10030 the shell commands are run to determine the value, the value is
10031 saved in the cache file just before @command{configure} creates its output
10032 files.  @xref{Cache Variable Names}, for how to choose the name of the
10033 @var{cache-id} variable.
10035 The @var{commands-to-set-it} @emph{must have no side effects} except for
10036 setting the variable @var{cache-id}, see below.
10037 @end defmac
10039 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10040   @var{commands-to-set-it})
10041 @acindex{CACHE_CHECK}
10042 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10043 messages.  This macro provides a convenient shorthand for the most
10044 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10045 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10046 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10048 The @var{commands-to-set-it} @emph{must have no side effects} except for
10049 setting the variable @var{cache-id}, see below.
10050 @end defmac
10052 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10053 @code{AC_CACHE_CHECK}, because people are tempted to call
10054 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10055 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10056 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10057 instance, the following macro is broken:
10059 @example
10060 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10061 @group
10062 AC_DEFUN([AC_SHELL_TRUE],
10063 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10064                 [my_cv_shell_true_works=no
10065                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10066                  if test "x$my_cv_shell_true_works" = xyes; then
10067                    AC_DEFINE([TRUE_WORKS], [1],
10068                              [Define if `true(1)' works properly.])
10069                  fi])
10071 @end group
10072 @end example
10074 @noindent
10075 This fails if the cache is enabled: the second time this macro is run,
10076 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10079 @example
10080 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10081 @group
10082 AC_DEFUN([AC_SHELL_TRUE],
10083 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10084                 [my_cv_shell_true_works=no
10085                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10086  if test "x$my_cv_shell_true_works" = xyes; then
10087    AC_DEFINE([TRUE_WORKS], [1],
10088              [Define if `true(1)' works properly.])
10089  fi
10091 @end group
10092 @end example
10094 Also, @var{commands-to-set-it} should not print any messages, for
10095 example with @code{AC_MSG_CHECKING}; do that before calling
10096 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10097 the results of the check are retrieved from the cache or determined by
10098 running the shell commands.
10100 @menu
10101 * Cache Variable Names::        Shell variables used in caches
10102 * Cache Files::                 Files @command{configure} uses for caching
10103 * Cache Checkpointing::         Loading and saving the cache file
10104 @end menu
10106 @node Cache Variable Names
10107 @subsection Cache Variable Names
10108 @cindex Cache variable
10110 The names of cache variables should have the following format:
10112 @example
10113 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10114 @end example
10116 @noindent
10117 for example, @samp{ac_cv_header_stat_broken} or
10118 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10120 @table @asis
10121 @item @var{package-prefix}
10122 An abbreviation for your package or organization; the same prefix you
10123 begin local Autoconf macros with, except lowercase by convention.
10124 For cache values used by the distributed Autoconf macros, this value is
10125 @samp{ac}.
10127 @item @code{_cv_}
10128 Indicates that this shell variable is a cache value.  This string
10129 @emph{must} be present in the variable name, including the leading
10130 underscore.
10132 @item @var{value-type}
10133 A convention for classifying cache values, to produce a rational naming
10134 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10136 @item @var{specific-value}
10137 Which member of the class of cache values this test applies to.
10138 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10139 output variable (@samp{INSTALL}).
10141 @item @var{additional-options}
10142 Any particular behavior of the specific member that this test applies to.
10143 For example, @samp{broken} or @samp{set}.  This part of the name may
10144 be omitted if it does not apply.
10145 @end table
10147 The values assigned to cache variables may not contain newlines.
10148 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10149 names of files or functions; so this is not an important restriction.
10150 @ref{Cache Variable Index} for an index of cache variables with
10151 documented semantics.
10154 @node Cache Files
10155 @subsection Cache Files
10157 A cache file is a shell script that caches the results of configure
10158 tests run on one system so they can be shared between configure scripts
10159 and configure runs.  It is not useful on other systems.  If its contents
10160 are invalid for some reason, the user may delete or edit it, or override
10161 documented cache variables on the @command{configure} command line.
10163 By default, @command{configure} uses no cache file,
10164 to avoid problems caused by accidental
10165 use of stale cache files.
10167 To enable caching, @command{configure} accepts @option{--config-cache} (or
10168 @option{-C}) to cache results in the file @file{config.cache}.
10169 Alternatively, @option{--cache-file=@var{file}} specifies that
10170 @var{file} be the cache file.  The cache file is created if it does not
10171 exist already.  When @command{configure} calls @command{configure} scripts in
10172 subdirectories, it uses the @option{--cache-file} argument so that they
10173 share the same cache.  @xref{Subdirectories}, for information on
10174 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10176 @file{config.status} only pays attention to the cache file if it is
10177 given the @option{--recheck} option, which makes it rerun
10178 @command{configure}.
10180 It is wrong to try to distribute cache files for particular system types.
10181 There is too much room for error in doing that, and too much
10182 administrative overhead in maintaining them.  For any features that
10183 can't be guessed automatically, use the standard method of the canonical
10184 system type and linking files (@pxref{Manual Configuration}).
10186 The site initialization script can specify a site-wide cache file to
10187 use, instead of the usual per-program cache.  In this case, the cache
10188 file gradually accumulates information whenever someone runs a new
10189 @command{configure} script.  (Running @command{configure} merges the new cache
10190 results with the existing cache file.)  This may cause problems,
10191 however, if the system configuration (e.g., the installed libraries or
10192 compilers) changes and the stale cache file is not deleted.
10194 If @command{configure} is interrupted at the right time when it updates
10195 a cache file outside of the build directory where the @command{configure}
10196 script is run, it may leave behind a temporary file named after the
10197 cache file with digits following it.  You may safely delete such a file.
10200 @node Cache Checkpointing
10201 @subsection Cache Checkpointing
10203 If your configure script, or a macro called from @file{configure.ac}, happens
10204 to abort the configure process, it may be useful to checkpoint the cache
10205 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10206 reduces the amount of time it takes to rerun the configure script with
10207 (hopefully) the error that caused the previous abort corrected.
10209 @c FIXME: Do we really want to document this guy?
10210 @defmac AC_CACHE_LOAD
10211 @acindex{CACHE_LOAD}
10212 Loads values from existing cache file, or creates a new cache file if a
10213 cache file is not found.  Called automatically from @code{AC_INIT}.
10214 @end defmac
10216 @defmac AC_CACHE_SAVE
10217 @acindex{CACHE_SAVE}
10218 Flushes all cached values to the cache file.  Called automatically from
10219 @code{AC_OUTPUT}, but it can be quite useful to call
10220 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10221 @end defmac
10223 For instance:
10225 @example
10226 @r{ @dots{} AC_INIT, etc. @dots{}}
10227 @group
10228 # Checks for programs.
10229 AC_PROG_CC
10230 AC_PROG_AWK
10231 @r{ @dots{} more program checks @dots{}}
10232 AC_CACHE_SAVE
10233 @end group
10235 @group
10236 # Checks for libraries.
10237 AC_CHECK_LIB([nsl], [gethostbyname])
10238 AC_CHECK_LIB([socket], [connect])
10239 @r{ @dots{} more lib checks @dots{}}
10240 AC_CACHE_SAVE
10241 @end group
10243 @group
10244 # Might abort@dots{}
10245 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10246 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10247 @end group
10248 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10249 @end example
10251 @node Printing Messages
10252 @section Printing Messages
10253 @cindex Messages, from @command{configure}
10255 @command{configure} scripts need to give users running them several kinds
10256 of information.  The following macros print messages in ways appropriate
10257 for each kind.  The arguments to all of them get enclosed in shell
10258 double quotes, so the shell performs variable and back-quote
10259 substitution on them.
10261 These macros are all wrappers around the @command{echo} shell command.
10262 They direct output to the appropriate file descriptor (@pxref{File
10263 Descriptor Macros}).
10264 @command{configure} scripts should rarely need to run @command{echo} directly
10265 to print messages for the user.  Using these macros makes it easy to
10266 change how and when each kind of message is printed; such changes need
10267 only be made to the macro definitions and all the callers change
10268 automatically.
10270 To diagnose static issues, i.e., when @command{autoconf} is run, see
10271 @ref{Diagnostic Macros}.
10273 @defmac AC_MSG_CHECKING (@var{feature-description})
10274 @acindex{MSG_CHECKING}
10275 Notify the user that @command{configure} is checking for a particular
10276 feature.  This macro prints a message that starts with @samp{checking }
10277 and ends with @samp{...} and no newline.  It must be followed by a call
10278 to @code{AC_MSG_RESULT} to print the result of the check and the
10279 newline.  The @var{feature-description} should be something like
10280 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10281 c89}.
10283 This macro prints nothing if @command{configure} is run with the
10284 @option{--quiet} or @option{--silent} option.
10285 @end defmac
10287 @anchor{AC_MSG_RESULT}
10288 @defmac AC_MSG_RESULT (@var{result-description})
10289 @acindex{MSG_RESULT}
10290 Notify the user of the results of a check.  @var{result-description} is
10291 almost always the value of the cache variable for the check, typically
10292 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10293 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10294 the completion of the message printed by the call to
10295 @code{AC_MSG_CHECKING}.
10297 This macro prints nothing if @command{configure} is run with the
10298 @option{--quiet} or @option{--silent} option.
10299 @end defmac
10301 @anchor{AC_MSG_NOTICE}
10302 @defmac AC_MSG_NOTICE (@var{message})
10303 @acindex{MSG_NOTICE}
10304 Deliver the @var{message} to the user.  It is useful mainly to print a
10305 general description of the overall purpose of a group of feature checks,
10306 e.g.,
10308 @example
10309 AC_MSG_NOTICE([checking if stack overflow is detectable])
10310 @end example
10312 This macro prints nothing if @command{configure} is run with the
10313 @option{--quiet} or @option{--silent} option.
10314 @end defmac
10316 @anchor{AC_MSG_ERROR}
10317 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10318 @acindex{MSG_ERROR}
10319 Notify the user of an error that prevents @command{configure} from
10320 completing.  This macro prints an error message to the standard error
10321 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10322 by default, except that @samp{0} is converted to @samp{1}).
10323 @var{error-description} should be something like @samp{invalid value
10324 $HOME for \$HOME}.
10326 The @var{error-description} should start with a lower-case letter, and
10327 ``cannot'' is preferred to ``can't''.
10328 @end defmac
10330 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10331 @acindex{MSG_FAILURE}
10332 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10333 prevents @command{configure} from completing @emph{and} that additional
10334 details are provided in @file{config.log}.  This is typically used when
10335 abnormal results are found during a compilation.
10336 @end defmac
10338 @anchor{AC_MSG_WARN}
10339 @defmac AC_MSG_WARN (@var{problem-description})
10340 @acindex{MSG_WARN}
10341 Notify the @command{configure} user of a possible problem.  This macro
10342 prints the message to the standard error output; @command{configure}
10343 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10344 provide a default (back-up) behavior for the situations they warn about.
10345 @var{problem-description} should be something like @samp{ln -s seems to
10346 make hard links}.
10347 @end defmac
10351 @c ====================================================== Programming in M4.
10353 @node Programming in M4
10354 @chapter Programming in M4
10355 @cindex M4
10357 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10358 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10359 provides macros dedicated to shell script generation.
10361 As of this version of Autoconf, these two layers still contain
10362 experimental macros, whose interface might change in the future.  As a
10363 matter of fact, @emph{anything that is not documented must not be used}.
10365 @menu
10366 * M4 Quotation::                Protecting macros from unwanted expansion
10367 * Using autom4te::              The Autoconf executables backbone
10368 * Programming in M4sugar::      Convenient pure M4 macros
10369 * Debugging via autom4te::      Figuring out what M4 was doing
10370 @end menu
10372 @node M4 Quotation
10373 @section M4 Quotation
10374 @cindex M4 quotation
10375 @cindex quotation
10377 The most common problem with existing macros is an improper quotation.
10378 This section, which users of Autoconf can skip, but which macro writers
10379 @emph{must} read, first justifies the quotation scheme that was chosen
10380 for Autoconf and then ends with a rule of thumb.  Understanding the
10381 former helps one to follow the latter.
10383 @menu
10384 * Active Characters::           Characters that change the behavior of M4
10385 * One Macro Call::              Quotation and one macro call
10386 * Quoting and Parameters::      M4 vs. shell parameters
10387 * Quotation and Nested Macros::  Macros calling macros
10388 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10389 * Quadrigraphs::                Another way to escape special characters
10390 * Balancing Parentheses::       Dealing with unbalanced parentheses
10391 * Quotation Rule Of Thumb::     One parenthesis, one quote
10392 @end menu
10394 @node Active Characters
10395 @subsection Active Characters
10397 To fully understand where proper quotation is important, you first need
10398 to know what the special characters are in Autoconf: @samp{#} introduces
10399 a comment inside which no macro expansion is performed, @samp{,}
10400 separates arguments, @samp{[} and @samp{]} are the quotes
10401 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10402 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10403 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10404 @samp{$} inside a macro definition.
10406 In order to understand the delicate case of macro calls, we first have
10407 to present some obvious failures.  Below they are ``obvious-ified'',
10408 but when you find them in real life, they are usually in disguise.
10410 Comments, introduced by a hash and running up to the newline, are opaque
10411 tokens to the top level: active characters are turned off, and there is
10412 no macro expansion:
10414 @example
10415 # define([def], ine)
10416 @result{}# define([def], ine)
10417 @end example
10419 Each time there can be a macro expansion, there is a quotation
10420 expansion, i.e., one level of quotes is stripped:
10422 @example
10423 int tab[10];
10424 @result{}int tab10;
10425 [int tab[10];]
10426 @result{}int tab[10];
10427 @end example
10429 Without this in mind, the reader might try hopelessly to use her macro
10430 @code{array}:
10432 @example
10433 define([array], [int tab[10];])
10434 array
10435 @result{}int tab10;
10436 [array]
10437 @result{}array
10438 @end example
10440 @noindent
10441 How can you correctly output the intended results@footnote{Using
10442 @code{defn}.}?
10445 @node One Macro Call
10446 @subsection One Macro Call
10448 Let's proceed on the interaction between active characters and macros
10449 with this small macro, which just returns its first argument:
10451 @example
10452 define([car], [$1])
10453 @end example
10455 @noindent
10456 The two pairs of quotes above are not part of the arguments of
10457 @code{define}; rather, they are understood by the top level when it
10458 tries to find the arguments of @code{define}.  Therefore, assuming
10459 @code{car} is not already defined, it is equivalent to write:
10461 @example
10462 define(car, $1)
10463 @end example
10465 @noindent
10466 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10467 quotes, it is bad practice for Autoconf macros which must both be more
10468 robust and also advocate perfect style.
10470 At the top level, there are only two possibilities: either you
10471 quote or you don't:
10473 @example
10474 car(foo, bar, baz)
10475 @result{}foo
10476 [car(foo, bar, baz)]
10477 @result{}car(foo, bar, baz)
10478 @end example
10480 Let's pay attention to the special characters:
10482 @example
10483 car(#)
10484 @error{}EOF in argument list
10485 @end example
10487 The closing parenthesis is hidden in the comment; with a hypothetical
10488 quoting, the top level understood it this way:
10490 @example
10491 car([#)]
10492 @end example
10494 @noindent
10495 Proper quotation, of course, fixes the problem:
10497 @example
10498 car([#])
10499 @result{}#
10500 @end example
10502 Here are more examples:
10504 @example
10505 car(foo, bar)
10506 @result{}foo
10507 car([foo, bar])
10508 @result{}foo, bar
10509 car((foo, bar))
10510 @result{}(foo, bar)
10511 car([(foo], [bar)])
10512 @result{}(foo
10513 define([a], [b])
10514 @result{}
10515 car(a)
10516 @result{}b
10517 car([a])
10518 @result{}b
10519 car([[a]])
10520 @result{}a
10521 car([[[a]]])
10522 @result{}[a]
10523 @end example
10525 @node Quoting and Parameters
10526 @subsection Quoting and Parameters
10528 When M4 encounters @samp{$} within a macro definition, followed
10529 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10530 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10531 expansion.  This happens regardless of how many layers of quotes the
10532 parameter expansion is nested within, or even if it occurs in text that
10533 will be rescanned as a comment.
10535 @example
10536 define([none], [$1])
10537 @result{}
10538 define([one], [[$1]])
10539 @result{}
10540 define([two], [[[$1]]])
10541 @result{}
10542 define([comment], [# $1])
10543 @result{}
10544 define([active], [ACTIVE])
10545 @result{}
10546 none([active])
10547 @result{}ACTIVE
10548 one([active])
10549 @result{}active
10550 two([active])
10551 @result{}[active]
10552 comment([active])
10553 @result{}# active
10554 @end example
10556 On the other hand, since autoconf generates shell code, you often want
10557 to output shell variable expansion, rather than performing M4 parameter
10558 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10559 from the next character in the definition of your macro.  If the macro
10560 definition occurs in single-quoted text, then insert another level of
10561 quoting; if the usage is already inside a double-quoted string, then
10562 split it into concatenated strings.
10564 @example
10565 define([single], [a single-quoted $[]1 definition])
10566 @result{}
10567 define([double], [[a double-quoted $][1 definition]])
10568 @result{}
10569 single
10570 @result{}a single-quoted $1 definition
10571 double
10572 @result{}a double-quoted $1 definition
10573 @end example
10575 Posix states that M4 implementations are free to provide implementation
10576 extensions when @samp{$@{} is encountered in a macro definition.
10577 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10578 extensions that will be available in the future GNU M4 2.0,
10579 but guarantees that all other instances of @samp{$@{} will be output
10580 literally.  Therefore, this idiom can also be used to output shell code
10581 parameter references:
10583 @example
10584 define([first], [$@{1@}])first
10585 @result{}$@{1@}
10586 @end example
10588 Posix also states that @samp{$11} should expand to the first parameter
10589 concatenated with a literal @samp{1}, although some versions of
10590 GNU M4 expand the eleventh parameter instead.  For
10591 portability, you should only use single-digit M4 parameter expansion.
10593 With this in mind, we can explore the cases where macros invoke
10594 macros@enddots{}
10596 @node Quotation and Nested Macros
10597 @subsection Quotation and Nested Macros
10599 The examples below use the following macros:
10601 @example
10602 define([car], [$1])
10603 define([active], [ACT, IVE])
10604 define([array], [int tab[10]])
10605 @end example
10607 Each additional embedded macro call introduces other possible
10608 interesting quotations:
10610 @example
10611 car(active)
10612 @result{}ACT
10613 car([active])
10614 @result{}ACT, IVE
10615 car([[active]])
10616 @result{}active
10617 @end example
10619 In the first case, the top level looks for the arguments of @code{car},
10620 and finds @samp{active}.  Because M4 evaluates its arguments
10621 before applying the macro, @samp{active} is expanded, which results in:
10623 @example
10624 car(ACT, IVE)
10625 @result{}ACT
10626 @end example
10628 @noindent
10629 In the second case, the top level gives @samp{active} as first and only
10630 argument of @code{car}, which results in:
10632 @example
10633 active
10634 @result{}ACT, IVE
10635 @end example
10637 @noindent
10638 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10639 In the third case, @code{car} receives @samp{[active]}, which results in:
10641 @example
10642 [active]
10643 @result{}active
10644 @end example
10646 @noindent
10647 exactly as we already saw above.
10649 The example above, applied to a more realistic example, gives:
10651 @example
10652 car(int tab[10];)
10653 @result{}int tab10;
10654 car([int tab[10];])
10655 @result{}int tab10;
10656 car([[int tab[10];]])
10657 @result{}int tab[10];
10658 @end example
10660 @noindent
10661 Huh?  The first case is easily understood, but why is the second wrong,
10662 and the third right?  To understand that, you must know that after
10663 M4 expands a macro, the resulting text is immediately subjected
10664 to macro expansion and quote removal.  This means that the quote removal
10665 occurs twice---first before the argument is passed to the @code{car}
10666 macro, and second after the @code{car} macro expands to the first
10667 argument.
10669 As the author of the Autoconf macro @code{car}, you then consider it to
10670 be incorrect that your users have to double-quote the arguments of
10671 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10672 quoted car:
10674 @example
10675 define([qar], [[$1]])
10676 @end example
10678 @noindent
10679 and check that @code{qar} is properly fixed:
10681 @example
10682 qar([int tab[10];])
10683 @result{}int tab[10];
10684 @end example
10686 @noindent
10687 Ahhh!  That's much better.
10689 But note what you've done: now that the result of @code{qar} is always
10690 a literal string, the only time a user can use nested macros is if she
10691 relies on an @emph{unquoted} macro call:
10693 @example
10694 qar(active)
10695 @result{}ACT
10696 qar([active])
10697 @result{}active
10698 @end example
10700 @noindent
10701 leaving no way for her to reproduce what she used to do with @code{car}:
10703 @example
10704 car([active])
10705 @result{}ACT, IVE
10706 @end example
10708 @noindent
10709 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10710 macros:
10712 @example
10713 define([my_includes], [#include <stdio.h>])
10714 car([my_includes])
10715 @result{}#include <stdio.h>
10716 qar(my_includes)
10717 @error{}EOF in argument list
10718 @end example
10720 This macro, @code{qar}, because it double quotes its arguments, forces
10721 its users to leave their macro calls unquoted, which is dangerous.
10722 Commas and other active symbols are interpreted by M4 before
10723 they are given to the macro, often not in the way the users expect.
10724 Also, because @code{qar} behaves differently from the other macros,
10725 it's an exception that should be avoided in Autoconf.
10727 @node Changequote is Evil
10728 @subsection @code{changequote} is Evil
10729 @cindex @code{changequote}
10731 The temptation is often high to bypass proper quotation, in particular
10732 when it's late at night.  Then, many experienced Autoconf hackers
10733 finally surrender to the dark side of the force and use the ultimate
10734 weapon: @code{changequote}.
10736 The M4 builtin @code{changequote} belongs to a set of primitives that
10737 allow one to adjust the syntax of the language to adjust it to one's
10738 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10739 quotes, but in the context of shell programming (and actually of most
10740 programming languages), that's about the worst choice one can make:
10741 because of strings and back-quoted expressions in shell code (such as
10742 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10743 programming languages (as in @samp{'0'}), there are many unbalanced
10744 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10745 not impossible.  In order to make M4 useful in such a context, its
10746 designers have equipped it with @code{changequote}, which makes it
10747 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10748 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10749 because they are unlikely characters, but @emph{because they are
10750 characters unlikely to be unbalanced}.
10752 There are other magic primitives, such as @code{changecom} to specify
10753 what syntactic forms are comments (it is common to see
10754 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10755 @code{changeword} and @code{changesyntax} to change other syntactic
10756 details (such as the character to denote the @var{n}th argument, @samp{$} by
10757 default, the parentheses around arguments, etc.).
10759 These primitives are really meant to make M4 more useful for specific
10760 domains: they should be considered like command line options:
10761 @option{--quotes}, @option{--comments}, @option{--words}, and
10762 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10763 it makes M4 libraries self contained (no need for additional options).
10765 There lies the problem@enddots{}
10767 @sp 1
10769 The problem is that it is then tempting to use them in the middle of an
10770 M4 script, as opposed to its initialization.  This, if not carefully
10771 thought out, can lead to disastrous effects: @emph{you are changing the
10772 language in the middle of the execution}.  Changing and restoring the
10773 syntax is often not enough: if you happened to invoke macros in between,
10774 these macros are lost, as the current syntax is probably not
10775 the one they were implemented with.
10777 @c FIXME: I've been looking for a short, real case example, but I
10778 @c lost them all :(
10781 @node Quadrigraphs
10782 @subsection Quadrigraphs
10783 @cindex quadrigraphs
10784 @cindex @samp{@@S|@@}
10785 @cindex @samp{@@&t@@}
10786 @c Info cannot handle `:' in index entries.
10787 @ifnotinfo
10788 @cindex @samp{@@<:@@}
10789 @cindex @samp{@@:>@@}
10790 @cindex @samp{@@%:@@}
10791 @cindex @samp{@@@{:@@}
10792 @cindex @samp{@@:@}@@}
10793 @end ifnotinfo
10795 When writing an Autoconf macro you may occasionally need to generate
10796 special characters that are difficult to express with the standard
10797 Autoconf quoting rules.  For example, you may need to output the regular
10798 expression @samp{[^[]}, which matches any character other than @samp{[}.
10799 This expression contains unbalanced brackets so it cannot be put easily
10800 into an M4 macro.
10802 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10803 and @code{m4_expand}) which internally use special markers in addition
10804 to the regular quoting characters.  If the arguments to these macros
10805 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10806 might behave incorrectly.
10808 You can work around these problems by using one of the following
10809 @dfn{quadrigraphs}:
10811 @table @samp
10812 @item @@<:@@
10813 @samp{[}
10814 @item @@:>@@
10815 @samp{]}
10816 @item @@S|@@
10817 @samp{$}
10818 @item @@%:@@
10819 @samp{#}
10820 @item @@@{:@@
10821 @samp{(}
10822 @item @@:@}@@
10823 @samp{)}
10824 @item @@&t@@
10825 Expands to nothing.
10826 @end table
10828 Quadrigraphs are replaced at a late stage of the translation process,
10829 after @command{m4} is run, so they do not get in the way of M4 quoting.
10830 For example, the string @samp{^@@<:@@}, independently of its quotation,
10831 appears as @samp{^[} in the output.
10833 The empty quadrigraph can be used:
10835 @itemize @minus
10836 @item to mark trailing spaces explicitly
10838 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10840 @item to produce quadrigraphs and other strings reserved by m4sugar
10842 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10843 contrived example:
10845 @example
10846 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10847 m4_split([a )@}>=- b -=<@{( c])
10848 @result{}[a], [], [B], [], [c]
10849 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10850 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10851 @end example
10853 @item to escape @emph{occurrences} of forbidden patterns
10855 For instance you might want to mention @code{AC_FOO} in a comment, while
10856 still being sure that @command{autom4te} still catches unexpanded
10857 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10858 @end itemize
10860 The name @samp{@@&t@@} was suggested by Paul Eggert:
10862 @quotation
10863 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10864 own invention, but the @samp{t} came from the source code of the
10865 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10866 and which used @samp{mt} to denote the empty string.  In C, it would
10867 have looked like something like:
10869 @example
10870 char const mt[] = "";
10871 @end example
10873 @noindent
10874 but of course the source code was written in Algol 68.
10876 I don't know where he got @samp{mt} from: it could have been his own
10877 invention, and I suppose it could have been a common pun around the
10878 Cambridge University computer lab at the time.
10879 @end quotation
10882 @node Balancing Parentheses
10883 @subsection Dealing with unbalanced parentheses
10884 @cindex balancing parentheses
10885 @cindex parentheses, balancing
10886 @cindex unbalanced parentheses, managing
10888 One of the pitfalls of portable shell programming is that @command{case}
10889 statements require unbalanced parentheses (@pxref{case, , Limitations of
10890 Shell Builtins}).  With syntax highlighting
10891 editors, the presence of unbalanced @samp{)} can interfere with editors
10892 that perform syntax highlighting of macro contents based on finding the
10893 matching @samp{(}.  Another concern is how much editing must be done
10894 when transferring code snippets between shell scripts and macro
10895 definitions.  But most importantly, the presence of unbalanced
10896 parentheses can introduce expansion bugs.
10898 For an example, here is an underquoted attempt to use the macro
10899 @code{my_case}, which happens to expand to a portable @command{case}
10900 statement:
10902 @example
10903 AC_DEFUN([my_case],
10904 [case $file_name in
10905   *.c) echo "C source code";;
10906 esac])
10907 AS_IF(:, my_case)
10908 @end example
10910 @noindent
10911 In the above example, the @code{AS_IF} call underquotes its arguments.
10912 As a result, the unbalanced @samp{)} generated by the premature
10913 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10914 truncated parameter, and the expansion is syntactically invalid:
10916 @example
10917 if :; then
10918   case $file_name in
10919   *.c
10920 fi echo "C source code";;
10921 esac)
10922 @end example
10924 If nothing else, this should emphasize the importance of the quoting
10925 arguments to macro calls.  On the other hand, there are several
10926 variations for defining @code{my_case} to be more robust, even when used
10927 without proper quoting, each with some benefits and some drawbacks.
10929 @itemize @w{}
10930 @item Creative literal shell comment
10931 @example
10932 AC_DEFUN([my_case],
10933 [case $file_name in #(
10934   *.c) echo "C source code";;
10935 esac])
10936 @end example
10937 @noindent
10938 This version provides balanced parentheses to several editors, and can
10939 be copied and pasted into a terminal as is.  Unfortunately, it is still
10940 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10941 that masks the normal properties of @samp{(}.
10943 @item Quadrigraph shell comment
10944 @example
10945 AC_DEFUN([my_case],
10946 [case $file_name in @@%:@@(
10947   *.c) echo "C source code";;
10948 esac])
10949 @end example
10950 @noindent
10951 This version provides balanced parentheses to even more editors, and can
10952 be used as a balanced Autoconf argument.  Unfortunately, it requires
10953 some editing before it can be copied and pasted into a terminal, and the
10954 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10956 @item Quoting just the parenthesis
10957 @example
10958 AC_DEFUN([my_case],
10959 [case $file_name in
10960   *.c[)] echo "C source code";;
10961 esac])
10962 @end example
10963 @noindent
10964 This version quotes the @samp{)}, so that it can be used as a balanced
10965 Autoconf argument.  As written, this is not balanced to an editor, but
10966 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10967 still requires some edits before it can be copied and pasted into a
10968 terminal.
10970 @item Double-quoting the entire statement
10971 @example
10972 AC_DEFUN([my_case],
10973 [[case $file_name in #(
10974   *.c) echo "C source code";;
10975 esac]])
10976 @end example
10977 @noindent
10978 Since the entire macro is double-quoted, there is no problem with using
10979 this as an Autoconf argument; and since the double-quoting is over the
10980 entire statement, this code can be easily copied and pasted into a
10981 terminal.  However, the double quoting prevents the expansion of any
10982 macros inside the case statement, which may cause its own set of
10983 problems.
10985 @item Using @code{AS_CASE}
10986 @example
10987 AC_DEFUN([my_case],
10988 [AS_CASE([$file_name],
10989   [*.c], [echo "C source code"])])
10990 @end example
10991 @noindent
10992 This version avoids the balancing issue altogether, by relying on
10993 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10994 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10995 statement, rather than within a branch of the case statement that might
10996 not be taken.  However, the abstraction comes with a penalty that it is
10997 no longer a quick copy, paste, and edit to get back to shell code.
10998 @end itemize
11001 @node Quotation Rule Of Thumb
11002 @subsection Quotation Rule Of Thumb
11004 To conclude, the quotation rule of thumb is:
11006 @center @emph{One pair of quotes per pair of parentheses.}
11008 Never over-quote, never under-quote, in particular in the definition of
11009 macros.  In the few places where the macros need to use brackets
11010 (usually in C program text or regular expressions), properly quote
11011 @emph{the arguments}!
11013 It is common to read Autoconf programs with snippets like:
11015 @example
11016 AC_TRY_LINK(
11017 changequote(<<, >>)dnl
11018 <<#include <time.h>
11019 #ifndef tzname /* For SGI.  */
11020 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11021 #endif>>,
11022 changequote([, ])dnl
11023 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11024 @end example
11026 @noindent
11027 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11028 double quoting, so you just need:
11030 @example
11031 AC_TRY_LINK(
11032 [#include <time.h>
11033 #ifndef tzname /* For SGI.  */
11034 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11035 #endif],
11036             [atoi (*tzname);],
11037             [ac_cv_var_tzname=yes],
11038             [ac_cv_var_tzname=no])
11039 @end example
11041 @noindent
11042 The M4-fluent reader might note that these two examples are rigorously
11043 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11044 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11045 quotes are not part of the arguments!
11047 Simplified, the example above is just doing this:
11049 @example
11050 changequote(<<, >>)dnl
11051 <<[]>>
11052 changequote([, ])dnl
11053 @end example
11055 @noindent
11056 instead of simply:
11058 @example
11059 [[]]
11060 @end example
11062 With macros that do not double quote their arguments (which is the
11063 rule), double-quote the (risky) literals:
11065 @example
11066 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11067 [[#include <time.h>
11068 #ifndef tzname /* For SGI.  */
11069 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11070 #endif]],
11071                                 [atoi (*tzname);])],
11072                [ac_cv_var_tzname=yes],
11073                [ac_cv_var_tzname=no])
11074 @end example
11076 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11077 should be using @code{AC_LINK_IFELSE} instead.
11079 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11080 where quoting does not suffice.
11082 When you create a @command{configure} script using newly written macros,
11083 examine it carefully to check whether you need to add more quotes in
11084 your macros.  If one or more words have disappeared in the M4
11085 output, you need more quotes.  When in doubt, quote.
11087 However, it's also possible to put on too many layers of quotes.  If
11088 this happens, the resulting @command{configure} script may contain
11089 unexpanded macros.  The @command{autoconf} program checks for this problem
11090 by looking for the string @samp{AC_} in @file{configure}.  However, this
11091 heuristic does not work in general: for example, it does not catch
11092 overquoting in @code{AC_DEFINE} descriptions.
11095 @c ---------------------------------------- Using autom4te
11097 @node Using autom4te
11098 @section Using @command{autom4te}
11100 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11101 to Autoconf per se, heavily rely on M4.  All these different uses
11102 revealed common needs factored into a layer over M4:
11103 @command{autom4te}@footnote{
11105 Yet another great name from Lars J. Aas.
11109 @command{autom4te} is a preprocessor that is like @command{m4}.
11110 It supports M4 extensions designed for use in tools like Autoconf.
11112 @menu
11113 * autom4te Invocation::         A GNU M4 wrapper
11114 * Customizing autom4te::        Customizing the Autoconf package
11115 @end menu
11117 @node autom4te Invocation
11118 @subsection Invoking @command{autom4te}
11120 The command line arguments are modeled after M4's:
11122 @example
11123 autom4te @var{options} @var{files}
11124 @end example
11126 @noindent
11127 @evindex M4
11128 where the @var{files} are directly passed to @command{m4}.  By default,
11129 GNU M4 is found during configuration, but the environment
11130 variable
11131 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11132 to the regular expansion, it handles the replacement of the quadrigraphs
11133 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11134 output.  It supports an extended syntax for the @var{files}:
11136 @table @file
11137 @item @var{file}.m4f
11138 This file is an M4 frozen file.  Note that @emph{all the previous files
11139 are ignored}.  See the option @option{--melt} for the rationale.
11141 @item @var{file}?
11142 If found in the library path, the @var{file} is included for expansion,
11143 otherwise it is ignored instead of triggering a failure.
11144 @end table
11146 @sp 1
11148 Of course, it supports the Autoconf common subset of options:
11150 @table @option
11151 @item --help
11152 @itemx -h
11153 Print a summary of the command line options and exit.
11155 @item --version
11156 @itemx -V
11157 Print the version number of Autoconf and exit.
11159 @item --verbose
11160 @itemx -v
11161 Report processing steps.
11163 @item --debug
11164 @itemx -d
11165 Don't remove the temporary files and be even more verbose.
11167 @item --include=@var{dir}
11168 @itemx -I @var{dir}
11169 Also look for input files in @var{dir}.  Multiple invocations
11170 accumulate.
11172 @item --output=@var{file}
11173 @itemx -o @var{file}
11174 Save output (script or trace) to @var{file}.  The file @option{-} stands
11175 for the standard output.
11176 @end table
11178 @sp 1
11180 As an extension of @command{m4}, it includes the following options:
11182 @table @option
11183 @item --warnings=@var{category}
11184 @itemx -W @var{category}
11185 @evindex WARNINGS
11186 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11187 Report the warnings related to @var{category} (which can actually be a
11188 comma separated list).  @xref{Reporting Messages}, macro
11189 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11190 values include:
11192 @table @samp
11193 @item all
11194 report all the warnings
11196 @item none
11197 report none
11199 @item error
11200 treats warnings as errors
11202 @item no-@var{category}
11203 disable warnings falling into @var{category}
11204 @end table
11206 Warnings about @samp{syntax} are enabled by default, and the environment
11207 variable @env{WARNINGS}, a comma separated list of categories, is
11208 honored.  @samp{autom4te -W @var{category}} actually
11209 behaves as if you had run:
11211 @example
11212 autom4te --warnings=syntax,$WARNINGS,@var{category}
11213 @end example
11215 @noindent
11216 For example, if you want to disable defaults and @env{WARNINGS}
11217 of @command{autom4te}, but enable the warnings about obsolete
11218 constructs, you would use @option{-W none,obsolete}.
11220 @cindex Back trace
11221 @cindex Macro invocation stack
11222 @command{autom4te} displays a back trace for errors, but not for
11223 warnings; if you want them, just pass @option{-W error}.
11225 @item --melt
11226 @itemx -M
11227 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11228 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11229 are executed only when the files are frozen, typically
11230 @code{m4_define}.  For instance, running:
11232 @example
11233 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11234 @end example
11236 @noindent
11237 is roughly equivalent to running:
11239 @example
11240 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11241 @end example
11243 @noindent
11244 while
11246 @example
11247 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11248 @end example
11250 @noindent
11251 is equivalent to:
11253 @example
11254 m4 --reload-state=4.m4f input.m4
11255 @end example
11257 @item --freeze
11258 @itemx -F
11259 Produce a frozen state file.  @command{autom4te} freezing is stricter
11260 than M4's: it must produce no warnings, and no output other than empty
11261 lines (a line with white space is @emph{not} empty) and comments
11262 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11263 this option takes no argument:
11265 @example
11266 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11267 @end example
11269 @noindent
11270 corresponds to
11272 @example
11273 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11274 @end example
11276 @item --mode=@var{octal-mode}
11277 @itemx -m @var{octal-mode}
11278 Set the mode of the non-traces output to @var{octal-mode}; by default
11279 @samp{0666}.
11280 @end table
11282 @sp 1
11284 @cindex @file{autom4te.cache}
11285 As another additional feature over @command{m4}, @command{autom4te}
11286 caches its results.  GNU M4 is able to produce a regular
11287 output and traces at the same time.  Traces are heavily used in the
11288 GNU Build System: @command{autoheader} uses them to build
11289 @file{config.h.in}, @command{autoreconf} to determine what
11290 GNU Build System components are used, @command{automake} to
11291 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11292 traces are cached while performing regular expansion,
11293 and conversely.  This cache is (actually, the caches are) stored in
11294 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11295 at any moment (especially if for some reason @command{autom4te}
11296 considers it trashed).
11298 @table @option
11299 @item --cache=@var{directory}
11300 @itemx -C @var{directory}
11301 Specify the name of the directory where the result should be cached.
11302 Passing an empty value disables caching.  Be sure to pass a relative
11303 file name, as for the time being, global caches are not supported.
11305 @item --no-cache
11306 Don't cache the results.
11308 @item --force
11309 @itemx -f
11310 If a cache is used, consider it obsolete (but update it anyway).
11311 @end table
11313 @sp 1
11315 Because traces are so important to the GNU Build System,
11316 @command{autom4te} provides high level tracing features as compared to
11317 M4, and helps exploiting the cache:
11319 @table @option
11320 @item --trace=@var{macro}[:@var{format}]
11321 @itemx -t @var{macro}[:@var{format}]
11322 Trace the invocations of @var{macro} according to the @var{format}.
11323 Multiple @option{--trace} arguments can be used to list several macros.
11324 Multiple @option{--trace} arguments for a single macro are not
11325 cumulative; instead, you should just make @var{format} as long as
11326 needed.
11328 The @var{format} is a regular string, with newlines if desired, and
11329 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11330 use the following special escapes:
11332 @table @samp
11333 @item $$
11334 @c $$ restore font-lock
11335 The character @samp{$}.
11337 @item $f
11338 The file name from which @var{macro} is called.
11340 @item $l
11341 The line number from which @var{macro} is called.
11343 @item $d
11344 The depth of the @var{macro} call.  This is an M4 technical detail that
11345 you probably don't want to know about.
11347 @item $n
11348 The name of the @var{macro}.
11350 @item $@var{num}
11351 The @var{num}th argument of the call to @var{macro}.
11353 @item $@@
11354 @itemx $@var{sep}@@
11355 @itemx $@{@var{separator}@}@@
11356 All the arguments passed to @var{macro}, separated by the character
11357 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11358 argument is quoted, i.e., enclosed in a pair of square brackets.
11360 @item $*
11361 @itemx $@var{sep}*
11362 @itemx $@{@var{separator}@}*
11363 As above, but the arguments are not quoted.
11365 @item $%
11366 @itemx $@var{sep}%
11367 @itemx $@{@var{separator}@}%
11368 As above, but the arguments are not quoted, all new line characters in
11369 the arguments are smashed, and the default separator is @samp{:}.
11371 The escape @samp{$%} produces single-line trace outputs (unless you put
11372 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11373 not.
11374 @end table
11376 @xref{autoconf Invocation}, for examples of trace uses.
11378 @item --preselect=@var{macro}
11379 @itemx -p @var{macro}
11380 Cache the traces of @var{macro}, but do not enable traces.  This is
11381 especially important to save CPU cycles in the future.  For instance,
11382 when invoked, @command{autoconf} preselects all the macros that
11383 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11384 trace, so that running @command{m4} is not needed to trace them: the
11385 cache suffices.  This results in a huge speed-up.
11386 @end table
11388 @sp 1
11390 @cindex Autom4te Library
11391 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11392 libraries}.  They consists in a powerful yet extremely simple feature:
11393 sets of combined command line arguments:
11395 @table @option
11396 @item --language=@var{language}
11397 @itemx -l @var{language}
11398 Use the @var{language} Autom4te library.  Current languages include:
11400 @table @code
11401 @item M4sugar
11402 create M4sugar output.
11404 @item M4sh
11405 create M4sh executable shell scripts.
11407 @item Autotest
11408 create Autotest executable test suites.
11410 @item Autoconf-without-aclocal-m4
11411 create Autoconf executable configure scripts without
11412 reading @file{aclocal.m4}.
11414 @item Autoconf
11415 create Autoconf executable configure scripts.  This language inherits
11416 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11417 additionally reads @file{aclocal.m4}.
11418 @end table
11420 @item --prepend-include=@var{dir}
11421 @itemx -B @var{dir}
11422 Prepend directory @var{dir} to the search path.  This is used to include
11423 the language-specific files before any third-party macros.
11425 @end table
11427 @cindex @file{autom4te.cfg}
11428 As an example, if Autoconf is installed in its default location,
11429 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11430 strictly equivalent to the command:
11432 @example
11433 autom4te --prepend-include /usr/local/share/autoconf \
11434   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11435 @end example
11437 @noindent
11438 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11439 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11440 foo.m4}, i.e.:
11442 @example
11443 autom4te --prepend-include /usr/local/share/autoconf \
11444   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11445 @end example
11447 @noindent
11448 The definition of the languages is stored in @file{autom4te.cfg}.
11450 @node Customizing autom4te
11451 @subsection Customizing @command{autom4te}
11453 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11454 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11455 as found in the directory from which @command{autom4te} is run).  The
11456 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11457 then @file{./.autom4te.cfg}, and finally the command line arguments.
11459 In these text files, comments are introduced with @code{#}, and empty
11460 lines are ignored.  Customization is performed on a per-language basis,
11461 wrapped in between a @samp{begin-language: "@var{language}"},
11462 @samp{end-language: "@var{language}"} pair.
11464 Customizing a language stands for appending options (@pxref{autom4te
11465 Invocation}) to the current definition of the language.  Options, and
11466 more generally arguments, are introduced by @samp{args:
11467 @var{arguments}}.  You may use the traditional shell syntax to quote the
11468 @var{arguments}.
11470 As an example, to disable Autoconf caches (@file{autom4te.cache})
11471 globally, include the following lines in @file{~/.autom4te.cfg}:
11473 @verbatim
11474 ## ------------------ ##
11475 ## User Preferences.  ##
11476 ## ------------------ ##
11478 begin-language: "Autoconf-without-aclocal-m4"
11479 args: --no-cache
11480 end-language: "Autoconf-without-aclocal-m4"
11481 @end verbatim
11484 @node Programming in M4sugar
11485 @section Programming in M4sugar
11487 @cindex M4sugar
11488 M4 by itself provides only a small, but sufficient, set of all-purpose
11489 macros.  M4sugar introduces additional generic macros.  Its name was
11490 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11491 M4sugar''.
11493 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11494 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11495 define your own macros into these namespaces.
11497 @menu
11498 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11499 * Diagnostic Macros::           Diagnostic messages from M4sugar
11500 * Diversion support::           Diversions in M4sugar
11501 * Conditional constructs::      Conditions in M4
11502 * Looping constructs::          Iteration in M4
11503 * Evaluation Macros::           More quotation and evaluation control
11504 * Text processing Macros::      String manipulation in M4
11505 * Number processing Macros::    Arithmetic computation in M4
11506 * Set manipulation Macros::     Set manipulation in M4
11507 * Forbidden Patterns::          Catching unexpanded macros
11508 @end menu
11510 @node Redefined M4 Macros
11511 @subsection Redefined M4 Macros
11513 @msindex{builtin}
11514 @msindex{changecom}
11515 @msindex{changequote}
11516 @msindex{debugfile}
11517 @msindex{debugmode}
11518 @msindex{decr}
11519 @msindex{define}
11520 @msindex{divnum}
11521 @msindex{errprint}
11522 @msindex{esyscmd}
11523 @msindex{eval}
11524 @msindex{format}
11525 @msindex{ifdef}
11526 @msindex{incr}
11527 @msindex{index}
11528 @msindex{indir}
11529 @msindex{len}
11530 @msindex{pushdef}
11531 @msindex{shift}
11532 @msindex{substr}
11533 @msindex{syscmd}
11534 @msindex{sysval}
11535 @msindex{traceoff}
11536 @msindex{traceon}
11537 @msindex{translit}
11538 With a few exceptions, all the M4 native macros are moved in the
11539 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11540 @code{m4_define} etc.
11542 The list of macros unchanged from M4, except for their name, is:
11543 @itemize @minus
11544 @item m4_builtin
11545 @item m4_changecom
11546 @item m4_changequote
11547 @item m4_debugfile
11548 @item m4_debugmode
11549 @item m4_decr
11550 @item m4_define
11551 @item m4_divnum
11552 @item m4_errprint
11553 @item m4_esyscmd
11554 @item m4_eval
11555 @item m4_format
11556 @item m4_ifdef
11557 @item m4_incr
11558 @item m4_index
11559 @item m4_indir
11560 @item m4_len
11561 @item m4_pushdef
11562 @item m4_shift
11563 @item m4_substr
11564 @item m4_syscmd
11565 @item m4_sysval
11566 @item m4_traceoff
11567 @item m4_traceon
11568 @item m4_translit
11569 @end itemize
11571 Some M4 macros are redefined, and are slightly incompatible with their
11572 native equivalent.
11574 @defmac __file__
11575 @defmacx __line__
11576 @MSindex __file__
11577 @MSindex __line__
11578 All M4 macros starting with @samp{__} retain their original name: for
11579 example, no @code{m4__file__} is defined.
11580 @end defmac
11582 @defmac __oline__
11583 @MSindex __oline__
11584 This is not technically a macro, but a feature of Autom4te.  The
11585 sequence @code{__oline__} can be used similarly to the other m4sugar
11586 location macros, but rather than expanding to the location of the input
11587 file, it is translated to the line number where it appears in the output
11588 file after all other M4 expansions.
11589 @end defmac
11591 @defmac dnl
11592 @MSindex dnl
11593 This macro kept its original name: no @code{m4_dnl} is defined.
11594 @end defmac
11596 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11597 @msindex{bpatsubst}
11598 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11599 is kept for future versions of M4sugar, once GNU M4 2.0 is
11600 released and supports extended regular expression syntax.
11601 @end defmac
11603 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11604 @msindex{bregexp}
11605 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11606 is kept for future versions of M4sugar, once GNU M4 2.0 is
11607 released and supports extended regular expression syntax.
11608 @end defmac
11610 @defmac m4_copy (@var{source}, @var{dest})
11611 @defmacx m4_copy_force (@var{source}, @var{dest})
11612 @defmacx m4_rename (@var{source}, @var{dest})
11613 @defmacx m4_rename_force (@var{source}, @var{dest})
11614 @msindex{copy}
11615 @msindex{copy_force}
11616 @msindex{rename}
11617 @msindex{rename_force}
11618 These macros aren't directly builtins, but are closely related to
11619 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11620 @code{m4_rename} ensure that @var{dest} is undefined, while
11621 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11622 definition.  All four macros then proceed to copy the entire pushdef
11623 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11624 and @code{m4_copy_force} preserve the source (including in the special
11625 case where @var{source} is undefined), while @code{m4_rename} and
11626 @code{m4_rename_force} undefine the original macro name (making it an
11627 error to rename an undefined @var{source}).
11629 Note that attempting to invoke a renamed macro might not work, since the
11630 macro may have a dependence on helper macros accessed via composition of
11631 @samp{$0} but that were not also renamed; likewise, other macros may
11632 have a hard-coded dependence on @var{source} and could break if
11633 @var{source} has been deleted.  On the other hand, it is always safe to
11634 rename a macro to temporarily move it out of the way, then rename it
11635 back later to restore original semantics.
11636 @end defmac
11638 @defmac m4_defn (@var{macro}@dots{})
11639 @msindex{defn}
11640 This macro fails if @var{macro} is not defined, even when using older
11641 versions of M4 that did not warn.  See @code{m4_undefine}.
11642 Unfortunately, in order to support these older versions of M4, there are
11643 some situations involving unbalanced quotes where concatenating multiple
11644 macros together will work in newer M4 but not in m4sugar; use
11645 quadrigraphs to work around this.
11646 @end defmac
11648 @defmac m4_divert (@var{diversion})
11649 @msindex{divert}
11650 M4sugar relies heavily on diversions, so rather than behaving as a
11651 primitive, @code{m4_divert} behaves like:
11652 @example
11653 m4_divert_pop()m4_divert_push([@var{diversion}])
11654 @end example
11655 @noindent
11656 @xref{Diversion support}, for more details about the use of the
11657 diversion stack.  In particular, this implies that @var{diversion}
11658 should be a named diversion rather than a raw number.  But be aware that
11659 it is seldom necessary to explicitly change the diversion stack, and
11660 that when done incorrectly, it can lead to syntactically invalid
11661 scripts.
11662 @end defmac
11664 @defmac m4_dumpdef (@var{name}@dots{})
11665 @defmacx m4_dumpdefs (@var{name}@dots{})
11666 @msindex{dumpdef}
11667 @msindex{dumpdefs}
11668 @code{m4_dumpdef} is like the M4 builtin, except that this version
11669 requires at least one argument, output always goes to standard error
11670 rather than the current debug file, no sorting is done on multiple
11671 arguments, and an error is issued if any
11672 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11673 calls @code{m4_dumpdef} for all of the
11674 @code{m4_pushdef} stack of definitions, starting with the current, and
11675 silently does nothing if @var{name} is undefined.
11677 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11678 builtin is output as the empty string.  This behavior is rectified by
11679 using M4 1.6 or newer.  However, this behavior difference means that
11680 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11681 and never in the final published form of a macro.
11682 @end defmac
11684 @defmac m4_esyscmd_s (@var{command})
11685 @msindex{esyscmd_s}
11686 Like @code{m4_esyscmd}, this macro expands to the result of running
11687 @var{command} in a shell.  The difference is that any trailing newlines
11688 are removed, so that the output behaves more like shell command
11689 substitution.
11690 @end defmac
11692 @defmac m4_exit (@var{exit-status})
11693 @msindex{exit}
11694 This macro corresponds to @code{m4exit}.
11695 @end defmac
11697 @defmac m4_if (@var{comment})
11698 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11699 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11700   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11701 @msindex{if}
11702 This macro corresponds to @code{ifelse}.  @var{string-1} and
11703 @var{string-2} are compared literally, so usually one of the two
11704 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11705 conditional idioms.
11706 @end defmac
11708 @defmac m4_include (@var{file})
11709 @defmacx m4_sinclude (@var{file})
11710 @msindex{include}
11711 @msindex{sinclude}
11712 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11713 @end defmac
11715 @defmac m4_mkstemp (@var{template})
11716 @defmacx m4_maketemp (@var{template})
11717 @msindex{maketemp}
11718 @msindex{mkstemp}
11719 Posix requires @code{maketemp} to replace the trailing @samp{X}
11720 characters in @var{template} with the process id, without regards to the
11721 existence of a file by that name, but this a security hole.  When this
11722 was pointed out to the Posix folks, they agreed to invent a new macro
11723 @code{mkstemp} that always creates a uniquely named file, but not all
11724 versions of GNU M4 support the new macro.  In M4sugar,
11725 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11726 and both have the secure semantics regardless of which macro the
11727 underlying M4 provides.
11728 @end defmac
11730 @defmac m4_popdef (@var{macro}@dots{})
11731 @msindex{popdef}
11732 This macro fails if @var{macro} is not defined, even when using older
11733 versions of M4 that did not warn.  See @code{m4_undefine}.
11734 @end defmac
11736 @defmac m4_undefine (@var{macro}@dots{})
11737 @msindex{undefine}
11738 This macro fails if @var{macro} is not defined, even when using older
11739 versions of M4 that did not warn.  Use
11741 @example
11742 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11743 @end example
11745 @noindent
11746 if you are not sure whether @var{macro} is defined.
11747 @end defmac
11749 @defmac m4_undivert (@var{diversion}@dots{})
11750 @msindex{undivert}
11751 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11752 Also, since the M4sugar diversion stack prefers named
11753 diversions, the use of @code{m4_undivert} to include files is risky.
11754 @xref{Diversion support}, for more details about the use of the
11755 diversion stack.  But be aware that it is seldom necessary to explicitly
11756 change the diversion stack, and that when done incorrectly, it can lead
11757 to syntactically invalid scripts.
11758 @end defmac
11760 @defmac m4_wrap (@var{text})
11761 @defmacx m4_wrap_lifo (@var{text})
11762 @msindex{wrap}
11763 @msindex{wrap_lifo}
11764 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11765 multiple wrap calls to be reprocessed at EOF in the same order
11766 as the original calls (first-in, first-out).  GNU M4 versions
11767 through 1.4.10, however, reprocess them in reverse order (last-in,
11768 first-out).  Both orders are useful, therefore, you can rely on
11769 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11770 LIFO semantics, regardless of the underlying GNU M4 version.
11772 Unlike the GNU M4 builtin, these macros only recognize one
11773 argument, and avoid token pasting between consecutive invocations.  On
11774 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11775 work just as in the builtin.
11776 @end defmac
11779 @node Diagnostic Macros
11780 @subsection Diagnostic messages from M4sugar
11781 @cindex Messages, from @command{M4sugar}
11783 When macros statically diagnose abnormal situations, benign or fatal,
11784 they should report them using these macros.  For issuing dynamic issues,
11785 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11787 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11788 @msindex{assert}
11789 Assert that the arithmetic @var{expression} evaluates to non-zero.
11790 Otherwise, issue a fatal error, and exit @command{autom4te} with
11791 @var{exit-status}.
11792 @end defmac
11794 @defmac m4_errprintn (@var{message})
11795 @msindex{errprintn}
11796 Similar to the builtin @code{m4_errprint}, except that a newline is
11797 guaranteed after @var{message}.
11798 @end defmac
11800 @anchor{m4_fatal}
11801 @defmac m4_fatal (@var{message})
11802 @msindex{fatal}
11803 Report a severe error @var{message} prefixed with the current location,
11804 and have @command{autom4te} die.
11805 @end defmac
11807 @defmac m4_location
11808 @msindex{location}
11809 Useful as a prefix in a message line.  Short for:
11810 @example
11811 __file__:__line__
11812 @end example
11813 @end defmac
11815 @anchor{m4_warn}
11816 @defmac m4_warn (@var{category}, @var{message})
11817 @msindex{warn}
11818 Report @var{message} as a warning (or as an error if requested by the
11819 user) if warnings of the @var{category} are turned on.  If the message
11820 is emitted, it is prefixed with the current location, and followed by a
11821 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11822 current expansion.  You are encouraged to use standard categories, which
11823 currently include:
11825 @table @samp
11826 @item all
11827 messages that don't fall into one of the following categories.  Use of an
11828 empty @var{category} is equivalent.
11830 @item cross
11831 related to cross compilation issues.
11833 @item obsolete
11834 use of an obsolete construct.
11836 @item syntax
11837 dubious syntactic constructs, incorrectly ordered macro calls.
11838 @end table
11839 @end defmac
11842 @node Diversion support
11843 @subsection Diversion support
11845 M4sugar makes heavy use of diversions under the hood, because it is
11846 often the case that
11847 text that must appear early in the output is not discovered until late
11848 in the input.  Additionally, some of the topological sorting algorithms
11849 used in resolving macro dependencies use diversions.  However, most
11850 macros should not need to change diversions directly, but rather rely on
11851 higher-level M4sugar macros to manage diversions transparently.  If you
11852 change diversions improperly, you risk generating a syntactically
11853 invalid script, because an incorrect diversion will violate assumptions
11854 made by many macros about whether prerequisite text has been previously
11855 output.  In short, if you manually change the diversion, you should not
11856 expect any macros provided by the Autoconf package to work until you
11857 have restored the diversion stack back to its original state.
11859 In the rare case that it is necessary to write a macro that explicitly
11860 outputs text to a different diversion, it is important to be aware of an
11861 M4 limitation regarding diversions: text only goes to a diversion if it
11862 is not part of argument collection.  Therefore, any macro that changes
11863 the current diversion cannot be used as an unquoted argument to another
11864 macro, but must be expanded at the top level.  The macro
11865 @code{m4_expand} will diagnose any attempt to change diversions, since
11866 it is generally useful only as an argument to another macro.  The
11867 following example shows what happens when diversion manipulation is
11868 attempted within macro arguments:
11870 @example
11871 m4_do([normal text]
11872 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11873 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11874 @result{}normal text
11875 @result{}unwanted
11876 @end example
11878 @noindent
11879 Notice that the unquoted text @code{unwanted} is output, even though it
11880 was processed while the current diversion was @code{KILL}, because it
11881 was collected as part of the argument to @code{m4_do}.  However, the
11882 text @code{discarded} disappeared as desired, because the diversion
11883 changes were single-quoted, and were not expanded until the top-level
11884 rescan of the output of @code{m4_do}.
11886 To make diversion management easier, M4sugar uses the concept of named
11887 diversions.  Rather than using diversion numbers directly, it is nicer
11888 to associate a name with each diversion.  The diversion number associated
11889 with a particular diversion name is an implementation detail, and a
11890 syntax warning is issued if a diversion number is used instead of a
11891 name.  In general, you should not output text
11892 to a named diversion until after calling the appropriate initialization
11893 routine for your language (@code{m4_init}, @code{AS_INIT},
11894 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11895 below.
11897 M4sugar defines two named diversions.
11898 @table @code
11899 @item KILL
11900 Text written to this diversion is discarded.  This is the default
11901 diversion once M4sugar is initialized.
11902 @item GROW
11903 This diversion is used behind the scenes by topological sorting macros,
11904 such as @code{AC_REQUIRE}.
11905 @end table
11907 M4sh adds several more named diversions.
11908 @table @code
11909 @item BINSH
11910 This diversion is reserved for the @samp{#!} interpreter line.
11911 @item HEADER-REVISION
11912 This diversion holds text from @code{AC_REVISION}.
11913 @item HEADER-COMMENT
11914 This diversion holds comments about the purpose of a file.
11915 @item HEADER-COPYRIGHT
11916 This diversion is managed by @code{AC_COPYRIGHT}.
11917 @item M4SH-SANITIZE
11918 This diversion contains M4sh sanitization code, used to ensure M4sh is
11919 executing in a reasonable shell environment.
11920 @item M4SH-INIT
11921 This diversion contains M4sh initialization code, initializing variables
11922 that are required by other M4sh macros.
11923 @item BODY
11924 This diversion contains the body of the shell code, and is the default
11925 diversion once M4sh is initialized.
11926 @end table
11928 Autotest inherits diversions from M4sh, and changes the default
11929 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11930 more named diversions, with the following subset designed for developer
11931 use.
11932 @table @code
11933 @item PREPARE_TESTS
11934 This diversion contains initialization sequences which are executed
11935 after @file{atconfig} and @file{atlocal}, and after all command line
11936 arguments have been parsed, but prior to running any tests.  It can be
11937 used to set up state that is required across all tests.  This diversion
11938 will work even before @code{AT_INIT}.
11939 @end table
11941 Autoconf inherits diversions from M4sh, and adds the following named
11942 diversions which developers can utilize.
11943 @table @code
11944 @item DEFAULTS
11945 This diversion contains shell variable assignments to set defaults that
11946 must be in place before arguments are parsed.  This diversion is placed
11947 early enough in @file{configure} that it is unsafe to expand any
11948 autoconf macros into this diversion.
11949 @item HELP_ENABLE
11950 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11951 diversion will be included as part of a quoted here-doc providing all of
11952 the @option{--help} output of @file{configure} related to options
11953 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11954 @item INIT_PREPARE
11955 This diversion occurs after all command line options have been parsed,
11956 but prior to the main body of the @file{configure} script.  This
11957 diversion is the last chance to insert shell code such as variable
11958 assignments or shell function declarations that will used by the
11959 expansion of other macros.
11960 @end table
11962 For now, the remaining named diversions of Autoconf, Autoheader, and
11963 Autotest are not documented.  In other words,
11964 intentionally outputting text into an undocumented diversion is subject
11965 to breakage in a future release of Autoconf.
11967 @defmac m4_cleardivert (@var{diversion}@dots{})
11968 @msindex{cleardivert}
11969 Permanently discard any text that has been diverted into
11970 @var{diversion}.
11971 @end defmac
11973 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11974 @msindex{divert_once}
11975 Similar to @code{m4_divert_text}, except that @var{content} is only
11976 output to @var{diversion} if this is the first time that
11977 @code{m4_divert_once} has been called with its particular arguments.
11978 @end defmac
11980 @defmac m4_divert_pop (@ovar{diversion})
11981 @msindex{divert_pop}
11982 If provided, check that the current diversion is indeed @var{diversion}.
11983 Then change to the diversion located earlier on the stack, giving an
11984 error if an attempt is made to pop beyond the initial m4sugar diversion
11985 of @code{KILL}.
11986 @end defmac
11988 @defmac m4_divert_push (@var{diversion})
11989 @msindex{divert_push}
11990 Remember the former diversion on the diversion stack, and output
11991 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11992 stack, and issues an error if there is not a matching pop for every
11993 push.
11994 @end defmac
11996 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11997 @msindex{divert_text}
11998 Output @var{content} and a newline into @var{diversion}, without
11999 affecting the current diversion.  Shorthand for:
12000 @example
12001 m4_divert_push([@var{diversion}])@var{content}
12002 m4_divert_pop([@var{diversion}])dnl
12003 @end example
12005 One use of @code{m4_divert_text} is to develop two related macros, where
12006 macro @samp{MY_A} does the work, but adjusts what work is performed
12007 based on whether the optional macro @samp{MY_B} has also been expanded.
12008 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12009 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12010 imposes an ordering restriction on the user; it would be nicer if macros
12011 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12012 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12013 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12014 expanded.
12016 @example
12017 AC_DEFUN([MY_A],
12018 [# various actions
12019 if test -n "$b_was_used"; then
12020   # extra action
12021 fi])
12022 AC_DEFUN([MY_B],
12023 [AC_REQUIRE([MY_A])dnl
12024 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12025 @end example
12027 @end defmac
12029 @defmac m4_init
12030 @msindex{init}
12031 Initialize the M4sugar environment, setting up the default named
12032 diversion to be @code{KILL}.
12033 @end defmac
12035 @node Conditional constructs
12036 @subsection Conditional constructs
12038 The following macros provide additional conditional constructs as
12039 convenience wrappers around @code{m4_if}.
12041 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12042   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12043 @msindex{bmatch}
12044 The string @var{string} is repeatedly compared against a series of
12045 @var{regex} arguments; if a match is found, the expansion is the
12046 corresponding @var{value}, otherwise, the macro moves on to the next
12047 @var{regex}.  If no @var{regex} match, then the result is the optional
12048 @var{default}, or nothing.
12049 @end defmac
12051 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12052   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12053 @msindex{bpatsubsts}
12054 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12055 as if by:
12056 @example
12057 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12058 @end example
12060 @noindent
12061 The result of the substitution is then passed through the next set of
12062 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12063 deletion of any matched portions in the current string.  Note that this
12064 macro over-quotes @var{string}; this behavior is intentional, so that
12065 the result of each step of the recursion remains as a quoted string.
12066 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12067 will line up with the extra quotations, and not the characters of the
12068 original string.  The overquoting is removed after the final
12069 substitution.
12070 @end defmac
12072 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12073   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12074 @msindex{case}
12075 Test @var{string} against multiple @var{value} possibilities, resulting
12076 in the first @var{if-value} for a match, or in the optional
12077 @var{default}.  This is shorthand for:
12078 @example
12079 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12080       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12081       [@var{default}])
12082 @end example
12083 @end defmac
12085 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12086   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12087 @msindex{cond}
12088 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12089 except that each @var{test} is expanded only when it is encountered.
12090 This is useful for short-circuiting expensive tests; while @code{m4_if}
12091 requires all its strings to be expanded up front before doing
12092 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12093 tests have failed.
12095 For an example, these two sequences give the same result, but in the
12096 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12097 version only expands @code{m4_index} once, instead of five times, for
12098 faster computation if this is a common case for @samp{$1}.  Notice that
12099 every third argument is unquoted for @code{m4_if}, and quoted for
12100 @code{m4_cond}:
12102 @example
12103 m4_if(m4_index([$1], [\]), [-1], [$2],
12104       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12105       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12106       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12107       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12108       [$2])
12109 m4_cond([m4_index([$1], [\])], [-1], [$2],
12110         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12111         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12112         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12113         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12114         [$2])
12115 @end example
12116 @end defmac
12118 @defmac m4_default (@var{expr-1}, @var{expr-2})
12119 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12120 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12121 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12122 @msindex{default}
12123 @msindex{default_quoted}
12124 @msindex{default_nblank}
12125 @msindex{default_nblank_quoted}
12126 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12127 @code{m4_default} expands the result, while @code{m4_default_quoted}
12128 does not.  Useful for providing a fixed default if the expression that
12129 results in @var{expr-1} would otherwise be empty.  The difference
12130 between @code{m4_default} and @code{m4_default_nblank} is whether an
12131 argument consisting of just blanks (space, tab, newline) is
12132 significant.  When using the expanding versions, note that an argument
12133 may contain text but still expand to an empty string.
12135 @example
12136 m4_define([active], [ACTIVE])dnl
12137 m4_define([empty], [])dnl
12138 m4_define([demo1], [m4_default([$1], [$2])])dnl
12139 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12140 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12141 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12142 demo1([active], [default])
12143 @result{}ACTIVE
12144 demo1([], [active])
12145 @result{}ACTIVE
12146 demo1([empty], [text])
12147 @result{}
12148 -demo1([ ], [active])-
12149 @result{}- -
12150 demo2([active], [default])
12151 @result{}active
12152 demo2([], [active])
12153 @result{}active
12154 demo2([empty], [text])
12155 @result{}empty
12156 -demo2([ ], [active])-
12157 @result{}- -
12158 demo3([active], [default])
12159 @result{}ACTIVE
12160 demo3([], [active])
12161 @result{}ACTIVE
12162 demo3([empty], [text])
12163 @result{}
12164 -demo3([ ], [active])-
12165 @result{}-ACTIVE-
12166 demo4([active], [default])
12167 @result{}active
12168 demo4([], [active])
12169 @result{}active
12170 demo4([empty], [text])
12171 @result{}empty
12172 -demo4([ ], [active])-
12173 @result{}-active-
12174 @end example
12175 @end defmac
12177 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12178 @msindex{define_default}
12179 If @var{macro} does not already have a definition, then define it to
12180 @var{default-definition}.
12181 @end defmac
12183 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12184 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12185 @msindex{ifblank}
12186 @msindex{ifnblank}
12187 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12188 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12189 variants exist, in order to make it easier to select the correct logical
12190 sense when using only two parameters.  Note that this is more efficient
12191 than the equivalent behavior of:
12192 @example
12193 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12194 @end example
12195 @end defmac
12197 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12198 @msindex{ifndef}
12199 This is shorthand for:
12200 @example
12201 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12202 @end example
12203 @end defmac
12205 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12206 @msindex{ifset}
12207 If @var{macro} is undefined, or is defined as the empty string, expand
12208 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12209 @example
12210 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12211 @end example
12212 @noindent
12213 except that it is not an error if @var{macro} is undefined.
12214 @end defmac
12216 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12217 @msindex{ifval}
12218 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12219 @var{if-false}.  This is shorthand for:
12220 @example
12221 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12222 @end example
12223 @end defmac
12225 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12226 @msindex{ifvaln}
12227 Similar to @code{m4_ifval}, except guarantee that a newline is present
12228 after any non-empty expansion.  Often followed by @code{dnl}.
12229 @end defmac
12231 @defmac m4_n (@var{text})
12232 @msindex{n}
12233 Expand to @var{text}, and add a newline if @var{text} is not empty.
12234 Often followed by @code{dnl}.
12235 @end defmac
12238 @node Looping constructs
12239 @subsection Looping constructs
12241 The following macros are useful in implementing recursive algorithms in
12242 M4, including loop operations.  An M4 list is formed by quoting a list
12243 of quoted elements; generally the lists are comma-separated, although
12244 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12245 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12246 It is common to see lists with unquoted elements when those elements are
12247 not likely to be macro names, as in @samp{[fputc_unlocked,
12248 fgetc_unlocked]}.
12250 Although not generally recommended, it is possible for quoted lists to
12251 have side effects; all side effects are expanded only once, and prior to
12252 visiting any list element.  On the other hand, the fact that unquoted
12253 macros are expanded exactly once means that macros without side effects
12254 can be used to generate lists.  For example,
12256 @example
12257 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12258 @error{}hi
12259 @result{}123
12260 m4_define([list], [[1], [2], [3]])
12261 @result{}
12262 m4_foreach([i], [list], [i])
12263 @result{}123
12264 @end example
12266 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12267 @msindex{argn}
12268 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12269 If there are too few arguments, the empty string is used.  For any
12270 @var{n} besides 1, this is more efficient than the similar
12271 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12272 @end defmac
12274 @defmac m4_car (@var{arg}@dots{})
12275 @msindex{car}
12276 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12277 to recursively iterate
12278 through a list.  Generally, when using quoted lists of quoted elements,
12279 @code{m4_car} should be called without any extra quotes.
12280 @end defmac
12282 @defmac m4_cdr (@var{arg}@dots{})
12283 @msindex{cdr}
12284 Expands to a quoted list of all but the first @var{arg}, or the empty
12285 string if there was only one argument.  Generally, when using quoted
12286 lists of quoted elements, @code{m4_cdr} should be called without any
12287 extra quotes.
12289 For example, this is a simple implementation of @code{m4_map}; note how
12290 each iteration checks for the end of recursion, then merely applies the
12291 first argument to the first element of the list, then repeats with the
12292 rest of the list.  (The actual implementation in M4sugar is a bit more
12293 involved, to gain some speed and share code with @code{m4_map_sep}, and
12294 also to avoid expanding side effects in @samp{$2} twice).
12295 @example
12296 m4_define([m4_map], [m4_ifval([$2],
12297   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12298 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12299 @result{} 1 2 a
12300 @end example
12301 @end defmac
12303 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12304   @var{expression})
12305 @msindex{for}
12306 Loop over the numeric values between @var{first} and @var{last}
12307 including bounds by increments of @var{step}.  For each iteration,
12308 expand @var{expression} with the numeric value assigned to @var{var}.
12309 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12310 on the order of the limits.  If given, @var{step} has to match this
12311 order.  The number of iterations is determined independently from
12312 definition of @var{var}; iteration cannot be short-circuited or
12313 lengthened by modifying @var{var} from within @var{expression}.
12314 @end defmac
12316 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12317 @msindex{foreach}
12318 Loop over the comma-separated M4 list @var{list}, assigning each value
12319 to @var{var}, and expand @var{expression}.  The following example
12320 outputs two lines:
12322 @example
12323 m4_foreach([myvar], [[foo], [bar, baz]],
12324            [echo myvar
12325 ])dnl
12326 @result{}echo foo
12327 @result{}echo bar, baz
12328 @end example
12330 Note that for some forms of @var{expression}, it may be faster to use
12331 @code{m4_map_args}.
12332 @end defmac
12334 @anchor{m4_foreach_w}
12335 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12336 @msindex{foreach_w}
12337 Loop over the white-space-separated list @var{list}, assigning each value
12338 to @var{var}, and expand @var{expression}.  If @var{var} is only
12339 referenced once in @var{expression}, it is more efficient to use
12340 @code{m4_map_args_w}.
12342 The deprecated macro @code{AC_FOREACH} is an alias of
12343 @code{m4_foreach_w}.
12344 @end defmac
12346 @defmac m4_map (@var{macro}, @var{list})
12347 @defmacx m4_mapall (@var{macro}, @var{list})
12348 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12349 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12350 @msindex{map}
12351 @msindex{mapall}
12352 @msindex{map_sep}
12353 @msindex{mapall_sep}
12354 Loop over the comma separated quoted list of argument descriptions in
12355 @var{list}, and invoke @var{macro} with the arguments.  An argument
12356 description is in turn a comma-separated quoted list of quoted elements,
12357 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12358 @code{m4_map_sep} ignore empty argument descriptions, while
12359 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12360 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12361 additionally expand @var{separator} between invocations of @var{macro}.
12363 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12364 separating output with commas, this means that the map result can be
12365 used as a series of arguments, by using a single-quoted comma as
12366 @var{separator}, or as a single string, by using a double-quoted comma.
12368 @example
12369 m4_map([m4_count], [])
12370 @result{}
12371 m4_map([ m4_count], [[],
12372                      [[1]],
12373                      [[1], [2]]])
12374 @result{} 1 2
12375 m4_mapall([ m4_count], [[],
12376                         [[1]],
12377                         [[1], [2]]])
12378 @result{} 0 1 2
12379 m4_map_sep([m4_eval], [,], [[[1+2]],
12380                             [[10], [16]]])
12381 @result{}3,a
12382 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12383 @result{}a,b
12384 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12385 @result{}2
12386 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12387 @result{}a,b
12388 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12389 @result{}1
12390 @end example
12391 @end defmac
12393 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12394 @msindex{map_args}
12395 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12396 argument.  In the following example, three solutions are presented with
12397 the same expansion; the solution using @code{m4_map_args} is the most
12398 efficient.
12399 @example
12400 m4_define([active], [ACTIVE])dnl
12401 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12402 @result{} plain active
12403 m4_map([ m4_echo], [[[plain]], [[active]]])
12404 @result{} plain active
12405 m4_map_args([ m4_echo], [plain], [active])
12406 @result{} plain active
12407 @end example
12409 In cases where it is useful to operate on additional parameters besides
12410 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12411 to supply the argument currying necessary to generate the desired
12412 argument list.  In the following example, @code{list_add_n} is more
12413 efficient than @code{list_add_x}.  On the other hand, using
12414 @code{m4_map_args_sep} can be even more efficient.
12416 @example
12417 m4_define([list], [[1], [2], [3]])dnl
12418 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12419 dnl list_add_n(N, ARG...)
12420 dnl Output a list consisting of each ARG added to N
12421 m4_define([list_add_n],
12422 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12423 list_add_n([1], list)
12424 @result{}2,3,4
12425 list_add_n([2], list)
12426 @result{}3,4,5
12427 m4_define([list_add_x],
12428 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12429   [,add([$1],m4_defn([var]))]))])dnl
12430 list_add_x([1], list)
12431 @result{}2,3,4
12432 @end example
12433 @end defmac
12435 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
12436   @var{arg}@dots{})
12437 @msindex{map_args_pair}
12438 For every pair of arguments @var{arg}, invoke @var{macro} with two
12439 arguments.  If there is an odd number of arguments, invoke
12440 @var{macro-end}, which defaults to @var{macro}, with the remaining
12441 argument.
12443 @example
12444 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12445 @result{}, 2, 1, 3
12446 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12447 @result{}, 2, 1, [3]
12448 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12449 @result{}, 2, 1, 4, 3
12450 @end example
12451 @end defmac
12453 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12454 @msindex{map_args_sep}
12455 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12456 argument, additionally expanding @var{sep} between arguments.  One
12457 common use of this macro is constructing a macro call, where the opening
12458 and closing parentheses are split between @var{pre} and @var{post}; in
12459 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12460 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12461 macro provides the most efficient means for iterating over an arbitrary
12462 list of arguments, particularly when repeatedly constructing a macro
12463 call with more arguments than @var{arg}.
12464 @end defmac
12466 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12467 @msindex{map_args_w}
12468 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12469 the whitespace-separated @var{string}, additionally expanding @var{sep}
12470 between words.  This macro provides the most efficient means for
12471 iterating over a whitespace-separated string.  In particular,
12472 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12473 efficient than @code{m4_foreach_w([var], [@var{string}],
12474 [@var{action}(m4_defn([var]))])}.
12475 @end defmac
12477 @defmac m4_shiftn (@var{count}, @dots{})
12478 @defmacx m4_shift2 (@dots{})
12479 @defmacx m4_shift3 (@dots{})
12480 @msindex{shift2}
12481 @msindex{shift3}
12482 @msindex{shiftn}
12483 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12484 along with validation that enough arguments were passed in to match the
12485 shift count, and that the count is positive.  @code{m4_shift2} and
12486 @code{m4_shift3} are specializations
12487 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12488 for two and three shifts, respectively.
12489 @end defmac
12491 @defmac m4_stack_foreach (@var{macro}, @var{action})
12492 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12493 @msindex{stack_foreach}
12494 @msindex{stack_foreach_lifo}
12495 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12496 @var{action} with the single argument of a definition of @var{macro}.
12497 @code{m4_stack_foreach} starts with the oldest definition, while
12498 @code{m4_stack_foreach_lifo} starts with the current definition.
12499 @var{action} should not push or pop definitions of @var{macro}, nor is
12500 there any guarantee that the current definition of @var{macro} matches
12501 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12502 can be used if @var{action} needs more than one argument, although in
12503 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12505 Due to technical limitations, there are a few low-level m4sugar
12506 functions, such as @code{m4_pushdef}, that cannot be used as the
12507 @var{macro} argument.
12509 @example
12510 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12511 m4_stack_foreach([a], [ m4_incr])
12512 @result{} 2 3
12513 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12514 @result{} cd bcd
12515 @end example
12516 @end defmac
12518 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12519 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12520   @ovar{sep})
12521 @msindex{stack_foreach_sep}
12522 @msindex{stack_foreach_sep_lifo}
12523 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12524 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12525 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12526 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12527 the current definition first.  This macro provides the most efficient
12528 means for iterating over a pushdef stack.  In particular,
12529 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12530 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12531 @end defmac
12533 @node Evaluation Macros
12534 @subsection Evaluation Macros
12536 The following macros give some control over the order of the evaluation
12537 by adding or removing levels of quotes.
12539 @defmac m4_apply (@var{macro}, @var{list})
12540 @msindex{apply}
12541 Apply the elements of the quoted, comma-separated @var{list} as the
12542 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12543 without arguments.  Note the difference between @code{m4_indir}, which
12544 expects its first argument to be a macro name but can use names that are
12545 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12546 other text, but must end in a valid macro name.
12547 @example
12548 m4_apply([m4_count], [])
12549 @result{}0
12550 m4_apply([m4_count], [[]])
12551 @result{}1
12552 m4_apply([m4_count], [[1], [2]])
12553 @result{}2
12554 m4_apply([m4_join], [[|], [1], [2]])
12555 @result{}1|2
12556 @end example
12557 @end defmac
12559 @defmac m4_count (@var{arg}, @dots{})
12560 @msindex{count}
12561 This macro returns the decimal count of the number of arguments it was
12562 passed.
12563 @end defmac
12565 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12566 @msindex{curry}
12567 This macro performs argument currying.  The expansion of this macro is
12568 another macro name that expects exactly one argument; that argument is
12569 then appended to the @var{arg} list, and then @var{macro} is expanded
12570 with the resulting argument list.
12572 @example
12573 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12574 @result{}3, 2, 1
12575 @end example
12577 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12578 pass the definition of a builtin macro as the argument to the output of
12579 @code{m4_curry}; the empty string is used instead of the builtin token.
12580 This behavior is rectified by using M4 1.6 or newer.
12581 @end defmac
12583 @defmac m4_do (@var{arg}, @dots{})
12584 @msindex{do}
12585 This macro loops over its arguments and expands each @var{arg} in
12586 sequence.  Its main use is for readability; it allows the use of
12587 indentation and fewer @code{dnl} to result in the same expansion.  This
12588 macro guarantees that no expansion will be concatenated with subsequent
12589 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12590 @var{arg@dots{}}))}.
12592 @example
12593 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12594 m4_do([a],[b])c
12595 @result{}abc
12596 m4_unquote(m4_join([],[a],[b]))c
12597 @result{}3
12598 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12599 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12600 m4_do([a],[b])c
12601 @result{}ABC
12602 m4_unquote(m4_join([],[a],[b]))c
12603 @result{}3
12604 @end example
12605 @end defmac
12607 @defmac m4_dquote (@var{arg}, @dots{})
12608 @msindex{dquote}
12609 Return the arguments as a quoted list of quoted arguments.
12610 Conveniently, if there is just one @var{arg}, this effectively adds a
12611 level of quoting.
12612 @end defmac
12614 @defmac m4_dquote_elt (@var{arg}, @dots{})
12615 @msindex{dquote_elt}
12616 Return the arguments as a series of double-quoted arguments.  Whereas
12617 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12618 as many arguments as it was passed.
12619 @end defmac
12621 @defmac m4_echo (@var{arg}, @dots{})
12622 @msindex{echo}
12623 Return the arguments, with the same level of quoting.  Other than
12624 discarding whitespace after unquoted commas, this macro is a no-op.
12625 @end defmac
12627 @defmac m4_expand (@var{arg})
12628 @msindex{expand}
12629 Return the expansion of @var{arg} as a quoted string.  Whereas
12630 @code{m4_quote} is designed to collect expanded text into a single
12631 argument, @code{m4_expand} is designed to perform one level of expansion
12632 on quoted text.  One distinction is in the treatment of whitespace
12633 following a comma in the original @var{arg}.  Any time multiple
12634 arguments are collected into one with @code{m4_quote}, the M4 argument
12635 collection rules discard the whitespace.  However, with @code{m4_expand},
12636 whitespace is preserved, even after the expansion of macros contained in
12637 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12638 would involve an unterminated comment, whereas expanding that same text
12639 as the argument to @code{m4_quote} runs into difficulty in finding the
12640 end of the argument.  Since manipulating diversions during argument
12641 collection is inherently unsafe, @code{m4_expand} issues an error if
12642 @var{arg} attempts to change the current diversion (@pxref{Diversion
12643 support}).
12645 @example
12646 m4_define([active], [ACT, IVE])dnl
12647 m4_define([active2], [[ACT, IVE]])dnl
12648 m4_quote(active, active)
12649 @result{}ACT,IVE,ACT,IVE
12650 m4_expand([active, active])
12651 @result{}ACT, IVE, ACT, IVE
12652 m4_quote(active2, active2)
12653 @result{}ACT, IVE,ACT, IVE
12654 m4_expand([active2, active2])
12655 @result{}ACT, IVE, ACT, IVE
12656 m4_expand([# m4_echo])
12657 @result{}# m4_echo
12658 m4_quote(# m4_echo)
12660 @result{}# m4_echo)
12661 @result{}
12662 @end example
12664 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12665 literal unbalanced quotes, but that quadrigraphs can be used when
12666 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12667 be supplied with double quoting or a quadrigraph.
12669 @example
12670 m4_define([pattern], [[!@@<:@@]])dnl
12671 m4_define([bar], [BAR])dnl
12672 m4_expand([case $foo in
12673   m4_defn([pattern])@@:@}@@ bar ;;
12674   *[)] blah ;;
12675 esac])
12676 @result{}case $foo in
12677 @result{}  [![]) BAR ;;
12678 @result{}  *) blah ;;
12679 @result{}esac
12680 @end example
12681 @end defmac
12683 @defmac m4_ignore (@dots{})
12684 @msindex{ignore}
12685 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12686 ignoring all of its arguments.  By itself, this isn't very useful.
12687 However, it can be used to conditionally ignore an arbitrary number of
12688 arguments, by deciding which macro name to apply to a list of arguments.
12689 @example
12690 dnl foo outputs a message only if [debug] is defined.
12691 m4_define([foo],
12692 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12693 @end example
12695 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12696 serve the same purpose, although it is less readable.
12697 @end defmac
12699 @defmac m4_make_list (@var{arg}, @dots{})
12700 @msindex{make_list}
12701 This macro exists to aid debugging of M4sugar algorithms.  Its net
12702 effect is similar to @code{m4_dquote}---it produces a quoted list of
12703 quoted arguments, for each @var{arg}.  The difference is that this
12704 version uses a comma-newline separator instead of just comma, to improve
12705 readability of the list; with the result that it is less efficient than
12706 @code{m4_dquote}.
12707 @example
12708 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12709 m4_dquote(zero, [one], [[two]])
12710 @result{}[0],[one],[[two]]
12711 m4_make_list(zero, [one], [[two]])
12712 @result{}[0],
12713 @result{}[one],
12714 @result{}[[two]]
12715 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12716 @result{} 0 1 two
12717 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12718 @result{} 0 1 two
12719 @end example
12720 @end defmac
12722 @c m4_noquote is too dangerous to document - it invokes macros that
12723 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12724 @c user should generally prefer m4_unquote instead.
12726 @defmac m4_quote (@var{arg}, @dots{})
12727 @msindex{quote}
12728 Return the arguments as a single entity, i.e., wrap them into a pair of
12729 quotes.  This effectively collapses multiple arguments into one,
12730 although it loses whitespace after unquoted commas in the process.
12731 @end defmac
12733 @defmac m4_reverse (@var{arg}, @dots{})
12734 @msindex{reverse}
12735 Outputs each argument with the same level of quoting, but in reverse
12736 order, and with space following each comma for readability.
12738 @example
12739 m4_define([active], [ACT,IVE])
12740 @result{}
12741 m4_reverse(active, [active])
12742 @result{}active, IVE, ACT
12743 @end example
12744 @end defmac
12746 @defmac m4_unquote (@var{arg}, @dots{})
12747 @msindex{unquote}
12748 This macro was introduced in Autoconf 2.62.  Expand each argument,
12749 separated by commas.  For a single @var{arg}, this effectively removes a
12750 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12751 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12752 this results in an unquoted list of expansions.  This is commonly used
12753 with @code{m4_split}, in order to convert a single quoted list into a
12754 series of quoted elements.
12755 @end defmac
12757 The following example aims at emphasizing the difference between several
12758 scenarios: not using these macros, using @code{m4_defn}, using
12759 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12761 @example
12762 $ @kbd{cat example.m4}
12763 dnl Overquote, so that quotes are visible.
12764 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12765 m4_define([a], [A])
12766 m4_define([mkargs], [1, 2[,] 3])
12767 m4_define([arg1], [[$1]])
12768 m4_divert([0])dnl
12769 show(a, b)
12770 show([a, b])
12771 show(m4_quote(a, b))
12772 show(m4_dquote(a, b))
12773 show(m4_expand([a, b]))
12775 arg1(mkargs)
12776 arg1([mkargs])
12777 arg1(m4_defn([mkargs]))
12778 arg1(m4_quote(mkargs))
12779 arg1(m4_dquote(mkargs))
12780 arg1(m4_expand([mkargs]))
12781 $ @kbd{autom4te -l m4sugar example.m4}
12782 $1 = A, $@@ = [A],[b]
12783 $1 = a, b, $@@ = [a, b]
12784 $1 = A,b, $@@ = [A,b]
12785 $1 = [A],[b], $@@ = [[A],[b]]
12786 $1 = A, b, $@@ = [A, b]
12789 mkargs
12790 1, 2[,] 3
12791 1,2, 3
12792 [1],[2, 3]
12793 1, 2, 3
12794 @end example
12797 @node Text processing Macros
12798 @subsection String manipulation in M4
12800 The following macros may be used to manipulate strings in M4.  Many of
12801 the macros in this section intentionally result in quoted strings as
12802 output, rather than subjecting the arguments to further expansions.  As
12803 a result, if you are manipulating text that contains active M4
12804 characters, the arguments are passed with single quoting rather than
12805 double.
12807 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12808 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12809   @ovar{if-uniq}, @ovar{if-duplicate})
12810 @msindex{append}
12811 @msindex{append_uniq}
12812 Redefine @var{macro-name} to its former contents with @var{separator}
12813 and @var{string} added at the end.  If @var{macro-name} was undefined
12814 before (but not if it was defined but empty), then no @var{separator} is
12815 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12816 are expanded during this macro; instead, they are expanded when
12817 @var{macro-name} is invoked.
12819 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12820 to grow strings without duplicating substrings.  Additionally,
12821 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12822 @var{if-uniq} is expanded if @var{string} was appended, and
12823 @var{if-duplicate} is expanded if @var{string} was already present.
12824 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12825 occurs within @var{string}, since that can lead to duplicates.
12827 Note that @code{m4_append} can scale linearly in the length of the final
12828 string, depending on the quality of the underlying M4 implementation,
12829 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12830 If an algorithm can tolerate duplicates in the final string, use the
12831 former for speed.  If duplicates must be avoided, consider using
12832 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12834 @example
12835 m4_define([active], [ACTIVE])dnl
12836 m4_append([sentence], [This is an])dnl
12837 m4_append([sentence], [ active ])dnl
12838 m4_append([sentence], [symbol.])dnl
12839 sentence
12840 @result{}This is an ACTIVE symbol.
12841 m4_undefine([active])dnl
12842 @result{}This is an active symbol.
12843 m4_append_uniq([list], [one], [, ], [new], [existing])
12844 @result{}new
12845 m4_append_uniq([list], [one], [, ], [new], [existing])
12846 @result{}existing
12847 m4_append_uniq([list], [two], [, ], [new], [existing])
12848 @result{}new
12849 m4_append_uniq([list], [three], [, ], [new], [existing])
12850 @result{}new
12851 m4_append_uniq([list], [two], [, ], [new], [existing])
12852 @result{}existing
12853 list
12854 @result{}one, two, three
12855 m4_dquote(list)
12856 @result{}[one],[two],[three]
12857 m4_append([list2], [one], [[, ]])dnl
12858 m4_append_uniq([list2], [two], [[, ]])dnl
12859 m4_append([list2], [three], [[, ]])dnl
12860 list2
12861 @result{}one, two, three
12862 m4_dquote(list2)
12863 @result{}[one, two, three]
12864 @end example
12865 @end defmac
12867 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12868 @msindex{append_uniq_w}
12869 This macro was introduced in Autoconf 2.62.  It is similar to
12870 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12871 separated list of words to append, and only appends unique words.
12872 @var{macro-name} is updated with a single space between new words.
12873 @example
12874 m4_append_uniq_w([numbers], [1 1 2])dnl
12875 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12876 numbers
12877 @result{}1 2 3
12878 @end example
12879 @end defmac
12881 @defmac m4_chomp (@var{string})
12882 @defmacx m4_chomp_all (@var{string})
12883 @msindex{chomp}
12884 @msindex{chomp_all}
12885 Output @var{string} in quotes, but without a trailing newline.  The
12886 macro @code{m4_chomp} is slightly faster, and removes at most one
12887 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12888 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12889 and backslash does not influence the result.
12890 @end defmac
12892 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12893   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12894 @msindex{combine}
12895 This macro produces a quoted string containing the pairwise combination
12896 of every element of the quoted, comma-separated @var{prefix-list}, and
12897 every element from the @var{suffix} arguments.  Each pairwise
12898 combination is joined with @var{infix} in the middle, and successive
12899 pairs are joined by @var{separator}.  No expansion occurs on any of the
12900 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12901 list is empty, but the lists can contain empty elements.
12902 @example
12903 m4_define([a], [oops])dnl
12904 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12905 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12906 m4_combine([, ], [[a], [b]], [-])
12907 @result{}
12908 m4_combine([, ], [[a], [b]], [-], [])
12909 @result{}a-, b-
12910 m4_combine([, ], [], [-], [1], [2])
12911 @result{}
12912 m4_combine([, ], [[]], [-], [1], [2])
12913 @result{}-1, -2
12914 @end example
12915 @end defmac
12917 @defmac m4_escape (@var{string})
12918 @msindex{escape}
12919 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12920 within @var{string} into their respective quadrigraphs.  The result is
12921 still a quoted string.
12922 @end defmac
12924 @defmac m4_flatten (@var{string})
12925 @msindex{flatten}
12926 Flatten @var{string} into a single line.  Delete all backslash-newline
12927 pairs, and replace all remaining newlines with a space.  The result is
12928 still a quoted string.
12929 @end defmac
12931 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12932 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12933 @msindex{join}
12934 @msindex{joinall}
12935 Concatenate each @var{arg}, separated by @var{separator}.
12936 @code{joinall} uses every argument, while @code{join} omits empty
12937 arguments so that there are no back-to-back separators in the output.
12938 The result is a quoted string.
12939 @example
12940 m4_define([active], [ACTIVE])dnl
12941 m4_join([|], [one], [], [active], [two])
12942 @result{}one|active|two
12943 m4_joinall([|], [one], [], [active], [two])
12944 @result{}one||active|two
12945 @end example
12947 Note that if all you intend to do is join @var{args} with commas between
12948 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12949 efficient to use @code{m4_dquote}.
12950 @end defmac
12952 @defmac m4_newline (@ovar{text})
12953 @msindex{newline}
12954 This macro was introduced in Autoconf 2.62, and expands to a newline,
12955 followed by any @var{text}.
12956 It is primarily useful for maintaining macro formatting, and ensuring
12957 that M4 does not discard leading whitespace during argument collection.
12958 @end defmac
12960 @defmac m4_normalize (@var{string})
12961 @msindex{normalize}
12962 Remove leading and trailing spaces and tabs, sequences of
12963 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12964 with a single space.  This is a combination of @code{m4_flatten} and
12965 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12966 that would be removed by @code{m4_normalize}, you can use
12967 @code{m4_ifblank}.
12968 @end defmac
12970 @defmac m4_re_escape (@var{string})
12971 @msindex{re_escape}
12972 Backslash-escape all characters in @var{string} that are active in
12973 regexps.
12974 @end defmac
12976 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12977 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12978 @msindex{split}
12979 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12980 @samp{]}, while keeping white space at the beginning and at the end.
12981 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12982 If @var{string} is empty, the result is an empty list.
12983 @end defmac
12985 @defmac m4_strip (@var{string})
12986 @msindex{strip}
12987 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12988 reduced to a single space, then leading and trailing spaces are removed.
12989 The result is still a quoted string.  Note that this does not interfere
12990 with newlines; if you want newlines stripped as well, consider
12991 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12992 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12993 @end defmac
12995 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12996 @msindex{text_box}
12997 Add a text box around @var{message}, using @var{frame} as the border
12998 character above and below the message.  The @var{frame} argument must be
12999 a single byte, and does not support quadrigraphs.
13000 The frame correctly accounts for
13001 the subsequent expansion of @var{message}.  For example:
13002 @example
13003 m4_define([macro], [abc])dnl
13004 m4_text_box([macro])
13005 @result{}## --- ##
13006 @result{}## abc ##
13007 @result{}## --- ##
13008 @end example
13010 The @var{message} must contain balanced quotes and parentheses, although
13011 quadrigraphs can be used to work around this.
13012 @end defmac
13014 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13015   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
13016 @msindex{text_wrap}
13017 Break @var{string} into a series of whitespace-separated words, then
13018 output those words separated by spaces, and wrapping lines any time the
13019 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13020 the first line, and @var{prefix} begins all wrapped lines.  If
13021 @var{prefix1} is longer than @var{prefix}, then the first line consists
13022 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13023 padding is inserted so that the first word of @var{string} begins at the
13024 same indentation as all wrapped lines.  Note that using literal tab
13025 characters in any of the arguments will interfere with the calculation
13026 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13027 words of @var{string}, although quadrigraphs are recognized.
13029 For some examples:
13030 @example
13031 m4_text_wrap([Short string */], [   ], [/* ], [20])
13032 @result{}/* Short string */
13033 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13034 @result{}/* Much longer
13035 @result{}   string */
13036 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13037 @result{}  --short Short doc.
13038 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13039 @result{}  --too-wide
13040 @result{}          Short doc.
13041 m4_text_wrap([Super long documentation.], [     ],
13042              [  --too-wide ], 30)
13043 @result{}  --too-wide
13044 @result{}     Super long
13045 @result{}     documentation.
13046 @end example
13047 @end defmac
13049 @defmac m4_tolower (@var{string})
13050 @defmacx m4_toupper (@var{string})
13051 @msindex{tolower}
13052 @msindex{toupper}
13053 Return @var{string} with letters converted to upper or lower case,
13054 respectively.
13055 @end defmac
13057 @node Number processing Macros
13058 @subsection Arithmetic computation in M4
13060 The following macros facilitate integer arithmetic operations.
13061 Where a parameter is documented as taking an arithmetic expression, you
13062 can use anything that can be parsed by @code{m4_eval}.
13064 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13065 @msindex{cmp}
13066 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13067 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13068 equal, and @samp{1} if @var{expr-1} is larger.
13069 @end defmac
13071 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13072 @msindex{list_cmp}
13073 Compare the two M4 lists consisting of comma-separated arithmetic
13074 expressions, left to right.  Expand to @samp{-1} for the first element
13075 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13076 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13077 same values.  If one list is shorter than the other, the remaining
13078 elements of the longer list are compared against zero.
13079 @example
13080 m4_list_cmp([1, 0],       [1])
13081 @result{}0
13082 m4_list_cmp([1, [1 * 0]], [1, 0])
13083 @result{}0
13084 m4_list_cmp([1, 2],       [1, 0])
13085 @result{}1
13086 m4_list_cmp([1, [1+1], 3],[1, 2])
13087 @result{}1
13088 m4_list_cmp([1, 2, -3],   [1, 2])
13089 @result{}-1
13090 m4_list_cmp([1, 0],       [1, 2])
13091 @result{}-1
13092 m4_list_cmp([1],          [1, 2])
13093 @result{}-1
13094 @end example
13095 @end defmac
13097 @defmac m4_max (@var{arg}, @dots{})
13098 @msindex{max}
13099 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13100 of the maximum arithmetic expression among all the arguments.
13101 @end defmac
13103 @defmac m4_min (@var{arg}, @dots{})
13104 @msindex{min}
13105 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13106 of the minimum arithmetic expression among all the arguments.
13107 @end defmac
13109 @defmac m4_sign (@var{expr})
13110 @msindex{sign}
13111 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13112 @samp{1} if it is positive, and @samp{0} if it is zero.
13113 @end defmac
13115 @anchor{m4_version_compare}
13116 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13117 @msindex{version_compare}
13118 This macro was introduced in Autoconf 2.53, but had a number of
13119 usability limitations that were not lifted until Autoconf 2.62.  Compare
13120 the version strings @var{version-1} and @var{version-2}, and expand to
13121 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13122 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13123 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13124 element is a number along with optional case-insensitive letters
13125 designating beta releases.  The comparison stops at the leftmost element
13126 that contains a difference, although a 0 element compares equal to a
13127 missing element.
13129 It is permissible to include commit identifiers in @var{version}, such
13130 as an abbreviated SHA1 of the commit, provided there is still a
13131 monotonically increasing prefix to allow for accurate version-based
13132 comparisons.  For example, this paragraph was written when the
13133 development snapshot of autoconf claimed to be at version
13134 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13135 abbreviated commit identification of @samp{dc51}.
13137 @example
13138 m4_version_compare([1.1], [2.0])
13139 @result{}-1
13140 m4_version_compare([2.0b], [2.0a])
13141 @result{}1
13142 m4_version_compare([1.1.1], [1.1.1a])
13143 @result{}-1
13144 m4_version_compare([1.2], [1.1.1a])
13145 @result{}1
13146 m4_version_compare([1.0], [1])
13147 @result{}0
13148 m4_version_compare([1.1pre], [1.1PRE])
13149 @result{}0
13150 m4_version_compare([1.1a], [1,10])
13151 @result{}-1
13152 m4_version_compare([2.61a], [2.61a-248-dc51])
13153 @result{}-1
13154 m4_version_compare([2.61b], [2.61a-248-dc51])
13155 @result{}1
13156 @end example
13157 @end defmac
13159 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13160   @dvar{if-old, m4_fatal})
13161 @msindex{version_prereq}
13162 Compares @var{version} against the version of Autoconf currently
13163 running.  If the running version is at @var{version} or newer, expand
13164 @var{if-new-enough}, but if @var{version} is larger than the version
13165 currently executing, expand @var{if-old}, which defaults to printing an
13166 error message and exiting m4sugar with status 63.  When given only one
13167 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13168 Remember that the autoconf philosophy favors feature checks over version
13169 checks.
13170 @end defmac
13172 @node Set manipulation Macros
13173 @subsection Set manipulation in M4
13174 @cindex Set manipulation
13175 @cindex Data structure, set
13176 @cindex Unordered set manipulation
13178 Sometimes, it is necessary to track a set of data, where the order does
13179 not matter and where there are no duplicates in the set.  The following
13180 macros facilitate set manipulations.  Each set is an opaque object,
13181 which can only be accessed via these basic operations.  The underlying
13182 implementation guarantees linear scaling for set creation, which is more
13183 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13184 names and values can be arbitrary strings, except for unbalanced quotes.
13185 This implementation ties up memory for removed elements until the next
13186 operation that must traverse all the elements of a set; and although
13187 that may slow down some operations until the memory for removed elements
13188 is pruned, it still guarantees linear performance.
13190 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13191 @msindex{set_add}
13192 Adds the string @var{value} as a member of set @var{set}.  Expand
13193 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13194 previously in the set.  Operates in amortized constant time, so that set
13195 creation scales linearly.
13196 @end defmac
13198 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13199 @msindex{set_add_all}
13200 Adds each @var{value} to the set @var{set}.  This is slightly more
13201 efficient than repeatedly invoking @code{m4_set_add}.
13202 @end defmac
13204 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13205  @ovar{if-absent})
13206 @msindex{set_contains}
13207 Expands @var{if-present} if the string @var{value} is a member of
13208 @var{set}, otherwise @var{if-absent}.
13210 @example
13211 m4_set_contains([a], [1], [yes], [no])
13212 @result{}no
13213 m4_set_add([a], [1], [added], [dup])
13214 @result{}added
13215 m4_set_add([a], [1], [added], [dup])
13216 @result{}dup
13217 m4_set_contains([a], [1], [yes], [no])
13218 @result{}yes
13219 m4_set_remove([a], [1], [removed], [missing])
13220 @result{}removed
13221 m4_set_contains([a], [1], [yes], [no])
13222 @result{}no
13223 m4_set_remove([a], [1], [removed], [missing])
13224 @result{}missing
13225 @end example
13226 @end defmac
13228 @defmac m4_set_contents (@var{set}, @ovar{sep})
13229 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13230 @msindex{set_contents}
13231 @msindex{set_dump}
13232 Expands to a single string consisting of all the members of the set
13233 @var{set}, each separated by @var{sep}, which is not expanded.
13234 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13235 memory occupied by removed elements, while @code{m4_set_dump} is a
13236 faster one-shot action that also deletes the set.  No provision is made
13237 for disambiguating members that contain a non-empty @var{sep} as a
13238 substring; use @code{m4_set_empty} to distinguish between an empty set
13239 and the set containing only the empty string.  The order of the output
13240 is unspecified; in the current implementation, part of the speed of
13241 @code{m4_set_dump} results from using a different output order than
13242 @code{m4_set_contents}.  These macros scale linearly in the size of the
13243 set before memory pruning, and @code{m4_set_contents([@var{set}],
13244 [@var{sep}])} is faster than
13245 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13247 @example
13248 m4_set_add_all([a], [1], [2], [3])
13249 @result{}
13250 m4_set_contents([a], [-])
13251 @result{}1-2-3
13252 m4_joinall([-]m4_set_listc([a]))
13253 @result{}1-2-3
13254 m4_set_dump([a], [-])
13255 @result{}3-2-1
13256 m4_set_contents([a])
13257 @result{}
13258 m4_set_add([a], [])
13259 @result{}
13260 m4_set_contents([a], [-])
13261 @result{}
13262 @end example
13263 @end defmac
13265 @defmac m4_set_delete (@var{set})
13266 @msindex{set_delete}
13267 Delete all elements and memory associated with @var{set}.  This is
13268 linear in the set size, and faster than removing one element at a time.
13269 @end defmac
13271 @defmac m4_set_difference (@var{seta}, @var{setb})
13272 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13273 @defmacx m4_set_union (@var{seta}, @var{setb})
13274 @msindex{set_difference}
13275 @msindex{set_intersection}
13276 @msindex{set_union}
13277 Compute the relation between @var{seta} and @var{setb}, and output the
13278 result as a list of quoted arguments without duplicates and with a
13279 leading comma.  Set difference selects the elements in @var{seta} but
13280 not @var{setb}, intersection selects only elements in both sets, and
13281 union selects elements in either set.  These actions are linear in the
13282 sum of the set sizes.  The leading comma is necessary to distinguish
13283 between no elements and the empty string as the only element.
13285 @example
13286 m4_set_add_all([a], [1], [2], [3])
13287 @result{}
13288 m4_set_add_all([b], [3], [], [4])
13289 @result{}
13290 m4_set_difference([a], [b])
13291 @result{},1,2
13292 m4_set_difference([b], [a])
13293 @result{},,4
13294 m4_set_intersection([a], [b])
13295 @result{},3
13296 m4_set_union([a], [b])
13297 @result{},1,2,3,,4
13298 @end example
13299 @end defmac
13301 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13302 @msindex{set_empty}
13303 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13304 expand @var{if-elements}.  This macro operates in constant time.  Using
13305 this macro can help disambiguate output from @code{m4_set_contents} or
13306 @code{m4_set_list}.
13307 @end defmac
13309 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13310 @msindex{set_foreach}
13311 For each element in the set @var{set}, expand @var{action} with the
13312 macro @var{variable} defined as the set element.  Behavior is
13313 unspecified if @var{action} recursively lists the contents of @var{set}
13314 (although listing other sets is acceptable), or if it modifies the set
13315 in any way other than removing the element currently contained in
13316 @var{variable}.  This macro is faster than the corresponding
13317 @code{m4_foreach([@var{variable}],
13318 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13319 although @code{m4_set_map} might be faster still.
13321 @example
13322 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13323 @result{}
13324 m4_set_contents([a])
13325 @result{}12345
13326 m4_set_foreach([a], [i],
13327   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13328 @result{}24
13329 m4_set_contents([a])
13330 @result{}135
13331 @end example
13332 @end defmac
13334 @defmac m4_set_list (@var{set})
13335 @defmacx m4_set_listc (@var{set})
13336 @msindex{set_list}
13337 @msindex{set_listc}
13338 Produce a list of arguments, where each argument is a quoted element
13339 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13340 by adding a leading comma if there are any set elements, whereas the
13341 variant @code{m4_set_list} cannot distinguish between an empty set and a
13342 set containing only the empty string.  These can be directly used in
13343 macros that take multiple arguments, such as @code{m4_join} or
13344 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13345 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13346 memory occupied by removed elements is reclaimed during these macros.
13348 @example
13349 m4_set_add_all([a], [1], [2], [3])
13350 @result{}
13351 m4_set_list([a])
13352 @result{}1,2,3
13353 m4_set_list([b])
13354 @result{}
13355 m4_set_listc([b])
13356 @result{}
13357 m4_count(m4_set_list([b]))
13358 @result{}1
13359 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13360 @result{}0
13361 m4_set_add([b], [])
13362 @result{}
13363 m4_set_list([b])
13364 @result{}
13365 m4_set_listc([b])
13366 @result{},
13367 m4_count(m4_set_list([b]))
13368 @result{}1
13369 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13370 @result{}1
13371 @end example
13372 @end defmac
13374 @defmac m4_set_map (@var{set}, @var{action})
13375 @msindex{set_map}
13376 For each element in the set @var{set}, expand @var{action} with a single
13377 argument of the set element.  Behavior is unspecified if @var{action}
13378 recursively lists the contents of @var{set} (although listing other sets
13379 is acceptable), or if it modifies the set in any way other than removing
13380 the element passed as an argument.  This macro is faster than either
13381 corresponding counterpart of
13382 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13383 @code{m4_set_foreach([@var{set}], [var],
13384 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13385 if more than one argument is needed for @var{action}, although it is
13386 more efficient to use @code{m4_set_map_sep} in that case.
13387 @end defmac
13389 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13390 @msindex{set_map_sep}
13391 For each element in the set @var{set}, expand
13392 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13393 between elements.  Behavior is unspecified if the expansion recursively
13394 lists the contents of @var{set} (although listing other sets
13395 is acceptable), or if it modifies the set in any way other than removing
13396 the element visited by the expansion.  This macro provides the most
13397 efficient means for non-destructively visiting the elements of a set; in
13398 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13399 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13400 @end defmac
13402 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13403  @ovar{if-absent})
13404 @msindex{set_remove}
13405 If @var{value} is an element in the set @var{set}, then remove it and
13406 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13407 operates in constant time so that multiple removals will scale linearly
13408 rather than quadratically; but when used outside of
13409 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13410 until the set is later
13411 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13412 other set operations are then less efficient between the time of element
13413 removal and subsequent memory compaction, but still maintain their
13414 guaranteed scaling performance.
13415 @end defmac
13417 @defmac m4_set_size (@var{set})
13418 @msindex{set_size}
13419 Expand to the size of the set @var{set}.  This implementation operates
13420 in constant time, and is thus more efficient than
13421 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13422 @end defmac
13425 @node Forbidden Patterns
13426 @subsection Forbidden Patterns
13427 @cindex Forbidden patterns
13428 @cindex Patterns, forbidden
13430 M4sugar provides a means to define suspicious patterns, patterns
13431 describing tokens which should not be found in the output.  For
13432 instance, if an Autoconf @file{configure} script includes tokens such as
13433 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13434 wrong (typically a macro was not evaluated because of overquotation).
13436 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13437 Additional layers, such as M4sh and Autoconf, add additional forbidden
13438 patterns to the list.
13440 @defmac m4_pattern_forbid (@var{pattern})
13441 @msindex{pattern_forbid}
13442 Declare that no token matching @var{pattern} must be found in the output.
13443 Comments are not checked; this can be a problem if, for instance, you
13444 have some macro left unexpanded after an @samp{#include}.  No consensus
13445 is currently found in the Autoconf community, as some people consider it
13446 should be valid to name macros in comments (which doesn't make sense to
13447 the authors of this documentation: input, such as macros, should be
13448 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13449 document the output).
13450 @end defmac
13452 Of course, you might encounter exceptions to these generic rules, for
13453 instance you might have to refer to @samp{$m4_flags}.
13455 @defmac m4_pattern_allow (@var{pattern})
13456 @msindex{pattern_allow}
13457 Any token matching @var{pattern} is allowed, including if it matches an
13458 @code{m4_pattern_forbid} pattern.
13459 @end defmac
13461 @node Debugging via autom4te
13462 @section Debugging via autom4te
13463 @cindex debugging tips
13464 @cindex autom4te debugging tips
13465 @cindex m4sugar debugging tips
13466 At times, it is desirable to see what was happening inside m4, to see
13467 why output was not matching expectations.  However, post-processing done
13468 by @command{autom4te} means that directly using the m4 builtin
13469 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13470 diversion changes and the concept of forbidden tokens make it difficult
13471 to use @code{m4_defn} to generate inline comments in the final output.
13473 There are a couple of tools to help with this.  One is the use of the
13474 @option{--trace} option provided by @command{autom4te} (as well as each
13475 of the programs that wrap @command{autom4te}, such as
13476 @command{autoconf}), in order to inspect when a macro is called and with
13477 which arguments.  For example, when this paragraph was written, the
13478 autoconf version could be found by:
13480 @example
13481 $ @kbd{autoconf --trace=AC_INIT}
13482 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13483 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13484 version is 2.63b.95-3963
13485 @end example
13487 Another trick is to print out the expansion of various m4 expressions to
13488 standard error or to an independent file, with no further m4 expansion,
13489 and without interfering with diversion changes or the post-processing
13490 done to standard output.  @code{m4_errprintn} shows a given expression
13491 on standard error.  For example, if you want to see the expansion of an
13492 autoconf primitive or of one of your autoconf macros, you can do it like
13493 this:
13495 @example
13496 $ @kbd{cat <<\EOF > configure.ac}
13497 AC_INIT
13498 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13499 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13500 AC_OUTPUT
13502 $ @kbd{autoconf}
13503 @error{}The definition of AC_DEFINE_UNQUOTED:
13504 @error{}_AC_DEFINE_Q([], $@@)
13505 @end example
13507 @node Programming in M4sh
13508 @chapter Programming in M4sh
13510 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13511 scripts.  This name was coined by Lars J. Aas, who notes that,
13512 according to the Webster's Revised Unabridged Dictionary (1913):
13514 @quotation
13515 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13516 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13518 @enumerate 1
13519 @item
13520 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13521 pressure@enddots{}
13523 @item
13524 A mixture of meal or bran and water fed to animals.
13526 @item
13527 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13528 @end enumerate
13529 @end quotation
13531 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13532 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13533 and environment variable namespace @samp{^as_}, and the here-document
13534 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13535 define your own macros or output shell code that conflicts with these
13536 namespaces.
13538 @menu
13539 * Common Shell Constructs::     Portability layer for common shell constructs
13540 * Polymorphic Variables::       Support for indirect variable names
13541 * Initialization Macros::       Macros to establish a sane shell environment
13542 * File Descriptor Macros::      File descriptor macros for input and output
13543 @end menu
13545 @node Common Shell Constructs
13546 @section Common Shell Constructs
13548 M4sh provides portable alternatives for some common shell constructs
13549 that unfortunately are not portable in practice.
13551 @c Deprecated, to be replaced by a better API
13552 @ignore
13553 @defmac AS_BASENAME (@var{file-name})
13554 @asindex{BASENAME}
13555 Output the non-directory portion of @var{file-name}.  For example,
13556 if @code{$file} is @samp{/one/two/three}, the command
13557 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13558 @end defmac
13559 @end ignore
13561 @defmac AS_BOX (@var{text}, @dvar{char, -})
13562 @asindex{BOX}
13563 Expand into shell code that will output @var{text} surrounded by a box
13564 with @var{char} in the top and bottom border.  @var{text} should not
13565 contain a newline, but may contain shell expansions valid for unquoted
13566 here-documents.  @var{char} defaults to @samp{-}, but can be any
13567 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13568 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13569 log files to separate distinct phases of script operation.
13570 @end defmac
13572 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13573   @dots{}, @ovar{default})
13574 @asindex{CASE}
13575 Expand into a shell @samp{case} statement, where @var{word} is matched
13576 against one or more patterns.  @var{if-matched} is run if the
13577 corresponding pattern matched @var{word}, else @var{default} is run.
13578 Avoids several portability issues (@pxref{case, , Limitations of Shell
13579 Builtins}).
13580 @end defmac
13582 @c Deprecated, to be replaced by a better API
13583 @defmac AS_DIRNAME (@var{file-name})
13584 @asindex{DIRNAME}
13585 Output the directory portion of @var{file-name}.  For example,
13586 if @code{$file} is @samp{/one/two/three}, the command
13587 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13589 This interface may be improved in the future to avoid forks and losing
13590 trailing newlines.
13591 @end defmac
13593 @defmac AS_ECHO (@var{word})
13594 @asindex{ECHO}
13595 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13596 must be a single shell word (typically a quoted string).  The bytes of
13597 @var{word} are output as-is, even if it starts with "-" or contains "\".
13598 Redirections can be placed outside the macro invocation.  This is much
13599 more portable than using @command{echo} (@pxref{echo, , Limitations of
13600 Shell Builtins}).
13601 @end defmac
13603 @defmac AS_ECHO_N (@var{word})
13604 @asindex{ECHO_N}
13605 Emits @var{word} to the standard output, without a following newline.
13606 @var{word} must be a single shell word (typically a quoted string) and,
13607 for portability, should not include more than one newline.  The bytes of
13608 @var{word} are output as-is, even if it starts with "-" or contains "\".
13609 Redirections can be placed outside the macro invocation.
13610 @end defmac
13612 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13613 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13614 @asindex{ESCAPE}
13615 Expands to @var{string}, with any characters in @var{chars} escaped with
13616 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13617 and only contain characters from the set @samp{`\"$}; however,
13618 characters may be safely listed more than once in @var{chars} for the
13619 sake of syntax highlighting editors.  The current implementation expands
13620 @var{string} after adding escapes; if @var{string} contains macro calls
13621 that in turn expand to text needing shell quoting, you can use
13622 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13624 The default for @var{chars} (@samp{\"$`}) is the set of characters
13625 needing escapes when @var{string} will be used literally within double
13626 quotes.  One common variant is the set of characters to protect when
13627 @var{string} will be used literally within back-ticks or an unquoted
13628 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13629 be used to form a double-quoted string containing the same expansions
13630 that would have occurred if @var{string} were expanded in an unquoted
13631 here-document; however, when using this variant, care must be taken that
13632 @var{string} does not use double quotes within complex variable
13633 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13634 with improper escapes.
13636 This macro is often used with @code{AS_ECHO}.  For an example, observe
13637 the output generated by the shell code generated from this snippet:
13639 @example
13640 foo=bar
13641 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13642 @result{}"$foo" = "bar"
13643 m4_define([macro], [a, [\b]])
13644 AS_ECHO(["AS_ESCAPE([[macro]])"])
13645 @result{}macro
13646 AS_ECHO(["AS_ESCAPE([macro])"])
13647 @result{}a, b
13648 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13649 @result{}a, \b
13650 @end example
13652 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13653 @comment the case of @var{string} that does not contain '.
13654 To escape a string that will be placed within single quotes, use:
13656 @example
13657 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13658 @end example
13659 @end defmac
13661 @defmac AS_EXIT (@dvar{status, $?})
13662 @asindex{EXIT}
13663 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13664 This macro
13665 works around shells that see the exit status of the command prior to
13666 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13667 of Shell Builtins}).
13668 @end defmac
13670 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13671 @asindex{IF}
13672 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13673 run shell code @var{run-if-true1}, else examine further tests.  If no test
13674 exits with a zero status, run shell code @var{run-if-false}, with
13675 simplifications if either @var{run-if-true1} or @var{run-if-false}
13676 is empty.  For example,
13678 @example
13679 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13680       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13681       [echo foo not specified])
13682 @end example
13684 @noindent
13685 ensures any required macros of @code{HANDLE_FOO}
13686 are expanded before the first test.
13687 @end defmac
13689 @defmac AS_MKDIR_P (@var{file-name})
13690 @asindex{MKDIR_P}
13691 Make the directory @var{file-name}, including intervening directories
13692 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13693 except that it is portable to older versions of @command{mkdir} that
13694 lack support for the @option{-p} option or for the @option{--}
13695 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13696 @code{AS_MKDIR_P}
13697 succeeds if @var{file-name} is a symbolic link to an existing directory,
13698 even though Posix is unclear whether @samp{mkdir -p} should
13699 succeed in that case.  If creation of @var{file-name} fails, exit the
13700 script.
13702 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13703 @end defmac
13705 @defmac AS_SET_STATUS (@var{status})
13706 @asindex{SET_STATUS}
13707 Emit shell code to set the value of @samp{$?} to @var{status}, as
13708 efficiently as possible.  However, this is not guaranteed to abort a
13709 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13710 Builtins}).  This should also be used at the end of a complex shell
13711 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13712 a DJGPP shell bug.
13713 @end defmac
13715 @defmac AS_TR_CPP (@var{expression})
13716 @asindex{TR_CPP}
13717 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13718 For example:
13720 @example
13721 # This outputs "#define HAVE_CHAR_P 1".
13722 # Notice the m4 quoting around #, to prevent an m4 comment
13723 type="char *"
13724 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13725 @end example
13726 @end defmac
13728 @defmac AS_TR_SH (@var{expression})
13729 @asindex{TR_SH}
13730 Transform @var{expression} into shell code that generates a valid shell
13731 variable name.  The result is literal when possible at m4 time, but must
13732 be used with @code{eval} if @var{expression} causes shell indirections.
13733 For example:
13735 @example
13736 # This outputs "Have it!".
13737 header="sys/some file.h"
13738 eval AS_TR_SH([HAVE_$header])=yes
13739 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13740 @end example
13741 @end defmac
13743 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13744 @asindex{SET_CATFILE}
13745 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13746 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13747 @var{file} is absolute, etc.).
13748 @end defmac
13750 @defmac AS_UNSET (@var{var})
13751 @asindex{UNSET}
13752 Unsets the shell variable @var{var}, working around bugs in older
13753 shells (@pxref{unset, , Limitations of Shell
13754 Builtins}).  @var{var} can be a literal or indirect variable name.
13755 @end defmac
13757 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13758   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13759 @asindex{VERSION_COMPARE}
13760 Compare two strings @var{version-1} and @var{version-2}, possibly
13761 containing shell variables, as version strings, and expand
13762 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13763 depending upon the result.
13764 The algorithm to compare is similar to the one used by strverscmp in
13765 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13766 The GNU C Library}).
13767 @end defmac
13769 @node Polymorphic Variables
13770 @section Support for indirect variable names
13771 @cindex variable name indirection
13772 @cindex polymorphic variable name
13773 @cindex indirection, variable name
13775 Often, it is convenient to write a macro that will emit shell code
13776 operating on a shell variable.  The simplest case is when the variable
13777 name is known.  But a more powerful idiom is writing shell code that can
13778 work through an indirection, where another variable or command
13779 substitution produces the name of the variable to actually manipulate.
13780 M4sh supports the notion of polymorphic shell variables, making it easy
13781 to write a macro that can deal with either literal or indirect variable
13782 names and output shell code appropriate for both use cases.  Behavior is
13783 undefined if expansion of an indirect variable does not result in a
13784 literal variable name.
13786 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13787   @dvar{if-simple-ref, @var{if-not}})
13788 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13789   @ovar{if-not}, @dvar{if-simple-ref, @var{if-not}})
13790 @asindex{LITERAL_IF}
13791 @asindex{LITERAL_WORD_IF}
13792 If the expansion of @var{expression} is definitely a shell literal,
13793 expand @var{if-literal}.  If the expansion of @var{expression} looks
13794 like it might contain shell indirections (such as @code{$var} or
13795 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13796 possible to output optimized code if @var{expression} consists only of
13797 shell variable expansions (such as @code{$@{var@}}), in which case
13798 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13799 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13800 @var{if-literal} if @var{expression} looks like a single shell word,
13801 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13802 in @var{expression}.
13804 In order to reduce the time spent recognizing whether an
13805 @var{expression} qualifies as a literal or a simple indirection, the
13806 implementation is somewhat conservative: @var{expression} must be a
13807 single shell word (possibly after stripping whitespace), consisting only
13808 of bytes that would have the same meaning whether unquoted or enclosed
13809 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13810 even though it is not a valid shell variable name; while both @samp{'a'}
13811 and @samp{[$]} result in @var{if-not}, because they behave differently
13812 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13813 for recognizing portable file names (such as in the implementation of
13814 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13815 valid variable names (such as in the implementation of @code{AS_TR_SH},
13816 which uses an additional @code{m4_translit} to convert @samp{.} to
13817 @samp{_}).
13819 This example shows how to read the contents of the shell variable
13820 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13821 results in a script that will output the line @samp{hello} three times.
13823 @example
13824 AC_DEFUN([MY_ACTION],
13825 [AS_LITERAL_IF([$1],
13826   [echo "$$1"],
13827 @c $$
13828   [AS_VAR_COPY([var], [$1])
13829    echo "$var"],
13830   [eval 'echo "$'"$1"\"])])
13831 foo=bar bar=hello
13832 MY_ACTION([bar])
13833 MY_ACTION([`echo bar`])
13834 MY_ACTION([$foo])
13835 @end example
13836 @end defmac
13838 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13839 @asindex{VAR_APPEND}
13840 Emit shell code to append the shell expansion of @var{text} to the end
13841 of the current contents of the polymorphic shell variable @var{var},
13842 taking advantage of shells that provide the @samp{+=} extension for more
13843 efficient scaling.
13845 For situations where the final contents of @var{var} are relatively
13846 short (less than 256 bytes), it is more efficient to use the simpler
13847 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13848 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13849 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13850 when the script will be repeatedly appending text into @code{var},
13851 issues of scaling start to become apparent.  A naive implementation
13852 requires execution time linear to the length of the current contents of
13853 @var{var} as well as the length of @var{text} for a single append, for
13854 an overall quadratic scaling with multiple appends.  This macro takes
13855 advantage of shells which provide the extension
13856 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13857 for a single append, for an overall linear scaling with multiple
13858 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13859 @var{text} be quoted properly to avoid field splitting and file name
13860 expansion.
13861 @end defmac
13863 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13864 @asindex{VAR_ARITH}
13865 Emit shell code to compute the arithmetic expansion of @var{expression},
13866 assigning the result as the contents of the polymorphic shell variable
13867 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13868 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13869 syntax for a valid @var{expression} is rather limited: all operators
13870 must occur as separate shell arguments and with proper quoting, there is
13871 no portable equality operator, all variables containing numeric values
13872 must be expanded prior to the computation, all numeric values must be
13873 provided in decimal without leading zeroes, and the first shell argument
13874 should not be a negative number.  In the following example, this snippet
13875 will print @samp{(2+3)*4 == 20}.
13877 @example
13878 bar=3
13879 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13880 echo "(2+$bar)*4 == $foo"
13881 @end example
13882 @end defmac
13884 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13885 @asindex{VAR_COPY}
13886 Emit shell code to assign the contents of the polymorphic shell variable
13887 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13888 executing this M4sh snippet will output @samp{bar hi}:
13890 @example
13891 foo=bar bar=hi
13892 AS_VAR_COPY([a], [foo])
13893 AS_VAR_COPY([b], [$foo])
13894 echo "$a $b"
13895 @end example
13897 When it is necessary to access the contents of an indirect variable
13898 inside a shell double-quoted context, the recommended idiom is to first
13899 copy the contents into a temporary literal shell variable.
13901 @smallexample
13902 for header in stdint_h inttypes_h ; do
13903   AS_VAR_COPY([var], [ac_cv_header_$header])
13904   echo "$header detected: $var"
13905 done
13906 @end smallexample
13907 @end defmac
13909 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13910 @comment trailing newlines uniformly, and forks too much.
13912 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13913   @ovar{if-not-equal})
13914 @asindex{VAR_IF}
13915 Output a shell conditional statement.  If the contents of the
13916 polymorphic shell variable @var{var} match the string @var{word},
13917 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13918 must be a single shell word (typically a quoted string).  Avoids
13919 shell bugs if an interrupt signal arrives while a command substitution
13920 in @var{var} is being expanded.
13921 @end defmac
13923 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13924 @defmacx AS_VAR_POPDEF (@var{m4-name})
13925 @asindex{VAR_PUSHDEF}
13926 @asindex{VAR_POPDEF}
13927 @cindex composing variable names
13928 @cindex variable names, composing
13929 A common M4sh idiom involves composing shell variable names from an m4
13930 argument (for example, writing a macro that uses a cache variable).
13931 @var{value} can be an arbitrary string, which will be transliterated
13932 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13933 composed variable name based on @var{value}, it is easier to declare a
13934 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13935 that macro as the argument to subsequent @code{AS_VAR} macros as a
13936 polymorphic variable name, and finally free the temporary macro with
13937 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13938 to avoid excess newlines in the output.
13940 Here is an involved example, that shows the power of writing macros that
13941 can handle composed shell variable names:
13943 @example
13944 m4_define([MY_CHECK_HEADER],
13945 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13946 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13947 AS_VAR_POPDEF([my_Header])dnl
13949 MY_CHECK_HEADER([stdint.h])
13950 for header in inttypes.h stdlib.h ; do
13951   MY_CHECK_HEADER([$header])
13952 done
13953 @end example
13955 @noindent
13956 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13957 variable names.  In the first invocation, the m4 argument is
13958 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13959 As a result, the temporary macro @code{my_Header} expands to the literal
13960 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13961 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13962 temporary macro @code{my_Header} expands to the indirect shell name
13963 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13964 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13965 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13966 platform where all three headers have been previously detected, the
13967 output of the script will include:
13969 @smallexample
13970 header stdint.h detected
13971 header inttypes.h detected
13972 header stdlib.h detected
13973 @end smallexample
13974 @end defmac
13976 @defmac AS_VAR_SET (@var{var}, @ovar{value})
13977 @asindex{VAR_SET}
13978 Emit shell code to assign the contents of the polymorphic shell variable
13979 @var{var} to the shell expansion of @var{value}.  @var{value} is not
13980 subject to field splitting or file name expansion, so if command
13981 substitution is used, it may be done with @samp{`""`} rather than using
13982 an intermediate variable (@pxref{Shell Substitutions}).  However,
13983 @var{value} does undergo rescanning for additional macro names; behavior
13984 is unspecified if late expansion results in any shell meta-characters.
13985 @end defmac
13987 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
13988 @asindex{VAR_SET_IF}
13989 Emit a shell conditional statement, which executes @var{if-set} if the
13990 polymorphic shell variable @code{var} is set to any value, and
13991 @var{if-undef} otherwise.
13992 @end defmac
13994 @defmac AS_VAR_TEST_SET (@var{var})
13995 @asindex{VAR_TEST_SET}
13996 Emit a shell statement that results in a successful exit status only if
13997 the polymorphic shell variable @code{var} is set.
13998 @end defmac
14000 @node Initialization Macros
14001 @section Initialization Macros
14003 @defmac AS_BOURNE_COMPATIBLE
14004 @asindex{BOURNE_COMPATIBLE}
14005 Set up the shell to be more compatible with the Bourne shell as
14006 standardized by Posix, if possible.  This may involve setting
14007 environment variables, or setting options, or similar
14008 implementation-specific actions.  This macro is deprecated, since
14009 @code{AS_INIT} already invokes it.
14010 @end defmac
14012 @defmac AS_INIT
14013 @asindex{INIT}
14014 @evindex LC_ALL
14015 @evindex SHELL
14016 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14017 outputs the @code{#! /bin/sh} line, a notice about where the output was
14018 generated from, and code to sanitize the environment for the rest of the
14019 script.  Among other initializations, this sets @env{SHELL} to the shell
14020 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14021 ensure the C locale.  Finally, it changes the current diversion to
14022 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14023 and @code{AT_INIT}, so shell code in @file{configure},
14024 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14025 shell environment.
14026 @end defmac
14028 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14029 @asindex{INIT_GENERATED}
14030 Emit shell code to start the creation of a subsidiary shell script in
14031 @var{file}, including changing @var{file} to be executable.  This macro
14032 populates the child script with information learned from the parent
14033 (thus, the emitted code is equivalent in effect, but more efficient,
14034 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14035 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14036 beginning of the child, prior to the shell initialization code, and is
14037 subject to parameter expansion, command substitution, and backslash
14038 quote removal.  The
14039 parent script should check the exit status after this macro, in case
14040 @var{file} could not be properly created (for example, if the disk was
14041 full).  If successfully created, the parent script can then proceed to
14042 append additional M4sh constructs into the child script.
14044 Note that the child script starts life without a log file open, so if
14045 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14046 must temporarily disable any attempts to use the log file until after
14047 emitting code to open a log within the child.  On the other hand, if the
14048 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14049 @samp{1}, then the child script already has code that copies stdout to
14050 that descriptor.  Currently, the suggested
14051 idiom for writing a M4sh shell script from within another script is:
14053 @example
14054 AS_INIT_GENERATED([@var{file}], [[# My child script.
14055 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14056 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14057 cat >> "@var{file}" <<\__EOF__
14058 # Code to initialize AS_MESSAGE_LOG_FD
14059 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14060 # Additional code
14061 __EOF__
14062 @end example
14064 This, however, may change in the future as the M4sh interface is
14065 stabilized further.
14067 Also, be aware that use of @env{LINENO} within the child script may
14068 report line numbers relative to their location in the parent script,
14069 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14070 unable to locate a shell with working @env{LINENO} support.
14071 @end defmac
14073 @defmac AS_LINENO_PREPARE
14074 @asindex{LINENO_PREPARE}
14075 @evindex LINENO
14076 Find a shell that supports the special variable @env{LINENO}, which
14077 contains the number of the currently executing line.  This macro is
14078 automatically invoked by @code{AC_INIT} in configure scripts.
14079 @end defmac
14081 @defmac AS_ME_PREPARE
14082 @asindex{ME_PREPARE}
14083 Set up variable @env{as_me} to be the basename of the currently executing
14084 script.  This macro is automatically invoked by @code{AC_INIT} in
14085 configure scripts.
14086 @end defmac
14088 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14089 @asindex{TMPDIR}
14090 @evindex TMPDIR
14091 @ovindex tmp
14092 Create, as safely as possible, a temporary sub-directory within
14093 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14094 be 2-4 characters, to make it slightly easier to identify the owner of
14095 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14096 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14097 newly created directory is stored in the shell variable @code{tmp}.  On
14098 error, the script is aborted.
14100 Typically, this macro is coupled with some exit traps to delete the created
14101 directory and its contents on exit or interrupt.  However, there is a
14102 slight window between when the directory is created and when the name is
14103 actually known to the shell, so an interrupt at the right moment might
14104 leave the temporary directory behind.  Hence it is important to use a
14105 @var{prefix} that makes it easier to determine if a leftover temporary
14106 directory from an interrupted script is safe to delete.
14108 The use of the output variable @samp{$tmp} rather than something in the
14109 @samp{as_} namespace is historical; it has the unfortunate consequence
14110 that reusing this otherwise common name for any other purpose inside
14111 your script has the potential to break any cleanup traps designed to
14112 remove the temporary directory.
14113 @end defmac
14115 @defmac AS_SHELL_SANITIZE
14116 @asindex{SHELL_SANITIZE}
14117 Initialize the shell suitably for @command{configure} scripts.  This has
14118 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14119 environment variables for predictable results from configuration tests.
14120 For example, it sets @env{LC_ALL} to change to the default C locale.
14121 @xref{Special Shell Variables}.  This macro is deprecated, since
14122 @code{AS_INIT} already invokes it.
14123 @end defmac
14126 @node File Descriptor Macros
14127 @section File Descriptor Macros
14128 @cindex input
14129 @cindex standard input
14130 @cindex file descriptors
14131 @cindex descriptors
14132 @cindex low-level output
14133 @cindex output, low-level
14135 The following macros define file descriptors used to output messages
14136 (or input values) from @file{configure} scripts.
14137 For example:
14139 @example
14140 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14141 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14142 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14143 @end example
14145 @noindent
14146 However doing so is seldom needed, because Autoconf provides higher
14147 level macros as described below.
14149 @defmac AS_MESSAGE_FD
14150 @asindex{MESSAGE_FD}
14151 The file descriptor for @samp{checking for...}  messages and results.
14152 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14153 clients.  However, @code{AC_INIT} shuffles things around to another file
14154 descriptor, in order to allow the @option{-q} option of
14155 @command{configure} to choose whether messages should go to the script's
14156 standard output or be discarded.
14158 If you want to display some messages, consider using one of the printing
14159 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14160 via these macros are also recorded in @file{config.log}.
14161 @end defmac
14163 @anchor{AS_MESSAGE_LOG_FD}
14164 @defmac AS_MESSAGE_LOG_FD
14165 @asindex{MESSAGE_LOG_FD}
14166 This must either be empty, or expand to a file descriptor for log
14167 messages.  By default, @code{AS_INIT} sets this macro to the empty
14168 string for standalone M4sh clients, thus disabling logging.  However,
14169 @code{AC_INIT} shuffles things around so that both @command{configure}
14170 and @command{config.status} use @file{config.log} for log messages.
14171 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14172 Compiler}), redirect all output to this descriptor.  You may want to do
14173 so if you develop such a low-level macro.
14174 @end defmac
14176 @defmac AS_ORIGINAL_STDIN_FD
14177 @asindex{ORIGINAL_STDIN_FD}
14178 This must expand to a file descriptor for the original standard input.
14179 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14180 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14181 safety.
14183 When @command{configure} runs, it may accidentally execute an
14184 interactive command that has the same name as the non-interactive meant
14185 to be used or checked.  If the standard input was the terminal, such
14186 interactive programs would cause @command{configure} to stop, pending
14187 some user input.  Therefore @command{configure} redirects its standard
14188 input from @file{/dev/null} during its initialization.  This is not
14189 normally a problem, since @command{configure} normally does not need
14190 user input.
14192 In the extreme case where your @file{configure} script really needs to
14193 obtain some values from the original standard input, you can read them
14194 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14195 @end defmac
14198 @c =================================================== Writing Autoconf Macros.
14200 @node Writing Autoconf Macros
14201 @chapter Writing Autoconf Macros
14203 When you write a feature test that could be applicable to more than one
14204 software package, the best thing to do is encapsulate it in a new macro.
14205 Here are some instructions and guidelines for writing Autoconf macros.
14207 @menu
14208 * Macro Definitions::           Basic format of an Autoconf macro
14209 * Macro Names::                 What to call your new macros
14210 * Reporting Messages::          Notifying @command{autoconf} users
14211 * Dependencies Between Macros::  What to do when macros depend on other macros
14212 * Obsoleting Macros::           Warning about old ways of doing things
14213 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14214 @end menu
14216 @node Macro Definitions
14217 @section Macro Definitions
14219 @defmac AC_DEFUN (@var{name}, @ovar{body})
14220 @acindex{DEFUN}
14221 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14222 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14223 named @var{name} and with @var{body} as its expansion.  In addition to
14224 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14225 constrain the order in which macros are called, while avoiding redundant
14226 output (@pxref{Prerequisite Macros}).
14227 @end defmac
14229 An Autoconf macro definition looks like this:
14231 @example
14232 AC_DEFUN(@var{macro-name}, @var{macro-body})
14233 @end example
14235 You can refer to any arguments passed to the macro as @samp{$1},
14236 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
14237 GNU M4}, for more complete information on writing M4 macros.
14239 Most macros fall in one of two general categories.  The first category
14240 includes macros which take arguments, in order to generate output
14241 parameterized by those arguments.  Macros in this category are designed
14242 to be directly expanded, often multiple times, and should not be used as
14243 the argument to @code{AC_REQUIRE}.  The other category includes macros
14244 which are shorthand for a fixed block of text, and therefore do not take
14245 arguments.  For this category of macros, directly expanding the macro
14246 multiple times results in redundant output, so it is more common to use
14247 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14248 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14250 Be sure to properly quote both the @var{macro-body} @emph{and} the
14251 @var{macro-name} to avoid any problems if the macro happens to have
14252 been previously defined.
14254 Each macro should have a header comment that gives its prototype, and a
14255 brief description.  When arguments have default values, display them in
14256 the prototype.  For example:
14258 @example
14259 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14260 # --------------------------------------
14261 m4_define([AC_MSG_ERROR],
14262   [@{ AS_MESSAGE([error: $1], [2])
14263      exit m4_default([$2], [1]); @}])
14264 @end example
14266 Comments about the macro should be left in the header comment.  Most
14267 other comments make their way into @file{configure}, so just keep
14268 using @samp{#} to introduce comments.
14270 @cindex @code{dnl}
14271 If you have some special comments about pure M4 code, comments
14272 that make no sense in @file{configure} and in the header comment, then
14273 use the builtin @code{dnl}: it causes M4 to discard the text
14274 through the next newline.
14276 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14277 @code{dnl} is more useful to get rid of the newlines following macros
14278 that produce no output, such as @code{AC_REQUIRE}.
14280 Public third-party macros need to use @code{AC_DEFUN}, and not
14281 @code{m4_define}, in order to be found by @command{aclocal}
14282 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14283 Additionally, if it is ever determined that a macro should be made
14284 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14285 in order to have @command{autoupdate} assist the user in choosing a
14286 better alternative, but there is no corresponding way to make
14287 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14289 There is another subtle, but important, difference between using
14290 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14291 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14292 block of text with a @code{m4_define} macro that will expand to the same
14293 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14294 the same content does not necessarily give the same results, because it
14295 changes the location where any embedded but unsatisfied
14296 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14297 example of this, see @ref{Expanded Before Required}.
14299 @node Macro Names
14300 @section Macro Names
14302 All of the public Autoconf macros have all-uppercase names in the
14303 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14304 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14305 internal macros.  All shell variables that they use for internal
14306 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14307 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14308 @command{configure}, files produced by Autoconf make heavy use of the
14309 file system namespace @samp{^conf}.
14311 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14312 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14313 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14314 @file{configure.ac} is also designed to be scanned by Autoheader,
14315 Autoscan, Autoupdate, and Automake, you should be aware of the
14316 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14317 the namespace of a package that does not own the macro or shell code you
14318 are writing.
14320 To ensure that your macros don't conflict with present or future
14321 Autoconf macros, you should prefix your own macro names and any shell
14322 variables they use with some other sequence.  Possibilities include your
14323 initials, or an abbreviation for the name of your organization or
14324 software package.  Historically, people have not always followed the
14325 rule of using a namespace appropriate for their package, and this has
14326 made it difficult for determining the origin of a macro (and where to
14327 report bugs about that macro), as well as difficult for the true
14328 namespace owner to add new macros without interference from pre-existing
14329 uses of third-party macros.  Perhaps the best example of this confusion
14330 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14331 to Gettext.
14333 Most of the Autoconf macros' names follow a structured naming convention
14334 that indicates the kind of feature check by the name.  The macro names
14335 consist of several words, separated by underscores, going from most
14336 general to most specific.  The names of their cache variables use the
14337 same convention (@pxref{Cache Variable Names}, for more information on
14338 them).
14340 The first word of the name after the namespace initials (such as
14341 @samp{AC_}) usually tells the category
14342 of the feature being tested.  Here are the categories used in Autoconf for
14343 specific test macros, the kind of macro that you are more likely to
14344 write.  They are also used for cache variables, in all-lowercase.  Use
14345 them where applicable; where they're not, invent your own categories.
14347 @table @code
14348 @item C
14349 C language builtin features.
14350 @item DECL
14351 Declarations of C variables in header files.
14352 @item FUNC
14353 Functions in libraries.
14354 @item GROUP
14355 Posix group owners of files.
14356 @item HEADER
14357 Header files.
14358 @item LIB
14359 C libraries.
14360 @item PROG
14361 The base names of programs.
14362 @item MEMBER
14363 Members of aggregates.
14364 @item SYS
14365 Operating system features.
14366 @item TYPE
14367 C builtin or declared types.
14368 @item VAR
14369 C variables in libraries.
14370 @end table
14372 After the category comes the name of the particular feature being
14373 tested.  Any further words in the macro name indicate particular aspects
14374 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
14375 C compiler supports ISO Standard C.
14377 An internal macro should have a name that starts with an underscore;
14378 Autoconf internals should therefore start with @samp{_AC_}.
14379 Additionally, a macro that is an internal subroutine of another macro
14380 should have a name that starts with an underscore and the name of that
14381 other macro, followed by one or more words saying what the internal
14382 macro does.  For example, @code{AC_PATH_X} has internal macros
14383 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14385 @node Reporting Messages
14386 @section Reporting Messages
14387 @cindex Messages, from @command{autoconf}
14389 When macros statically diagnose abnormal situations, benign or fatal, it
14390 is possible to make @command{autoconf} detect the problem, and refuse to
14391 create @file{configure} in the case of an error.  The macros in this
14392 section are considered obsolescent, and new code should use M4sugar
14393 macros for this purpose, see @ref{Diagnostic Macros}.
14395 On the other hand, it is possible to want to detect errors when
14396 @command{configure} is run, which are dependent on the environment of
14397 the user rather than the maintainer.  For dynamic diagnostics, see
14398 @ref{Printing Messages}.
14400 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14401 @acindex{DIAGNOSE}
14402 Report @var{message} as a warning (or as an error if requested by the
14403 user) if warnings of the @var{category} are turned on.  This macro is
14404 obsolescent; you are encouraged to use:
14405 @example
14406 m4_warn([@var{category}], [@var{message}])
14407 @end example
14408 @noindent
14409 instead.  @xref{m4_warn}, for more details, including valid
14410 @var{category} names.
14411 @end defmac
14413 @defmac AC_WARNING (@var{message})
14414 @acindex{WARNING}
14415 Report @var{message} as a syntax warning.  This macro is obsolescent;
14416 you are encouraged to use:
14417 @example
14418 m4_warn([syntax], [@var{message}])
14419 @end example
14420 @noindent
14421 instead.  @xref{m4_warn}, for more details, as well as better
14422 finer-grained categories of warnings (not all problems have to do with
14423 syntax).
14424 @end defmac
14426 @defmac AC_FATAL (@var{message})
14427 @acindex{FATAL}
14428 Report a severe error @var{message}, and have @command{autoconf} die.
14429 This macro is obsolescent; you are encouraged to use:
14430 @example
14431 m4_fatal([@var{message}])
14432 @end example
14433 @noindent
14434 instead.  @xref{m4_fatal}, for more details.
14435 @end defmac
14437 When the user runs @samp{autoconf -W error}, warnings from
14438 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14439 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14441 @node Dependencies Between Macros
14442 @section Dependencies Between Macros
14443 @cindex Dependencies between macros
14445 Some Autoconf macros depend on other macros having been called first in
14446 order to work correctly.  Autoconf provides a way to ensure that certain
14447 macros are called if needed and a way to warn the user if macros are
14448 called in an order that might cause incorrect operation.
14450 @menu
14451 * Prerequisite Macros::         Ensuring required information
14452 * Suggested Ordering::          Warning about possible ordering problems
14453 * One-Shot Macros::             Ensuring a macro is called only once
14454 @end menu
14456 @node Prerequisite Macros
14457 @subsection Prerequisite Macros
14458 @cindex Prerequisite macros
14459 @cindex Macros, prerequisites
14461 A macro that you write might need to use values that have previously
14462 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14463 examines the output of @code{flex} or @code{lex}, so it depends on
14464 @code{AC_PROG_LEX} having been called first to set the shell variable
14465 @code{LEX}.
14467 Rather than forcing the user of the macros to keep track of the
14468 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14469 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14470 called if it is needed, and only called once.
14472 @defmac AC_REQUIRE (@var{macro-name})
14473 @acindex{REQUIRE}
14474 If the M4 macro @var{macro-name} has not already been called, call it
14475 (without any arguments).  Make sure to quote @var{macro-name} with
14476 square brackets.  @var{macro-name} must have been defined using
14477 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14478 that it has been called.
14480 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14481 must not be called from the top level.  Also, it does not make sense to
14482 require a macro that takes parameters.
14483 @end defmac
14485 @code{AC_REQUIRE} is often misunderstood.  It really implements
14486 dependencies between macros in the sense that if one macro depends upon
14487 another, the latter is expanded @emph{before} the body of the
14488 former.  To be more precise, the required macro is expanded before
14489 the outermost defined macro in the current expansion stack.
14490 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14491 @code{FOO}.  For instance, this definition of macros:
14493 @example
14494 @group
14495 AC_DEFUN([TRAVOLTA],
14496 [test "$body_temperature_in_celsius" -gt "38" &&
14497   dance_floor=occupied])
14498 AC_DEFUN([NEWTON_JOHN],
14499 [test "x$hair_style" = xcurly &&
14500   dance_floor=occupied])
14501 @end group
14503 @group
14504 AC_DEFUN([RESERVE_DANCE_FLOOR],
14505 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14506   AC_REQUIRE([TRAVOLTA])
14507   AC_REQUIRE([NEWTON_JOHN])
14508 fi])
14509 @end group
14510 @end example
14512 @noindent
14513 with this @file{configure.ac}
14515 @example
14516 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14517 RESERVE_DANCE_FLOOR
14518 if test "x$dance_floor" = xoccupied; then
14519   AC_MSG_ERROR([cannot pick up here, let's move])
14521 @end example
14523 @noindent
14524 does not leave you with a better chance to meet a kindred soul at
14525 other times than Saturday night since it expands into:
14527 @example
14528 @group
14529 test "$body_temperature_in_Celsius" -gt "38" &&
14530   dance_floor=occupied
14531 test "x$hair_style" = xcurly &&
14532   dance_floor=occupied
14534 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14538 @end group
14539 @end example
14541 This behavior was chosen on purpose: (i) it prevents messages in
14542 required macros from interrupting the messages in the requiring macros;
14543 (ii) it avoids bad surprises when shell conditionals are used, as in:
14545 @example
14546 @group
14547 if @dots{}; then
14548   AC_REQUIRE([SOME_CHECK])
14550 @dots{}
14551 SOME_CHECK
14552 @end group
14553 @end example
14555 However, this implementation can lead to another class of problems.
14556 Consider the case where an outer macro first expands, then indirectly
14557 requires, an inner macro:
14559 @example
14560 AC_DEFUN([TESTA], [[echo in A
14561 if test -n "$SEEN_A" ; then echo duplicate ; fi
14562 SEEN_A=:]])
14563 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14564 if test -z "$SEEN_A" ; then echo bug ; fi]])
14565 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14566 AC_DEFUN([OUTER], [[echo in OUTER]
14567 TESTA
14568 TESTC])
14569 OUTER
14570 @end example
14572 @noindent
14573 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14574 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14575 of @code{OUTER}, but because @code{TESTA} had already been directly
14576 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14577 @code{TESTB} occurs prior to its prerequisites, leading to the following
14578 output:
14580 @example
14581 in B
14583 in OUTER
14584 in A
14585 in C
14586 @end example
14588 @noindent
14589 Newer Autoconf is smart enough to recognize this situation, and hoists
14590 @code{TESTA} even though it has already been expanded, but issues a
14591 syntax warning in the process.  This is because the hoisted expansion of
14592 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14593 redundant code, and causes its own set of problems if the hoisted macro
14594 is not idempotent:
14596 @example
14597 in A
14598 in B
14599 in OUTER
14600 in A
14601 duplicate
14602 in C
14603 @end example
14605 The bug is not in Autoconf, but in the macro definitions.  If you ever
14606 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14607 that the macro only needs to be expanded once.  But to enforce this,
14608 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14609 this only helps in Autoconf 2.64 or newer), or all
14610 uses of that macro should be through @code{AC_REQUIRE}; directly
14611 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14612 eliminate redundant expansion.  In the example, this rule of thumb was
14613 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14614 directly expands it.  One way of fixing the bug is to factor
14615 @code{TESTA} into two macros, the portion designed for direct and
14616 repeated use (here, named @code{TESTA}), and the portion designed for
14617 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14618 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14619 calling convention according to their needs:
14621 @example
14622 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14623 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14624 if test -n "$SEEN_A" ; then echo duplicate ; fi
14625 SEEN_A=:]])
14626 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14627 if test -z "$SEEN_A" ; then echo bug ; fi]])
14628 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14629 AC_DEFUN([OUTER], [[echo in OUTER]
14630 TESTA
14631 TESTC])
14632 OUTER
14633 @end example
14635 @noindent
14636 the resulting output will then obey all dependency rules and avoid any
14637 syntax warnings, whether the script is built with old or new Autoconf
14638 versions:
14640 @example
14641 in A_PREREQ
14642 in B
14643 in OUTER
14644 in A
14645 in C
14646 @end example
14648 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14649 enforce expansion of required macros outside of shell conditional
14650 constructs.  You are furthermore encouraged, although not required, to
14651 put all @code{AC_REQUIRE} calls
14652 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14653 lines they leave.
14655 @node Suggested Ordering
14656 @subsection Suggested Ordering
14657 @cindex Macros, ordering
14658 @cindex Ordering macros
14660 Some macros should be run before another macro if both are called, but
14661 neither @emph{requires} that the other be called.  For example, a macro
14662 that changes the behavior of the C compiler should be called before any
14663 macros that run the C compiler.  Many of these dependencies are noted in
14664 the documentation.
14666 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14667 with this kind of dependency appear out of order in a
14668 @file{configure.ac} file.  The warning occurs when creating
14669 @command{configure} from @file{configure.ac}, not when running
14670 @command{configure}.
14672 For example, @code{AC_PROG_CPP} checks whether the C compiler
14673 can run the C preprocessor when given the @option{-E} option.  It should
14674 therefore be called after any macros that change which C compiler is
14675 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14677 @example
14678 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14679 @end example
14681 @noindent
14682 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14683 when @code{AC_PROG_CC} is called.
14685 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14686 @acindex{BEFORE}
14687 Make M4 print a warning message to the standard error output if
14688 @var{called-macro-name} has already been called.  @var{this-macro-name}
14689 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14690 macro @var{called-macro-name} must have been defined using
14691 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14692 that it has been called.
14693 @end defmac
14695 @node One-Shot Macros
14696 @subsection One-Shot Macros
14697 @cindex One-shot macros
14698 @cindex Macros, called once
14700 Some macros should be called only once, either because calling them
14701 multiple time is unsafe, or because it is bad style.  For instance
14702 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14703 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14704 sense to run these expensive checks more than once.  Such one-shot
14705 macros can be defined using @code{AC_DEFUN_ONCE}.
14707 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14708 @acindex{DEFUN_ONCE}
14709 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14710 Definitions}), but add additional logic that guarantees that only the
14711 first use of the macro (whether by direct expansion or
14712 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14713 expansion will occur before the start of any enclosing macro defined by
14714 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14715 Generally, it does not make sense for @var{macro-body} to use parameters
14716 such as @code{$1}.
14717 @end defmac
14719 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14720 emit a warning if it was directly expanded a second time, so for
14721 portability, it is better to use @code{AC_REQUIRE} than direct
14722 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14723 (@pxref{Prerequisite Macros}).
14725 @node Obsoleting Macros
14726 @section Obsoleting Macros
14727 @cindex Obsoleting macros
14728 @cindex Macros, obsoleting
14730 Configuration and portability technology has evolved over the years.
14731 Often better ways of solving a particular problem are developed, or
14732 ad-hoc approaches are systematized.  This process has occurred in many
14733 parts of Autoconf.  One result is that some of the macros are now
14734 considered @dfn{obsolete}; they still work, but are no longer considered
14735 the best thing to do, hence they should be replaced with more modern
14736 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14737 with their modern implementation.
14739 Autoconf provides a simple means to obsolete a macro.
14741 @anchor{AU_DEFUN}
14742 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14743 @auindex{DEFUN}
14744 Define @var{old-macro} as @var{implementation}.  The only difference
14745 with @code{AC_DEFUN} is that the user is warned that
14746 @var{old-macro} is now obsolete.
14748 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14749 replaced by the modern @var{implementation}.  @var{message} should
14750 include information on what to do after running @command{autoupdate};
14751 @command{autoupdate} prints it as a warning, and includes it
14752 in the updated @file{configure.ac} file.
14754 The details of this macro are hairy: if @command{autoconf} encounters an
14755 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14756 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14757 macros are expanded here, while all other macros are disabled and
14758 appear literally in the updated @file{configure.ac}.
14759 @end defmac
14761 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14762 @auindex{ALIAS}
14763 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14764 with the same parameters.  This happens for example if the macro was renamed.
14765 @end defmac
14767 @node Coding Style
14768 @section Coding Style
14769 @cindex Coding style
14771 The Autoconf macros follow a strict coding style.  You are encouraged to
14772 follow this style, especially if you intend to distribute your macro,
14773 either by contributing it to Autoconf itself or the
14774 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14775 Archive}, or by other means.
14777 The first requirement is to pay great attention to the quotation.  For
14778 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14780 Do not try to invent new interfaces.  It is likely that there is a macro
14781 in Autoconf that resembles the macro you are defining: try to stick to
14782 this existing interface (order of arguments, default values, etc.).  We
14783 @emph{are} conscious that some of these interfaces are not perfect;
14784 nevertheless, when harmless, homogeneity should be preferred over
14785 creativity.
14787 Be careful about clashes both between M4 symbols and between shell
14788 variables.
14790 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14791 you are unlikely to generate conflicts.  Nevertheless, when you need to
14792 set a special value, @emph{avoid using a regular macro name}; rather,
14793 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14794 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14795 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14796 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14797 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14798 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14799 have been used (yes, with the parentheses).
14800 @c or better yet, high-level macros such as @code{m4_expand_once}
14802 No Autoconf macro should ever enter the user-variable name space; i.e.,
14803 except for the variables that are the actual result of running the
14804 macro, all shell variables should start with @code{ac_}.  In
14805 addition, small macros or any macro that is likely to be embedded in
14806 other macros should be careful not to use obvious names.
14808 @cindex @code{dnl}
14809 Do not use @code{dnl} to introduce comments: most of the comments you
14810 are likely to write are either header comments which are not output
14811 anyway, or comments that should make their way into @file{configure}.
14812 There are exceptional cases where you do want to comment special M4
14813 constructs, in which case @code{dnl} is right, but keep in mind that it
14814 is unlikely.
14816 M4 ignores the leading blanks and newlines before each argument.
14817 Use this feature to
14818 indent in such a way that arguments are (more or less) aligned with the
14819 opening parenthesis of the macro being called.  For instance, instead of
14821 @example
14822 AC_CACHE_CHECK(for EMX OS/2 environment,
14823 ac_cv_emxos2,
14824 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14825 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14826 @end example
14828 @noindent
14829 write
14831 @example
14832 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14833 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14834                    [ac_cv_emxos2=yes],
14835                    [ac_cv_emxos2=no])])
14836 @end example
14838 @noindent
14839 or even
14841 @example
14842 AC_CACHE_CHECK([for EMX OS/2 environment],
14843                [ac_cv_emxos2],
14844                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14845                                                    [return __EMX__;])],
14846                                   [ac_cv_emxos2=yes],
14847                                   [ac_cv_emxos2=no])])
14848 @end example
14850 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14851 cross-compiling, provide a pessimistic value (typically @samp{no}).
14853 Feel free to use various tricks to prevent auxiliary tools, such as
14854 syntax-highlighting editors, from behaving improperly.  For instance,
14855 instead of:
14857 @example
14858 m4_bpatsubst([$1], [$"])
14859 @end example
14861 @noindent
14864 @example
14865 m4_bpatsubst([$1], [$""])
14866 @end example
14868 @noindent
14869 so that Emacsen do not open an endless ``string'' at the first quote.
14870 For the same reasons, avoid:
14872 @example
14873 test $[#] != 0
14874 @end example
14876 @noindent
14877 and use:
14879 @example
14880 test $[@@%:@@] != 0
14881 @end example
14883 @noindent
14884 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14885 breaking the bracket-matching highlighting from Emacsen.  Note the
14886 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14887 not escape when it is unnecessary.  Common examples of useless quotation
14888 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14889 etc.  If you add portability issues to the picture, you'll prefer
14890 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14891 better than hacking Autoconf @code{:-)}.
14893 When using @command{sed}, don't use @option{-e} except for indenting
14894 purposes.  With the @code{s} and @code{y} commands, the preferred
14895 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14896 or replacement, in which case you should use @samp{|}, or optionally
14897 @samp{,} if you know the pattern and replacement cannot contain a file
14898 name.  If none of these characters will do, choose a printable character
14899 that cannot appear in the pattern or replacement.  Characters from the
14900 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14901 replacement might contain a file name, since they have special meaning
14902 to the shell and are less likely to occur in file names.
14904 @xref{Macro Definitions}, for details on how to define a macro.  If a
14905 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14906 of an @code{AC_REQUIRE} directive, and macros required by other macros
14907 inside arguments do not need to be expanded before this macro, then
14908 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14909 Also take into account that public third-party macros need to use
14910 @code{AC_DEFUN} in order to be found by @command{aclocal}
14911 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14912 All the @code{AC_REQUIRE} statements should be at the beginning of the
14913 macro, and each statement should be followed by @code{dnl}.
14915 You should not rely on the number of arguments: instead of checking
14916 whether an argument is missing, test that it is not empty.  It provides
14917 both a simpler and a more predictable interface to the user, and saves
14918 room for further arguments.
14920 Unless the macro is short, try to leave the closing @samp{])} at the
14921 beginning of a line, followed by a comment that repeats the name of the
14922 macro being defined.  This introduces an additional newline in
14923 @command{configure}; normally, that is not a problem, but if you want to
14924 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14925 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14926 is recommended instead of @samp{dnl} to ensure that M4 does not
14927 interpret the @samp{dnl} as being attached to the preceding text or
14928 macro output.  For example, instead of:
14930 @example
14931 AC_DEFUN([AC_PATH_X],
14932 [AC_MSG_CHECKING([for X])
14933 AC_REQUIRE_CPP()
14934 @r{# @dots{}omitted@dots{}}
14935   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14936 fi])
14937 @end example
14939 @noindent
14940 you would write:
14942 @example
14943 AC_DEFUN([AC_PATH_X],
14944 [AC_REQUIRE_CPP()[]dnl
14945 AC_MSG_CHECKING([for X])
14946 @r{# @dots{}omitted@dots{}}
14947   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14948 fi[]dnl
14949 ])# AC_PATH_X
14950 @end example
14952 If the macro is long, try to split it into logical chunks.  Typically,
14953 macros that check for a bug in a function and prepare its
14954 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14955 this setup.  Do not hesitate to introduce auxiliary macros to factor
14956 your code.
14958 In order to highlight the recommended coding style, here is a macro
14959 written the old way:
14961 @example
14962 dnl Check for EMX on OS/2.
14963 dnl _AC_EMXOS2
14964 AC_DEFUN(_AC_EMXOS2,
14965 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
14966 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
14967 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
14968 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
14969 @end example
14971 @noindent
14972 and the new way:
14974 @example
14975 # _AC_EMXOS2
14976 # ----------
14977 # Check for EMX on OS/2.
14978 m4_define([_AC_EMXOS2],
14979 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14980 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14981                    [ac_cv_emxos2=yes],
14982                    [ac_cv_emxos2=no])])
14983 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
14984 ])# _AC_EMXOS2
14985 @end example
14990 @c ============================================= Portable Shell Programming
14992 @node Portable Shell
14993 @chapter Portable Shell Programming
14994 @cindex Portable shell programming
14996 When writing your own checks, there are some shell-script programming
14997 techniques you should avoid in order to make your code portable.  The
14998 Bourne shell and upward-compatible shells like the Korn shell and Bash
14999 have evolved over the years, and many features added to the original
15000 System7 shell are now supported on all interesting porting targets.
15001 However, the following discussion between Russ Allbery and Robert Lipe
15002 is worth reading:
15004 @noindent
15005 Russ Allbery:
15007 @quotation
15008 The GNU assumption that @command{/bin/sh} is the one and only shell
15009 leads to a permanent deadlock.  Vendors don't want to break users'
15010 existing shell scripts, and there are some corner cases in the Bourne
15011 shell that are not completely compatible with a Posix shell.  Thus,
15012 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15013 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15014 Posix shell.
15015 @end quotation
15017 @noindent
15018 Robert Lipe:
15020 @quotation
15021 This is exactly the problem.  While most (at least most System V's) do
15022 have a Bourne shell that accepts shell functions most vendor
15023 @command{/bin/sh} programs are not the Posix shell.
15025 So while most modern systems do have a shell @emph{somewhere} that meets the
15026 Posix standard, the challenge is to find it.
15027 @end quotation
15029 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15030 is to find such a shell.  But to prevent trouble, if you're not using
15031 M4sh you should not take advantage of features that were added after Unix
15032 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15033 negated character classes, or even @command{unset}.  @code{#} comments,
15034 while not in Unix version 7, were retrofitted in the original Bourne
15035 shell and can be assumed to be part of the least common denominator.
15037 On the other hand, if you're using M4sh you can assume that the shell
15038 has the features that were added in SVR2 (circa 1984), including shell
15039 functions,
15040 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15041 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15042 However, some pitfalls have to be avoided for portable use of these
15043 constructs; these will be documented in the rest of this chapter.
15044 See in particular @ref{Shell Functions} and @ref{Limitations of
15045 Builtins, , Limitations of Shell Builtins}.
15047 Some ancient systems have quite
15048 small limits on the length of the @samp{#!} line; for instance, 32
15049 bytes (not including the newline) on SunOS 4.
15050 However, these ancient systems are no longer of practical concern.
15052 The set of external programs you should run in a @command{configure} script
15053 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15054 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15055 restriction allows users to start out with a fairly small set of
15056 programs and build the rest, avoiding too many interdependencies between
15057 packages.
15059 Some of these external utilities have a portable subset of features; see
15060 @ref{Limitations of Usual Tools}.
15062 There are other sources of documentation about shells.  The
15063 specification for the Posix
15064 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15065 Command Language}, though more generous than the restrictive shell
15066 subset described above, is fairly portable nowadays.  Also please see
15067 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15069 @menu
15070 * Shellology::                  A zoology of shells
15071 * Here-Documents::              Quirks and tricks
15072 * File Descriptors::            FDs and redirections
15073 * File System Conventions::     File names
15074 * Shell Pattern Matching::      Pattern matching
15075 * Shell Substitutions::         Variable and command expansions
15076 * Assignments::                 Varying side effects of assignments
15077 * Parentheses::                 Parentheses in shell scripts
15078 * Slashes::                     Slashes in shell scripts
15079 * Special Shell Variables::     Variables you should not change
15080 * Shell Functions::             What to look out for if you use them
15081 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15082 * Limitations of Usual Tools::  Portable use of portable tools
15083 @end menu
15085 @node Shellology
15086 @section Shellology
15087 @cindex Shellology
15089 There are several families of shells, most prominently the Bourne family
15090 and the C shell family which are deeply incompatible.  If you want to
15091 write portable shell scripts, avoid members of the C shell family.  The
15092 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15093 Shell difference FAQ} includes a small history of Posix shells, and a
15094 comparison between several of them.
15096 Below we describe some of the members of the Bourne shell family.
15098 @table @asis
15099 @item Ash
15100 @cindex Ash
15101 Ash is often used on GNU/Linux and BSD
15102 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15103 bugs that are fixed in the 0.3.x series, but portable shell scripts
15104 should work around them, since version 0.2 is still shipped with many
15105 GNU/Linux distributions.
15107 To be compatible with Ash 0.2:
15109 @itemize @minus
15110 @item
15111 don't use @samp{$?} after expanding empty or unset variables,
15112 or at the start of an @command{eval}:
15114 @example
15115 foo=
15116 false
15117 $foo
15118 echo "Do not use it: $?"
15119 false
15120 eval 'echo "Do not use it: $?"'
15121 @end example
15123 @item
15124 don't use command substitution within variable expansion:
15126 @example
15127 cat $@{FOO=`bar`@}
15128 @end example
15130 @item
15131 beware that single builtin substitutions are not performed by a
15132 subshell, hence their effect applies to the current shell!  @xref{Shell
15133 Substitutions}, item ``Command Substitution''.
15134 @end itemize
15136 @item Bash
15137 @cindex Bash
15138 To detect whether you are running Bash, test whether
15139 @code{BASH_VERSION} is set.  To require
15140 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15141 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15142 Manual}, for details.
15144 @item Bash 2.05 and later
15145 @cindex Bash 2.05 and later
15146 Versions 2.05 and later of Bash use a different format for the
15147 output of the @command{set} builtin, designed to make evaluating its
15148 output easier.  However, this output is not compatible with earlier
15149 versions of Bash (or with many other shells, probably).  So if
15150 you use Bash 2.05 or higher to execute @command{configure},
15151 you'll need to use Bash 2.05 for all other build tasks as well.
15153 @item Ksh
15154 @cindex Ksh
15155 @cindex Korn shell
15156 @prindex @samp{ksh}
15157 @prindex @samp{ksh88}
15158 @prindex @samp{ksh93}
15159 The Korn shell is compatible with the Bourne family and it mostly
15160 conforms to Posix.  It has two major variants commonly
15161 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15162 release.  It is usually called @command{ksh}, but is called @command{sh}
15163 on some hosts if you set your path appropriately.
15165 Solaris systems have three variants:
15166 @prindex @command{/usr/bin/ksh} on Solaris
15167 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15168 standard on Solaris 2.0 and later.
15169 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15170 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15171 @samp{ksh88}; it is standard on Solaris 9 and later.
15172 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15173 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15174 Variants that are not standard may be parts of optional
15175 packages.  There is no extra charge for these packages, but they are
15176 not part of a minimal OS install and therefore some installations may
15177 not have it.
15179 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15180 is also available as @command{/usr/bin/posix/sh}.  If the environment
15181 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15182 the standard shell conform to Posix.
15184 @item Pdksh
15185 @prindex @samp{pdksh}
15186 A public-domain clone of the Korn shell called @command{pdksh} is widely
15187 available: it has most of the @samp{ksh88} features along with a few of
15188 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15189 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15190 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15191 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15192 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15193 at least one respect, see @ref{Shell Substitutions}.
15195 @item Zsh
15196 @cindex Zsh
15197 To detect whether you are running @command{zsh}, test whether
15198 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15199 compatible with the Bourne shell: you must execute @samp{emulate sh},
15200 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15201 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15202 zsh, The Z Shell Manual}, for details.
15204 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15205 Bash in Mac OS X 10.2.
15206 @end table
15208 @node Here-Documents
15209 @section Here-Documents
15210 @cindex Here-documents
15211 @cindex Shell here-documents
15213 Don't rely on @samp{\} being preserved just because it has no special
15214 meaning together with the next symbol.  In the native @command{sh}
15215 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15216 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15217 use @samp{\\} to get @samp{\}.
15219 With OpenBSD 2.7's @command{sh}
15221 @example
15222 @group
15223 $ @kbd{cat <<EOF
15224 > \" \\
15225 > EOF}
15226 " \
15227 @end group
15228 @end example
15230 @noindent
15231 and with Bash:
15233 @example
15234 @group
15235 bash-2.04$ @kbd{cat <<EOF
15236 > \" \\
15237 > EOF}
15238 \" \
15239 @end group
15240 @end example
15242 Some shells mishandle large here-documents: for example,
15243 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15244 derived from Korn shell version M-12/28/93d, mishandle braced variable
15245 expansion that crosses a 1024- or 4096-byte buffer boundary
15246 within a here-document.  Only the part of the variable name after the boundary
15247 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15248 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15249 boundary, the shell reports an error, as if you used @code{$@{@}}.
15250 Instead of @code{$@{variable-default@}}, the shell may expand
15251 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15252 be worked around by omitting the braces: @code{$variable}.  The bug was
15253 fixed in
15254 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15255 still shipping older versions with the bug.
15257 Empty here-documents are not portable either; with the following code,
15258 @command{zsh} up to at least version 4.3.10 creates a file with a single
15259 newline, whereas other shells create an empty file:
15261 @example
15262 cat >file <<EOF
15264 @end example
15266 Many shells (including the Bourne shell) implement here-documents
15267 inefficiently.  In particular, some shells can be extremely inefficient when
15268 a single statement contains many here-documents.  For instance if your
15269 @file{configure.ac} includes something like:
15271 @example
15272 @group
15273 if <cross_compiling>; then
15274   assume this and that
15275 else
15276   check this
15277   check that
15278   check something else
15279   @dots{}
15280   on and on forever
15281   @dots{}
15283 @end group
15284 @end example
15286 A shell parses the whole @code{if}/@code{fi} construct, creating
15287 temporary files for each here-document in it.  Some shells create links
15288 for such here-documents on every @code{fork}, so that the clean-up code
15289 they had installed correctly removes them.  It is creating the links
15290 that can take the shell forever.
15292 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15293 @code{if}/@code{fi} constructs, would improve the performance
15294 significantly.  Anyway, this kind of construct is not exactly the
15295 typical use of Autoconf.  In fact, it's even not recommended, because M4
15296 macros can't look into shell conditionals, so we may fail to expand a
15297 macro when it was expanded before in a conditional path, and the
15298 condition turned out to be false at runtime, and we end up not
15299 executing the macro at all.
15301 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15302 behavior is only portable for stripping leading @key{TAB}s, and things
15303 can silently break if an overzealous editor converts to using leading
15304 spaces (not all shells are nice enough to warn about unterminated
15305 here-documents).
15307 @example
15308 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15311 done
15312 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15314   2
15316 done
15317 @end example
15319 @node File Descriptors
15320 @section File Descriptors
15321 @cindex Descriptors
15322 @cindex File descriptors
15323 @cindex Shell file descriptors
15325 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15326 stderr, even for subshells.  This might result in undesirable content
15327 if you meant to capture the standard-error output of the inner command:
15329 @example
15330 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15331 $ @kbd{cat stderr}
15332 + eval echo foo >&2
15333 + echo foo
15335 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15336 $ @kbd{cat stderr}
15337 + eval 'echo foo >&2'
15338 ++ echo foo
15340 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15341 @i{# Traces on startup files deleted here.}
15342 $ @kbd{cat stderr}
15343 +zsh:1> eval echo foo >&2
15344 +zsh:1> echo foo
15346 @end example
15348 @noindent
15349 One workaround is to grep out uninteresting lines, hoping not to remove
15350 good ones.
15352 If you intend to redirect both standard error and standard output,
15353 redirect standard output first.  This works better with HP-UX,
15354 since its shell mishandles tracing if standard error is redirected
15355 first:
15357 @example
15358 $ @kbd{sh -x -c ': 2>err >out'}
15359 + :
15360 + 2> err $ @kbd{cat err}
15361 1> out
15362 @end example
15364 Don't try to redirect the standard error of a command substitution.  It
15365 must be done @emph{inside} the command substitution.  When running
15366 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15367 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15369 On the other hand, some shells, such as Solaris or FreeBSD
15370 @command{/bin/sh}, warn about missing programs before performing
15371 redirections.  Therefore, to silently check whether a program exists, it
15372 is necessary to perform redirections on a subshell or brace group:
15373 @example
15374 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15375 nosuch: not found
15376 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15377 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15378 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15379 @end example
15381 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15382 shell pipeline.
15384 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15385 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15387 Some shells, like @command{ash}, don't recognize bi-directional
15388 redirection (@samp{<>}).  And even on shells that recognize it, it is
15389 not portable to use on fifos: Posix does not require read-write support
15390 for named pipes, and Cygwin does not support it:
15392 @example
15393 $ @kbd{mkfifo fifo}
15394 $ @kbd{exec 5<>fifo}
15395 $ @kbd{echo hi >&5}
15396 bash: echo: write error: Communication error on send
15397 @end example
15399 @noindent
15400 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15401 regular files when using @samp{<>}:
15403 @example
15404 $ @kbd{echo a > file}
15405 $ @kbd{bash -c ': 1<>file'; cat file}
15407 $ @kbd{dash -c ': 1<>file'; cat file}
15408 $ rm a
15409 @end example
15411 When catering to old systems, don't redirect the same file descriptor
15412 several times, as you are doomed to failure under Ultrix.
15414 @example
15415 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15416 UWS V4.4 (Rev. 11)
15417 $ @kbd{eval 'echo matter >fullness' >void}
15418 illegal io
15419 $ @kbd{eval '(echo matter >fullness)' >void}
15420 illegal io
15421 $ @kbd{(eval '(echo matter >fullness)') >void}
15422 Ambiguous output redirect.
15423 @end example
15425 @noindent
15426 In each case the expected result is of course @file{fullness} containing
15427 @samp{matter} and @file{void} being empty.  However, this bug is
15428 probably not of practical concern to modern platforms.
15430 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15431 in a loop after the first iteration, even if it is redirected:
15433 @example
15434 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15435 $ @kbd{ls}
15437 @end example
15439 @noindent
15440 As a workaround, @command{echo} or @command{eval} can be used.
15442 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15443 subsidiary program.  If any of these descriptors is closed, the
15444 operating system may open an unspecified file for the descriptor in the
15445 new process image.  Posix 2008 says this may be done only if the
15446 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15447 it even for ordinary programs, and the next version of Posix will allow
15448 HP-UX behavior.
15450 If you want a file descriptor above 2 to be inherited into a child
15451 process, then you must use redirections specific to that command or a
15452 containing subshell or command group, rather than relying on
15453 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15454 @command{sh}, file descriptors above 2 which are opened using
15455 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15456 that involved in the fork-and-exec which runs a program or script):
15458 @example
15459 $ @kbd{echo 'echo hello >&5' >k}
15460 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15461 hello
15462 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15463 hello
15464 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15465 ./k[1]: 5: cannot open [Bad file number]
15466 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15467 hello
15468 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15469 hello
15470 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15471 hello
15472 @end example
15474 Don't rely on duplicating a closed file descriptor to cause an
15475 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15476 ignored, which can cause unintended leaks to the original file
15477 descriptor.  In this example, observe the leak to standard output:
15479 @example
15480 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15481 bash: 3: Bad file descriptor
15483 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15486 @end example
15488 Fortunately, an attempt to close an already closed file descriptor will
15489 portably succeed.  Likewise, it is safe to use either style of
15490 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15491 even if it doesn't match the read/write mode that the file descriptor
15492 was opened with.
15494 DOS variants cannot rename or remove open files, such as in
15495 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15496 perfectly portable among Posix hosts.
15498 A few ancient systems reserved some file descriptors.  By convention,
15499 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15500 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15501 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15502 1990), though we don't now remember what it was.  Both these systems are
15503 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15504 other file descriptors.
15506 On the other hand, you can't portably use multi-digit file descriptors.
15507 Solaris @command{ksh} doesn't understand any file descriptor larger than
15508 @samp{9}:
15510 @example
15511 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15513 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15515 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15516 ksh[1]: exec: 10: not found
15518 @end example
15520 @node File System Conventions
15521 @section File System Conventions
15522 @cindex File system conventions
15524 Autoconf uses shell-script processing extensively, so the file names
15525 that it processes should not contain characters that are special to the
15526 shell.  Special characters include space, tab, newline, NUL, and
15527 the following:
15529 @example
15530 " # $ & ' ( ) * ; < = > ? [ \ ` |
15531 @end example
15533 Also, file names should not begin with @samp{~} or @samp{-}, and should
15534 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15535 immediately after @samp{:}.  On Posix-like platforms, directory names
15536 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15537 path separator.
15539 These restrictions apply not only to the files that you distribute, but
15540 also to the absolute file names of your source, build, and destination
15541 directories.
15543 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15544 they should be avoided.
15546 Posix lets implementations treat leading @file{//} specially, but
15547 requires leading @file{///} and beyond to be equivalent to @file{/}.
15548 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15549 @file{//} as a ``super-root'' that can provide access to files that are
15550 not otherwise reachable from @file{/}.  The super-root tradition began
15551 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15552 has revived it.
15554 While @command{autoconf} and friends are usually run on some Posix
15555 variety, they can be used on other systems, most notably DOS
15556 variants.  This impacts several assumptions regarding file names.
15558 @noindent
15559 For example, the following code:
15561 @example
15562 case $foo_dir in
15563   /*) # Absolute
15564      ;;
15565   *)
15566      foo_dir=$dots$foo_dir ;;
15567 esac
15568 @end example
15570 @noindent
15571 fails to properly detect absolute file names on those systems, because
15572 they can use a drivespec, and usually use a backslash as directory
15573 separator.  If you want to be portable to DOS variants (at the
15574 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15575 you can check for absolute file names like this:
15577 @cindex absolute file names, detect
15578 @example
15579 case $foo_dir in
15580   [\\/]* | ?:[\\/]* ) # Absolute
15581      ;;
15582   *)
15583      foo_dir=$dots$foo_dir ;;
15584 esac
15585 @end example
15587 @noindent
15588 Make sure you quote the brackets if appropriate and keep the backslash as
15589 first character (@pxref{case, , Limitations of Shell Builtins}).
15591 Also, because the colon is used as part of a drivespec, these systems don't
15592 use it as path separator.  When creating or accessing paths, you can use the
15593 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15594 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15595 starts up.
15597 File names need extra care as well.  While DOS variants
15598 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15599 are usually able to handle long file names properly, there are still
15600 limitations that can seriously break packages.  Several of these issues
15601 can be easily detected by the
15602 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15603 package.
15605 A short overview follows; problems are marked with SFN/LFN to
15606 indicate where they apply: SFN means the issues are only relevant to
15607 plain DOS, not to DOS under Microsoft Windows
15608 variants, while LFN identifies problems that exist even under
15609 Microsoft Windows variants.
15611 @table @asis
15612 @item No multiple dots (SFN)
15613 DOS cannot handle multiple dots in file names.  This is an especially
15614 important thing to remember when building a portable configure script,
15615 as @command{autoconf} uses a .in suffix for template files.
15617 This is perfectly OK on Posix variants:
15619 @example
15620 AC_CONFIG_HEADERS([config.h])
15621 AC_CONFIG_FILES([source.c foo.bar])
15622 AC_OUTPUT
15623 @end example
15625 @noindent
15626 but it causes problems on DOS, as it requires @samp{config.h.in},
15627 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15628 to DOS-based environments, you should use this instead:
15630 @example
15631 AC_CONFIG_HEADERS([config.h:config.hin])
15632 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15633 AC_OUTPUT
15634 @end example
15636 @item No leading dot (SFN)
15637 DOS cannot handle file names that start with a dot.  This is usually
15638 not important for @command{autoconf}.
15640 @item Case insensitivity (LFN)
15641 DOS is case insensitive, so you cannot, for example, have both a
15642 file called @samp{INSTALL} and a directory called @samp{install}.  This
15643 also affects @command{make}; if there's a file called @samp{INSTALL} in
15644 the directory, @samp{make install} does nothing (unless the
15645 @samp{install} target is marked as PHONY).
15647 @item The 8+3 limit (SFN)
15648 Because the DOS file system only stores the first 8 characters of
15649 the file name and the first 3 of the extension, those must be unique.
15650 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15651 @file{foobar-prettybird.c} all resolve to the same file name
15652 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15653 @file{foo.bartender}.
15655 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15656 uses numeric
15657 tails in the short version of file names to make them unique.  However, a
15658 registry setting can turn this behavior off.  While this makes it
15659 possible to share file trees containing long file names between SFN
15660 and LFN environments, it also means the above problem applies there
15661 as well.
15663 @item Invalid characters (LFN)
15664 Some characters are invalid in DOS file names, and should therefore
15665 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15666 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15667 In a SFN environment, other characters are also invalid.  These
15668 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15670 @item Invalid names (LFN)
15671 Some DOS file names are reserved, and cause problems if you
15672 try to use files with those names.  These names include @file{CON},
15673 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15674 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15675 File names are case insensitive, so even names like
15676 @file{aux/config.guess} are disallowed.
15678 @end table
15680 @node Shell Pattern Matching
15681 @section Shell Pattern Matching
15682 @cindex Shell pattern matching
15684 Nowadays portable patterns can use negated character classes like
15685 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15686 some shells but not others; hence portable scripts should never use
15687 @samp{^} as the first character of a bracket pattern.
15689 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15690 they may match characters that are not lower-case letters.
15692 @node Shell Substitutions
15693 @section Shell Substitutions
15694 @cindex Shell substitutions
15696 Contrary to a persistent urban legend, the Bourne shell does not
15697 systematically split variables and back-quoted expressions, in particular
15698 on the right-hand side of assignments and in the argument of @code{case}.
15699 For instance, the following code:
15701 @example
15702 case "$given_srcdir" in
15703 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15704 *)  top_srcdir="$dots$given_srcdir" ;;
15705 esac
15706 @end example
15708 @noindent
15709 is more readable when written as:
15711 @example
15712 case $given_srcdir in
15713 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15714 *)  top_srcdir=$dots$given_srcdir ;;
15715 esac
15716 @end example
15718 @noindent
15719 and in fact it is even @emph{more} portable: in the first case of the
15720 first attempt, the computation of @code{top_srcdir} is not portable,
15721 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15722 for example Solaris 10 ksh:
15724 @example
15725 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15726 ksh: : cannot execute
15727 ksh: bar | sed 's, ,,': cannot execute
15728 @end example
15730 @noindent
15731 Posix does not specify behavior for this sequence.  On the other hand,
15732 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15733 but in practice, not all shells understand it the same way: pdksh 5.2.14
15734 prints spurious quotes when in Posix mode:
15736 @example
15737 $ @kbd{echo "`echo \"hello\"`"}
15738 hello
15739 $ @kbd{set -o posix}
15740 $ @kbd{echo "`echo \"hello\"`"}
15741 "hello"
15742 @end example
15744 @noindent
15745 There is just no portable way to use double-quoted strings inside
15746 double-quoted back-quoted expressions (pfew!).
15748 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15749 parameter expansions are elided during word splitting.  Meanwhile, zsh
15750 does not perform word splitting except when in Bourne compatibility
15751 mode.  In the example below, the correct behavior is to have five
15752 arguments to the function, and exactly two spaces on either side of the
15753 middle @samp{-}, since word splitting collapses multiple spaces in
15754 @samp{$f} but leaves empty arguments intact.
15756 @example
15757 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15758 3- - -
15759 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15760 5-  -  -
15761 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15762 3-   -   -
15763 $ @kbd{zsh -c 'emulate sh;}
15764 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
15765 5-  -  -
15766 @end example
15768 @noindent
15769 You can work around this by doing manual word splitting, such as using
15770 @samp{"$str" $list} rather than @samp{"$str"$list}.
15772 There are also portability pitfalls with particular expansions:
15774 @table @code
15775 @item $@@
15776 @cindex @code{"$@@"}
15777 One of the most famous shell-portability issues is related to
15778 @samp{"$@@"}.  When there are no positional arguments, Posix says
15779 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
15780 original Unix version 7 Bourne shell treated it as equivalent to
15781 @samp{""} instead, and this behavior survives in later implementations
15782 like Digital Unix 5.0.
15784 The traditional way to work around this portability problem is to use
15785 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
15786 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
15787 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
15789 @example
15790 zsh $ @kbd{emulate sh}
15791 zsh $ @kbd{for i in "$@@"; do echo $i; done}
15792 Hello World
15794 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
15795 Hello
15796 World
15798 @end example
15800 @noindent
15801 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
15802 @samp{"$@@"} because of the portability problems mentioned above.
15803 One workaround relies on Zsh's ``global aliases'' to convert
15804 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
15806 @example
15807 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
15808 @end example
15810 Zsh only recognizes this alias when a shell word matches it exactly;
15811 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
15812 case always yields at least one shell word, use plain @samp{"$@@"}.
15814 A more conservative workaround is to avoid @samp{"$@@"} if it is
15815 possible that there may be no positional arguments.  For example,
15816 instead of:
15818 @example
15819 cat conftest.c "$@@"
15820 @end example
15822 you can use this instead:
15824 @example
15825 case $# in
15826 0) cat conftest.c;;
15827 *) cat conftest.c "$@@";;
15828 esac
15829 @end example
15831 Autoconf macros often use the @command{set} command to update
15832 @samp{$@@}, so if you are writing shell code intended for
15833 @command{configure} you should not assume that the value of @samp{$@@}
15834 persists for any length of time.
15837 @item $@{10@}
15838 @cindex positional parameters
15839 The 10th, 11th, @dots{} positional parameters can be accessed only after
15840 a @code{shift}.  The 7th Edition shell reported an error if given
15841 @code{$@{10@}}, and
15842 Solaris 10 @command{/bin/sh} still acts that way:
15844 @example
15845 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
15846 $ @kbd{echo $@{10@}}
15847 bad substitution
15848 @end example
15850 Conversely, not all shells obey the Posix rule that when braces are
15851 omitted, multiple digits beyond a @samp{$} imply the single-digit
15852 positional parameter expansion concatenated with the remaining literal
15853 digits.  To work around the issue, you must use braces.
15855 @example
15856 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
15857 a0 a0
15858 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
15859 j a0
15860 @end example
15862 @item $@{@var{var}:-@var{value}@}
15863 @c Info cannot handle `:' in index entries.
15864 @ifnotinfo
15865 @cindex @code{$@{@var{var}:-@var{value}@}}
15866 @end ifnotinfo
15867 @cindex @code{$@{@var{var}-@var{value}@}}
15868 Old BSD shells, including the Ultrix @code{sh}, don't accept the
15869 colon for any shell substitution, and complain and die.
15870 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
15871 However, all shells that support functions allow the use of colon in
15872 shell substitution, and since m4sh requires functions, you can portably
15873 use null variable substitution patterns in configure scripts.
15875 @item $@{@var{var}+@var{value}@}
15876 @cindex @code{$@{@var{var}+@var{value}@}}
15877 When using @samp{$@{@var{var}-@var{value}@}} or
15878 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
15879 @var{value} must either be a single shell word, quoted, or in the
15880 context of an unquoted here-document.  Solaris
15881 @command{/bin/sh} complains otherwise.
15883 @example
15884 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
15885 /bin/sh: bad substitution
15886 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
15887 b c
15888 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
15889 b c
15890 $ @kbd{/bin/sh -c 'cat <<EOF
15891 $@{a-b c@}
15892 EOF}
15893 b c
15894 @end example
15896 According to Posix, if an expansion occurs inside double quotes, then
15897 the use of unquoted double quotes within @var{value} is unspecified, and
15898 any single quotes become literal characters; in that case, escaping must
15899 be done with backslash.  Likewise, the use of unquoted here-documents is
15900 a case where double quotes have unspecified results:
15902 @example
15903 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
15904 /bin/sh: bad substitution
15905 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
15906 b c
15907 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
15908 b  c
15909 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
15910 b  c
15911 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
15912 'b  c'
15913 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
15914 "b  c"
15915 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
15916 b  c
15917 $ @kbd{/bin/sh -c 'cat <<EOF
15918 $@{a-"b  c"@}
15919 EOF'}
15920 "b  c"
15921 $ @kbd{/bin/sh -c 'cat <<EOF
15922 $@{a-'b  c'@}
15923 EOF'}
15924 'b  c'
15925 $ @kbd{bash -c 'cat <<EOF
15926 $@{a-"b  c"@}
15927 EOF'}
15928 b  c
15929 $ @kbd{bash -c 'cat <<EOF
15930 $@{a-'b  c'@}
15931 EOF'}
15932 'b  c'
15933 @end example
15935 Perhaps the easiest way to work around quoting issues in a manner
15936 portable to all shells is to place the results in a temporary variable,
15937 then use @samp{$t} as the @var{value}, rather than trying to inline
15938 the expression needing quoting.
15940 @example
15941 $ @kbd{/bin/sh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15942 b  c"'@}\
15943 $ @kbd{ksh -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15944 b  c"'@}\
15945 $ @kbd{bash -c 't="a  b\"'\''@}\\"; echo "$@{a-$t@}"'}
15946 b  c"'@}\
15947 @end example
15949 @item $@{@var{var}=@var{value}@}
15950 @cindex @code{$@{@var{var}=@var{value}@}}
15951 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
15952 to @var{var}, remember that even though the assignment to @var{var} does
15953 not undergo file name expansion, the result of the variable expansion
15954 does unless the expansion occurred within double quotes.  In particular,
15955 when using @command{:} followed by unquoted variable expansion for the
15956 side effect of setting a default value, if the final value of
15957 @samp{$var} contains any globbing characters (either from @var{value} or
15958 from prior contents), the shell has to spend time performing file name
15959 expansion and field splitting even though those results will not be
15960 used.  Therefore, it is a good idea to consider double quotes when performing
15961 default initialization; while remembering how this impacts any quoting
15962 characters appearing in @var{value}.
15964 @example
15965 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
15966 /usr/bin/*
15968 real    0m0.005s
15969 user    0m0.002s
15970 sys     0m0.003s
15971 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
15972 /usr/bin/*
15974 real    0m0.039s
15975 user    0m0.026s
15976 sys     0m0.009s
15977 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
15978 /usr/bin/*
15980 real    0m0.031s
15981 user    0m0.020s
15982 sys     0m0.010s
15984 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
15985 /usr/bin/*
15987 real    0m0.006s
15988 user    0m0.002s
15989 sys     0m0.003s
15990 @end example
15992 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
15993 if the @var{value} contains more than one shell word; either single
15994 quotes for just the @var{value}, or double quotes around the entire
15995 expansion:
15997 @example
15998 $ @kbd{: $@{var1='Some words'@}}
15999 $ @kbd{: "$@{var2=like this@}"}
16000 $ @kbd{echo $var1 $var2}
16001 Some words like this
16002 @end example
16004 @noindent
16005 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16006 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16007 requires that with @samp{=}, quote removal happens prior to the
16008 assignment, and the expansion be the final contents of @var{var} without
16009 quoting (and thus subject to field splitting), in contrast to the
16010 behavior with @samp{-} passing the quoting through to the final
16011 expansion.  However, @command{bash} 4.1 does not obey this rule.
16013 @example
16014 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16015 a  b
16016 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16017 a b
16018 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16019 a  b
16020 @end example
16022 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16023 commands, it is unspecified whether the assignments affect the parent
16024 shell environment.  It is best to perform assignments independently from
16025 commands, to avoid the problems demonstrated in this example:
16027 @example
16028 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16029 +b+b+
16031 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16032 ++b+
16034 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16035 +b+b+
16037 @end example
16039 @item $@{@var{var}=@var{value}@}
16040 @cindex @code{$@{@var{var}=@var{literal}@}}
16041 Solaris @command{/bin/sh} has a frightening bug in its handling of
16042 literal assignments.  Imagine you need set a variable to a string containing
16043 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16044 when the affected variable was already set.  This bug can be exercised
16045 by running:
16047 @example
16048 $ @kbd{unset foo}
16049 $ @kbd{foo=$@{foo='@}'@}}
16050 $ @kbd{echo $foo}
16052 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16053 $ @kbd{echo $foo}
16055 $ @kbd{foo=$@{foo='@}'@}}
16056 $ @kbd{echo $foo}
16057 @}@}
16058  ^ ugh!
16059 @end example
16061 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16062 though it is enclosed in single quotes.  The problem doesn't happen
16063 using double quotes, or when using a temporary variable holding the
16064 problematic string.
16066 @item $@{@var{var}=@var{expanded-value}@}
16067 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16068 On Ultrix,
16069 running
16071 @example
16072 default="yu,yaa"
16073 : $@{var="$default"@}
16074 @end example
16076 @noindent
16077 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16078 each char is set.  You don't observe the phenomenon using a simple
16079 @samp{echo $var} since apparently the shell resets the 8th bit when it
16080 expands $var.  Here are two means to make this shell confess its sins:
16082 @example
16083 $ @kbd{cat -v <<EOF
16084 $var
16085 EOF}
16086 @end example
16088 @noindent
16091 @example
16092 $ @kbd{set | grep '^var=' | cat -v}
16093 @end example
16095 One classic incarnation of this bug is:
16097 @example
16098 default="a b c"
16099 : $@{list="$default"@}
16100 for c in $list; do
16101   echo $c
16102 done
16103 @end example
16105 @noindent
16106 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16107 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16108 bit set, hence no IFS splitting is performed!!!
16110 One piece of good news is that Ultrix works fine with @samp{:
16111 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16112 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16113 @var{default}!
16115 The portable way out consists in using a double assignment, to switch
16116 the 8th bit twice on Ultrix:
16118 @example
16119 list=$@{list="$default"@}
16120 @end example
16122 @noindent
16123 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16124 use:
16126 @example
16127 test "$@{var+set@}" = set || var=@var{@{value@}}
16128 @end example
16130 @item $@{#@var{var}@}
16131 @itemx $@{@var{var}%@var{word}@}
16132 @itemx $@{@var{var}%%@var{word}@}
16133 @itemx $@{@var{var}#@var{word}@}
16134 @itemx $@{@var{var}##@var{word}@}
16135 @cindex @code{$@{#@var{var}@}}
16136 @cindex @code{$@{@var{var}%@var{word}@}}
16137 @cindex @code{$@{@var{var}%%@var{word}@}}
16138 @cindex @code{$@{@var{var}#@var{word}@}}
16139 @cindex @code{$@{@var{var}##@var{word}@}}
16140 Posix requires support for these usages, but they do not work with many
16141 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16143 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16144 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16145 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16146 yields the empty string.
16149 @item `@var{commands}`
16150 @cindex @code{`@var{commands}`}
16151 @cindex Command Substitution
16152 Posix requires shells to trim all trailing newlines from command
16153 output before substituting it, so assignments like
16154 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16155 @samp{$file} ends in a newline.
16157 While in general it makes no sense, do not substitute a single builtin
16158 with side effects, because Ash 0.2, trying to optimize, does not fork a
16159 subshell to perform the command.
16161 For instance, if you wanted to check that @command{cd} is silent, do not
16162 use @samp{test -z "`cd /`"} because the following can happen:
16164 @example
16165 $ @kbd{pwd}
16166 /tmp
16167 $ @kbd{test -z "`cd /`" && pwd}
16169 @end example
16171 @noindent
16172 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16174 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16175 command substitution of a native program, if the end of the substitution
16176 is not aligned with the end of the double quote.  This may be worked
16177 around by inserting another pair of quotes:
16179 @example
16180 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16181 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16182 - broken differ: char 4, line 1
16183 @end example
16185 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16186 replace it with a null string, and wrongly evaluate the enclosing
16187 command before entering the trap or ending the script.  This can lead to
16188 spurious errors:
16190 @example
16191 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16192 $ @kbd{^C}
16193 sh: test: hi: unexpected operator/operand
16194 @end example
16196 @noindent
16197 You can avoid this by assigning the command substitution to a temporary
16198 variable:
16200 @example
16201 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16202          if test "x$res" = xhi; then echo yes; fi'}
16203 $ @kbd{^C}
16204 @end example
16206 @item $(@var{commands})
16207 @cindex @code{$(@var{commands})}
16208 This construct is meant to replace @samp{`@var{commands}`},
16209 and it has most of the problems listed under @code{`@var{commands}`}.
16211 This construct can be
16212 nested while this is impossible to do portably with back quotes.
16213 Unfortunately it is not yet universally supported.  Most notably, even recent
16214 releases of Solaris don't support it:
16216 @example
16217 $ @kbd{showrev -c /bin/sh | grep version}
16218 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
16219 $ @kbd{echo $(echo blah)}
16220 syntax error: `(' unexpected
16221 @end example
16223 @noindent
16224 nor does IRIX 6.5's Bourne shell:
16225 @example
16226 $ @kbd{uname -a}
16227 IRIX firebird-image 6.5 07151432 IP22
16228 $ @kbd{echo $(echo blah)}
16229 $(echo blah)
16230 @end example
16232 If you do use @samp{$(@var{commands})}, make sure that the commands
16233 do not start with a parenthesis, as that would cause confusion with
16234 a different notation @samp{$((@var{expression}))} that in modern
16235 shells is an arithmetic expression not a command.  To avoid the
16236 confusion, insert a space between the two opening parentheses.
16238 Avoid @var{commands} that contain unbalanced parentheses in
16239 here-documents, comments, or case statement patterns, as many shells
16240 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16241 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16243 @example
16244 echo $(case x in x) echo hello;; esac)
16245 @end example
16248 @item $((@var{expression}))
16249 @cindex @code{$((@var{expression}))}
16250 Arithmetic expansion is not portable as some shells (most
16251 notably Solaris 10 @command{/bin/sh}) don't support it.
16253 Among shells that do support @samp{$(( ))}, not all of them obey the
16254 Posix rule that octal and hexadecimal constants must be recognized:
16256 @example
16257 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16259 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16261 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16263 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16264 pdksh:  010 + 0x10 : bad number `0x10'
16265 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16267 @end example
16269 When it is available, using arithmetic expansion provides a noticeable
16270 speedup in script execution; but testing for support requires
16271 @command{eval} to avoid syntax errors.  The following construct is used
16272 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16273 arguments are provided in decimal and without a leading zero, and all
16274 operators are properly quoted and appear as distinct arguments:
16276 @example
16277 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16278   eval 'func_arith ()
16279   @{
16280     func_arith_result=$(( $* ))
16281   @}'
16282 else
16283   func_arith ()
16284   @{
16285     func_arith_result=`expr "$@@"`
16286   @}
16288 func_arith 1 + 1
16289 foo=$func_arith_result
16290 @end example
16293 @item ^
16294 @cindex @code{^} quoting
16295 Always quote @samp{^}, otherwise traditional shells such as
16296 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16298 @end table
16301 @node Assignments
16302 @section Assignments
16303 @cindex Shell assignments
16305 When setting several variables in a row, be aware that the order of the
16306 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16307 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16308 You must use
16309 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16311 Don't rely on the following to find @file{subdir/program}:
16313 @example
16314 PATH=subdir$PATH_SEPARATOR$PATH program
16315 @end example
16317 @noindent
16318 as this does not work with Zsh 3.0.6.  Use something like this
16319 instead:
16321 @example
16322 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16323 @end example
16325 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16326 the status and propagates that of the last statement:
16328 @example
16329 $ @kbd{false || foo=bar; echo $?}
16331 $ @kbd{false || foo=`:`; echo $?}
16333 @end example
16335 @noindent
16336 and to make things even worse, QNX 4.25 just sets the exit status
16337 to 0 in any case:
16339 @example
16340 $ @kbd{foo=`exit 1`; echo $?}
16342 @end example
16344 To assign default values, follow this algorithm:
16346 @enumerate
16347 @item
16348 If the default value is a literal and does not contain any closing
16349 brace, use:
16351 @example
16352 : "$@{var='my literal'@}"
16353 @end example
16355 @item
16356 If the default value contains no closing brace, has to be expanded, and
16357 the variable being initialized is not intended to be IFS-split
16358 (i.e., it's not a list), then use:
16360 @example
16361 : $@{var="$default"@}
16362 @end example
16364 @item
16365 If the default value contains no closing brace, has to be expanded, and
16366 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16367 then use:
16369 @example
16370 var=$@{var="$default"@}
16371 @end example
16373 @item
16374 If the default value contains a closing brace, then use:
16376 @example
16377 test "$@{var+set@}" = set || var="has a '@}'"
16378 @end example
16379 @end enumerate
16381 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16382 doubt, just use the last form.  @xref{Shell Substitutions}, items
16383 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16384 for the rationale.
16386 @node Parentheses
16387 @section Parentheses in Shell Scripts
16388 @cindex Shell parentheses
16390 Beware of two opening parentheses in a row, as many shell
16391 implementations treat them specially, and Posix says that a portable
16392 script cannot use @samp{((} outside the @samp{$((} form used for shell
16393 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16394 @samp{(cat)}; but many shells, including
16395 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16396 expression equivalent to @samp{let "cat"}, and may or may not report an
16397 error when they detect that @samp{cat} is not a number.  As another
16398 example, @samp{pdksh} 5.2.14 does not treat the following code
16399 as a traditional shell would:
16401 @example
16402 if ((true) || false); then
16403   echo ok
16405 @end example
16407 @noindent
16408 To work around this problem, insert a space between the two opening
16409 parentheses.  There is a similar problem and workaround with
16410 @samp{$((}; see @ref{Shell Substitutions}.
16412 @node Slashes
16413 @section Slashes in Shell Scripts
16414 @cindex Shell slashes
16416 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16417 arguments that contain two trailing slashes:
16419 @example
16420 $ @kbd{echo / // /// //// .// //.}
16421 / / // /// ./ //.
16422 $ @kbd{x=//}
16423 $ @kbd{eval "echo \$x"}
16425 $ @kbd{set -x}
16426 $ @kbd{echo abc | tr -t ab //}
16427 + echo abc
16428 + tr -t ab /
16430 @end example
16432 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16433 variable is empty and the second double-quote is followed by a word that
16434 begins and ends with slash:
16436 @example
16437 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16439 + echo //ouch/
16440 //ouch/
16441 @end example
16443 However, our understanding is that patches are available, so perhaps
16444 it's not worth worrying about working around these horrendous bugs.
16446 @node Special Shell Variables
16447 @section Special Shell Variables
16448 @cindex Shell variables
16449 @cindex Special shell variables
16451 Some shell variables should not be used, since they can have a deep
16452 influence on the behavior of the shell.  In order to recover a sane
16453 behavior from the shell, some variables should be unset; M4sh takes
16454 care of this and provides fallback values, whenever needed, to cater
16455 for a very old @file{/bin/sh} that does not support @command{unset}.
16456 (@pxref{Portable Shell, , Portable Shell Programming}).
16458 As a general rule, shell variable names containing a lower-case letter
16459 are safe; you can define and use these variables without worrying about
16460 their effect on the underlying system, and without worrying about
16461 whether the shell changes them unexpectedly.  (The exception is the
16462 shell variable @code{status}, as described below.)
16464 Here is a list of names that are known to cause trouble.  This list is
16465 not exhaustive, but you should be safe if you avoid the name
16466 @code{status} and names containing only upper-case letters and
16467 underscores.
16469 @c Alphabetical order, case insensitive, `A' before `a'.
16470 @table @code
16471 @item ?
16472 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16473 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16474 correctly in shell functions (@pxref{Shell Functions}) or in traps
16475 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16476 @samp{$?} to zero after an empty command.
16478 @example
16479 $ @kbd{bash -c 'false; $empty; echo $?'}
16481 $ @kbd{zsh -c 'false; $empty; echo $?'}
16483 @end example
16485 @item _
16486 @evindex _
16487 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16488 the last command executed.
16490 @item BIN_SH
16491 @evindex BIN_SH
16492 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16493 the standard shell conform to Posix.
16495 @item CDPATH
16496 @evindex CDPATH
16497 When this variable is set it specifies a list of directories to search
16498 when invoking @code{cd} with a relative file name that did not start
16499 with @samp{./} or @samp{../}.  Posix
16500 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16501 is used successfully, @code{cd} prints the resulting absolute
16502 file name.  Unfortunately this output can break idioms like
16503 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16504 Also, many shells do not conform to this part of Posix; for
16505 example, @command{zsh} prints the result only if a directory name
16506 other than @file{.} was chosen from @env{CDPATH}.
16508 In practice the shells that have this problem also support
16509 @command{unset}, so you can work around the problem as follows:
16511 @example
16512 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16513 @end example
16515 You can also avoid output by ensuring that your directory name is
16516 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16518 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16519 possible, so you need not worry about this problem in those scripts.
16521 @item CLICOLOR_FORCE
16522 @evindex CLICOLOR_FORCE
16523 When this variable is set, some implementations of tools like
16524 @command{ls} attempt to add color to their output via terminal escape
16525 sequences, even when the output is not directed to a terminal, and can
16526 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16527 which automatically unsets this variable.
16529 @item DUALCASE
16530 @evindex DUALCASE
16531 In the MKS shell, case statements and file name generation are
16532 case-insensitive unless @env{DUALCASE} is nonzero.
16533 Autoconf-generated scripts export this variable when they start up.
16535 @item ENV
16536 @itemx MAIL
16537 @itemx MAILPATH
16538 @itemx PS1
16539 @itemx PS2
16540 @itemx PS4
16541 @evindex ENV
16542 @evindex MAIL
16543 @evindex MAILPATH
16544 @evindex PS1
16545 @evindex PS2
16546 @evindex PS4
16547 These variables should not matter for shell scripts, since they are
16548 supposed to affect only interactive shells.  However, at least one
16549 shell (the pre-3.0 UWIN Korn shell) gets confused about
16550 whether it is interactive, which means that (for example) a @env{PS1}
16551 with a side effect can unexpectedly modify @samp{$?}.  To work around
16552 this bug, M4sh scripts (including @file{configure} scripts) do something
16553 like this:
16555 @example
16556 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16557 PS1='$ '
16558 PS2='> '
16559 PS4='+ '
16560 @end example
16562 @noindent
16563 (actually, there is some complication due to bugs in @command{unset};
16564 see @pxref{unset, , Limitations of Shell Builtins}).
16566 @item FPATH
16567 @evindex FPATH
16568 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16569 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16570 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16571 to find whether a command exists, since they might report the wrong
16572 result if @env{FPATH} is also set.
16574 @item GREP_OPTIONS
16575 @evindex GREP_OPTIONS
16576 When this variable is set, some implementations of @command{grep} honor
16577 these options, even if the options include direction to enable colored
16578 output via terminal escape sequences, and the result can cause spurious
16579 failures when the output is not directed to a terminal.  Configure
16580 scripts use M4sh, which automatically unsets this variable.
16582 @item IFS
16583 @evindex IFS
16584 Long ago, shell scripts inherited @env{IFS} from the environment,
16585 but this caused many problems so modern shells ignore any environment
16586 settings for @env{IFS}.
16588 Don't set the first character of @env{IFS} to backslash.  Indeed,
16589 Bourne shells use the first character (backslash) when joining the
16590 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16591 backslash escapes, so you can end up with backspace and other strange
16592 characters.
16594 The proper value for @env{IFS} (in regular code, not when performing
16595 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16596 especially important, as it is used to join the arguments in @samp{$*};
16597 however, note that traditional shells, but also bash-2.04, fail to adhere
16598 to this and join with a space anyway.
16600 M4sh guarantees that @env{IFS} will have the default value at the
16601 beginning of a script, and many macros within autoconf rely on this
16602 setting.  It is okay to use blocks of shell code that temporarily change
16603 the value of @env{IFS} in order to split on another character, but
16604 remember to restore it before expanding further macros.
16606 Unsetting @code{IFS} instead of resetting it to the default sequence
16607 is not suggested, since code that tries to save and restore the
16608 variable's value will incorrectly reset it to an empty value, thus
16609 disabling field splitting:
16611 @example
16612 unset IFS
16613 # default separators used for field splitting
16615 save_IFS=$IFS
16616 IFS=:
16617 # ...
16618 IFS=$save_IFS
16619 # no field splitting performed
16620 @end example
16622 @item LANG
16623 @itemx LC_ALL
16624 @itemx LC_COLLATE
16625 @itemx LC_CTYPE
16626 @itemx LC_MESSAGES
16627 @itemx LC_MONETARY
16628 @itemx LC_NUMERIC
16629 @itemx LC_TIME
16630 @evindex LANG
16631 @evindex LC_ALL
16632 @evindex LC_COLLATE
16633 @evindex LC_CTYPE
16634 @evindex LC_MESSAGES
16635 @evindex LC_MONETARY
16636 @evindex LC_NUMERIC
16637 @evindex LC_TIME
16639 You should set all these variables to @samp{C} because so much
16640 configuration code assumes the C locale and Posix requires that locale
16641 environment variables be set to @samp{C} if the C locale is desired;
16642 @file{configure} scripts and M4sh do that for you.
16643 Export these variables after setting them.
16645 @c  However, some older, nonstandard
16646 @c  systems (notably SCO) break if locale environment variables
16647 @c  are set to @samp{C}, so when running on these systems
16648 @c  Autoconf-generated scripts unset the variables instead.
16650 @item LANGUAGE
16651 @evindex LANGUAGE
16653 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16654 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16655 should set it too.
16657 @item LC_ADDRESS
16658 @itemx LC_IDENTIFICATION
16659 @itemx LC_MEASUREMENT
16660 @itemx LC_NAME
16661 @itemx LC_PAPER
16662 @itemx LC_TELEPHONE
16663 @evindex LC_ADDRESS
16664 @evindex LC_IDENTIFICATION
16665 @evindex LC_MEASUREMENT
16666 @evindex LC_NAME
16667 @evindex LC_PAPER
16668 @evindex LC_TELEPHONE
16670 These locale environment variables are GNU extensions.  They
16671 are treated like their Posix brethren (@env{LC_COLLATE},
16672 etc.)@: as described above.
16674 @item LINENO
16675 @evindex LINENO
16676 Most modern shells provide the current line number in @code{LINENO}.
16677 Its value is the line number of the beginning of the current command.
16678 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16679 a shell that supports @code{LINENO}.  If no such shell is available, it
16680 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16681 instance of the string @code{$LINENO} (not followed by an alphanumeric
16682 character) with the line's number.  In M4sh scripts you should execute
16683 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16684 your script; configure scripts do this automatically in @code{AC_INIT}.
16686 You should not rely on @code{LINENO} within @command{eval} or shell
16687 functions, as the behavior differs in practice.  The presence of a
16688 quoted newline within simple commands can alter which line number is
16689 used as the starting point for @code{$LINENO} substitutions within that
16690 command.  Also, the possibility of the Sed prepass means that you should
16691 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16692 line continuations are used.  Subshells should be OK, though.  In the
16693 following example, lines 1, 9, and 14 are portable, but the other
16694 instances of @code{$LINENO} do not have deterministic values:
16696 @example
16697 @group
16698 $ @kbd{cat lineno}
16699 echo 1. $LINENO
16700 echo "2. $LINENO
16701 3. $LINENO"
16702 cat <<EOF
16703 5. $LINENO
16704 6. $LINENO
16705 7. \$LINENO
16707 ( echo 9. $LINENO )
16708 eval 'echo 10. $LINENO'
16709 eval 'echo 11. $LINENO
16710 echo 12. $LINENO'
16711 echo 13. '$LINENO'
16712 echo 14. $LINENO '
16713 15.' $LINENO
16714 f () @{ echo $1 $LINENO;
16715 echo $1 $LINENO @}
16716 f 18.
16717 echo 19. \
16718 $LINENO
16719 @end group
16720 @group
16721 $ @kbd{bash-3.2 ./lineno}
16722 1. 1
16723 2. 3
16724 3. 3
16725 5. 4
16726 6. 4
16727 7. $LINENO
16728 9. 9
16729 10. 10
16730 11. 12
16731 12. 13
16732 13. $LINENO
16733 14. 14
16734 15. 14
16735 18. 16
16736 18. 17
16737 19. 19
16738 @end group
16739 @group
16740 $ @kbd{zsh-4.3.4 ./lineno}
16741 1. 1
16742 2. 2
16743 3. 2
16744 5. 4
16745 6. 4
16746 7. $LINENO
16747 9. 9
16748 10. 1
16749 11. 1
16750 12. 2
16751 13. $LINENO
16752 14. 14
16753 15. 14
16754 18. 0
16755 18. 1
16756 19. 19
16757 @end group
16758 @group
16759 $ @kbd{pdksh-5.2.14 ./lineno}
16760 1. 1
16761 2. 2
16762 3. 2
16763 5. 4
16764 6. 4
16765 7. $LINENO
16766 9. 9
16767 10. 0
16768 11. 0
16769 12. 0
16770 13. $LINENO
16771 14. 14
16772 15. 14
16773 18. 16
16774 18. 17
16775 19. 19
16776 @end group
16777 @group
16778 $ @kbd{sed '=' <lineno |}
16779 > @kbd{  sed '}
16780 > @kbd{    N}
16781 > @kbd{    s,$,-,}
16782 > @kbd{    t loop}
16783 > @kbd{    :loop}
16784 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
16785 > @kbd{    t loop}
16786 > @kbd{    s,-$,,}
16787 > @kbd{    s,^[0-9]*\n,,}
16788 > @kbd{  ' |}
16789 > @kbd{  sh}
16790 1. 1
16791 2. 2
16792 3. 3
16793 5. 5
16794 6. 6
16795 7. \7
16796 9. 9
16797 10. 10
16798 11. 11
16799 12. 12
16800 13. 13
16801 14. 14
16802 15. 15
16803 18. 16
16804 18. 17
16805 19. 20
16806 @end group
16807 @end example
16809 In particular, note that @file{config.status} (and any other subsidiary
16810 script created by @code{AS_INIT_GENERATED}) might report line numbers
16811 relative to the parent script as a result of the potential Sed pass.
16813 @item NULLCMD
16814 @evindex NULLCMD
16815 When executing the command @samp{>foo}, @command{zsh} executes
16816 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
16817 compatibility mode and the @command{zsh} version is newer
16818 than 3.1.6-dev-18.  If you are using an older @command{zsh}
16819 and forget to set @env{NULLCMD},
16820 your script might be suspended waiting for data on its standard input.
16822 @item options
16823 @evindex options
16824 For @command{zsh} 4.3.10, @env{options} is treated as an associative
16825 array even after @code{emulate sh}, so it should not be used.
16827 @item PATH_SEPARATOR
16828 @evindex PATH_SEPARATOR
16829 On DJGPP systems, the @env{PATH_SEPARATOR} environment
16830 variable can be set to either @samp{:} or @samp{;} to control the path
16831 separator Bash uses to set up certain environment variables (such as
16832 @env{PATH}).  You can set this variable to @samp{;} if you want
16833 @command{configure} to use @samp{;} as a separator; this might be useful
16834 if you plan to use non-Posix shells to execute files.  @xref{File System
16835 Conventions}, for more information about @code{PATH_SEPARATOR}.
16837 @item POSIXLY_CORRECT
16838 @evindex POSIXLY_CORRECT
16839 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
16840 (even empty) causes programs to try harder to conform to Posix.
16841 Autoconf does not directly manipulate this variable, but @command{bash}
16842 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
16843 running in Posix mode.  Therefore, take care when exporting or unsetting
16844 this variable, so as not to change whether @command{bash} is in Posix
16845 mode.
16847 @example
16848 $ @kbd{bash --posix -c 'set -o | grep posix}
16849 > @kbd{unset POSIXLY_CORRECT}
16850 > @kbd{set -o | grep posix'}
16851 posix           on
16852 posix           off
16853 @end example
16855 @item PWD
16856 @evindex PWD
16857 Posix 1003.1-2001 requires that @command{cd} and
16858 @command{pwd} must update the @env{PWD} environment variable to point
16859 to the logical name of the current directory, but traditional shells
16860 do not support this.  This can cause confusion if one shell instance
16861 maintains @env{PWD} but a subsidiary and different shell does not know
16862 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
16863 points to the wrong directory.  Use @samp{`pwd`} rather than
16864 @samp{$PWD}.
16866 @item RANDOM
16867 @evindex RANDOM
16868 Many shells provide @code{RANDOM}, a variable that returns a different
16869 integer each time it is used.  Most of the time, its value does not
16870 change when it is not used, but on IRIX 6.5 the value changes all
16871 the time.  This can be observed by using @command{set}.  It is common
16872 practice to use @code{$RANDOM} as part of a file name, but code
16873 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
16875 @item status
16876 @evindex status
16877 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
16878 hence read-only.  Do not use it.
16879 @end table
16881 @node Shell Functions
16882 @section Shell Functions
16883 @cindex Shell Functions
16885 Nowadays, it is difficult to find a shell that does not support
16886 shell functions at all.  However, some differences should be expected.
16888 When declaring a shell function, you must include whitespace between the
16889 @samp{)} after the function name and the start of the compound
16890 expression, to avoid upsetting @command{ksh}.  While it is possible to
16891 use any compound command, most scripts use @samp{@{@dots{}@}}.
16893 @example
16894 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
16896 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
16897 ksh: syntax error at line 1: `@}' unexpected
16898 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
16900 @end example
16902 Inside a shell function, you should not rely on the error status of a
16903 subshell if the last command of that subshell was @code{exit} or
16904 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
16905 find a shell that does not exhibit the bug, zsh might be the only shell
16906 present on the user's machine.
16908 Likewise, the state of @samp{$?} is not reliable when entering a shell
16909 function.  This has the effect that using a function as the first
16910 command in a @command{trap} handler can cause problems.
16912 @example
16913 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16916 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
16919 @end example
16921 DJGPP bash 2.04 has a bug in that @command{return} from a
16922 shell function which also used a command substitution causes a
16923 segmentation fault.  To work around the issue, you can use
16924 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
16925 in the execution flow of the function (@pxref{Common Shell Constructs}).
16927 Not all shells treat shell functions as simple commands impacted by
16928 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
16930 @example
16931 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops}
16932 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops}
16933 oops
16934 @end example
16936 Shell variables and functions may share the same namespace, for example
16937 with Solaris 10 @command{/bin/sh}:
16939 @example
16940 $ @kbd{f () @{ :; @}; f=; f}
16941 f: not found
16942 @end example
16944 @noindent
16945 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
16946 uses the prefix @samp{as_fn_} for its functions.
16948 Handling of positional parameters and shell options varies among shells.
16949 For example, Korn shells reset and restore trace output (@samp{set -x})
16950 and other options upon function entry and exit.  Inside a function,
16951 IRIX sh sets @samp{$0} to the function name.
16953 It is not portable to pass temporary environment variables to shell
16954 functions.  Solaris @command{/bin/sh} does not see the variable.
16955 Meanwhile, not all shells follow the Posix rule that the assignment must
16956 affect the current environment in the same manner as special built-ins.
16958 @example
16959 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16960 @result{}
16961 @result{}
16962 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
16963 @result{}1
16964 @result{}
16965 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
16966 @result{}1
16967 @result{}1
16968 @end example
16970 Some ancient Bourne shell variants with function support did not reset
16971 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
16972 arguments of the script were lost after the first function invocation.
16973 It is probably not worth worrying about these shells any more.
16975 With AIX sh, a @command{trap} on 0 installed in a shell function
16976 triggers at function exit rather than at script exit.  @xref{trap, ,
16977 Limitations of Shell Builtins}.
16979 @node Limitations of Builtins
16980 @section Limitations of Shell Builtins
16981 @cindex Shell builtins
16982 @cindex Limitations of shell builtins
16984 No, no, we are serious: some shells do have limitations!  :)
16986 You should always keep in mind that any builtin or command may support
16987 options, and therefore differ in behavior with arguments
16988 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
16989 can give unexpected results when @code{word} starts with a dash.  It is
16990 often possible to avoid this problem using @samp{echo "x$word"}, taking
16991 the @samp{x} into account later in the pipe.  Many of these limitations
16992 can be worked around using M4sh (@pxref{Programming in M4sh}).
16994 @c This table includes things like `@command{test} (files)', so we can't
16995 @c use @table @command.
16996 @table @asis
16997 @item @command{.}
16998 @c --------------
16999 @prindex @command{.}
17000 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17001 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17002 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17003 some shells, including bash 3.2, implicitly append the current directory
17004 to this @env{PATH} search, even though Posix forbids it.  So if you want
17005 to use @command{.} on a file @file{foo} in the current directory, you
17006 must use @samp{. ./foo}.
17008 Not all shells gracefully handle syntax errors within a sourced file.
17009 On one extreme, some non-interactive shells abort the entire script.  On
17010 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17011 syntax error.
17013 @example
17014 $ @kbd{echo 'fi' > syntax}
17015 $ @kbd{bash -c '. ./syntax; echo $?'}
17016 ./syntax: line 1: syntax error near unexpected token `fi'
17017 ./syntax: line 1: `fi'
17019 $ @kbd{ash -c '. ./syntax; echo $?'}
17020 ./syntax: 1: Syntax error: "fi" unexpected
17021 $ @kbd{zsh -c '. ./syntax; echo $?'}
17022 ./syntax:1: parse error near `fi'
17024 @end example
17026 @item @command{!}
17027 @c --------------
17028 @prindex @command{!}
17029 The Unix version 7 shell did not support
17030 negating the exit status of commands with @command{!}, and this feature
17031 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17032 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17033 bugs when using @command{!}:
17035 @example
17036 $ @kbd{sh -c '! : | :'; echo $?}
17038 $ @kbd{ash -c '! : | :'; echo $?}
17040 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17042 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17043 @{: not found
17044 Syntax error: "@}" unexpected
17046 @end example
17048 Shell code like this:
17050 @example
17051 if ! cmp file1 file2 >/dev/null 2>&1; then
17052   echo files differ or trouble
17054 @end example
17056 is therefore not portable in practice.  Typically it is easy to rewrite
17057 such code, e.g.:
17059 @example
17060 cmp file1 file2 >/dev/null 2>&1 ||
17061   echo files differ or trouble
17062 @end example
17064 More generally, one can always rewrite @samp{! @var{command}} as:
17066 @example
17067 if @var{command}; then (exit 1); else :; fi
17068 @end example
17071 @item @command{@{...@}}
17072 @c --------------------
17073 @prindex @command{@{...@}}
17074 Bash 3.2 (and earlier versions) sometimes does not properly set
17075 @samp{$?} when failing to write redirected output of a compound command.
17076 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17077 not occur with @samp{(@dots{})}.  For example:
17079 @example
17080 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17081 bash: line 1: /bad: Permission denied
17083 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17084 bash: line 1: /bad: Permission denied
17086 @end example
17088 To work around the bug, prepend @samp{:;}:
17090 @example
17091 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17092 bash: line 1: /bad: Permission denied
17094 @end example
17096 Posix requires a syntax error if a brace list has no contents.  However,
17097 not all shells obey this rule; and on shells where empty lists are
17098 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17099 ensure that a brace list is never empty.
17101 @example
17102 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17103 bash: line 1: syntax error near unexpected token `@}'
17104 bash: line 1: `false; @{ @}; echo $?'
17106 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17108 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17110 @end example
17113 @item @command{break}
17114 @c ------------------
17115 @prindex @command{break}
17116 The use of @samp{break 2} etc.@: is safe.
17119 @anchor{case}
17120 @item @command{case}
17121 @c -----------------
17122 @prindex @command{case}
17123 You don't need to quote the argument; no splitting is performed.
17125 You don't need the final @samp{;;}, but you should use it.
17127 Posix requires support for @code{case} patterns with opening
17128 parentheses like this:
17130 @example
17131 case $file_name in
17132   (*.c) echo "C source code";;
17133 esac
17134 @end example
17136 @noindent
17137 but the @code{(} in this example is not portable to many Bourne
17138 shell implementations, which is a pity for those of us using tools that
17139 rely on balanced parentheses.  For instance, with Solaris
17140 @command{/bin/sh}:
17142 @example
17143 $ @kbd{case foo in (foo) echo foo;; esac}
17144 @error{}syntax error: `(' unexpected
17145 @end example
17147 @noindent
17148 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17149 contexts where unbalanced parentheses cause other problems, such as when
17150 using a syntax-highlighting editor that searches for the balancing
17151 counterpart, or more importantly, when using a case statement as an
17152 underquoted argument to an Autoconf macro.  @xref{Balancing
17153 Parentheses}, for tradeoffs involved in various styles of dealing with
17154 unbalanced @samp{)}.
17156 Zsh handles pattern fragments derived from parameter expansions or
17157 command substitutions as though quoted:
17159 @example
17160 $ pat=\?; case aa in ?$pat) echo match;; esac
17161 $ pat=\?; case a? in ?$pat) echo match;; esac
17162 match
17163 @end example
17165 @noindent
17166 Because of a bug in its @code{fnmatch}, Bash fails to properly
17167 handle backslashes in character classes:
17169 @example
17170 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17171 bash-2.02$
17172 @end example
17174 @noindent
17175 This is extremely unfortunate, since you are likely to use this code to
17176 handle Posix or MS-DOS absolute file names.  To work around this
17177 bug, always put the backslash first:
17179 @example
17180 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17182 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17184 @end example
17186 Many Bourne shells cannot handle closing brackets in character classes
17187 correctly.
17189 Some shells also have problems with backslash escaping in case you do not want
17190 to match the backslash: both a backslash and the escaped character match this
17191 pattern.  To work around this, specify the character class in a variable, so
17192 that quote removal does not apply afterwards, and the special characters don't
17193 have to be backslash-escaped:
17195 @example
17196 $ @kbd{case '\' in [\<]) echo OK;; esac}
17198 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17200 @end example
17202 Even with this, Solaris @command{ksh} matches a backslash if the set
17203 contains any
17204 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17206 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17207 a closing parenthesis if not specified in a character class:
17209 @example
17210 $ @kbd{case foo in *\)*) echo fail ;; esac}
17211 fail
17212 $ @kbd{case foo in *')'*) echo fail ;; esac}
17213 fail
17214 @end example
17216 Some shells, such as Ash 0.3.8, are confused by an empty
17217 @code{case}/@code{esac}:
17219 @example
17220 ash-0.3.8 $ @kbd{case foo in esac;}
17221 @error{}Syntax error: ";" unexpected (expecting ")")
17222 @end example
17224 Posix requires @command{case} to give an exit status of 0 if no cases
17225 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17226 rule.  Meanwhile, it is unclear whether a case that matches, but
17227 contains no statements, must also change the exit status to 0.  The M4sh
17228 macro @code{AS_CASE} works around these inconsistencies.
17230 @example
17231 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17233 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17235 @end example
17238 @item @command{cd}
17239 @c ---------------
17240 @prindex @command{cd}
17241 Posix 1003.1-2001 requires that @command{cd} must support
17242 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17243 with @option{-L} being the default.  However, traditional shells do
17244 not support these options, and their @command{cd} command has the
17245 @option{-P} behavior.
17247 Portable scripts should assume neither option is supported, and should
17248 assume neither behavior is the default.  This can be a bit tricky,
17249 since the Posix default behavior means that, for example,
17250 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17251 the current logical directory is a symbolic link.  It is safe to use
17252 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17253 Also, Autoconf-generated scripts check for this problem when computing
17254 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17255 so it is safe to @command{cd} to these variables.
17257 Posix states that behavior is undefined if @command{cd} is given an
17258 explicit empty argument.  Some shells do nothing, some change to the
17259 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17260 the shell rather than returning an error.  Unfortunately, this means
17261 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17262 than @samp{cd $var} (at least the latter is well-behaved in all shells
17263 at changing to @env{HOME}, although this is probably not what you wanted
17264 in a script).  You should check that a directory name was supplied
17265 before trying to change locations.
17267 @xref{Special Shell Variables}, for portability problems involving
17268 @command{cd} and the @env{CDPATH} environment variable.
17269 Also please see the discussion of the @command{pwd} command.
17272 @anchor{echo}
17273 @item @command{echo}
17274 @c -----------------
17275 @prindex @command{echo}
17276 The simple @command{echo} is probably the most surprising source of
17277 portability troubles.  It is not possible to use @samp{echo} portably
17278 unless both options and escape sequences are omitted.  Don't expect any
17279 option.
17281 Do not use backslashes in the arguments, as there is no consensus on
17282 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17283 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17284 The problem is truly @command{echo}: all the shells
17285 understand @samp{'\n'} as the string composed of a backslash and an
17286 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17287 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17288 the first character @samp{s} only, followed by a newline, and then
17289 entirely drop the output of the next echo in a command substitution.
17291 Because of these problems, do not pass a string containing arbitrary
17292 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17293 only if you know that @var{foo}'s value cannot contain backslashes and
17294 cannot start with @samp{-}.
17296 If this may not be true, @command{printf} is in general safer and
17297 easier to use than @command{echo} and @command{echo -n}.  Thus, scripts
17298 where portability is not a major concern should use @command{printf
17299 '%s\n'} whenever @command{echo} could fail, and similarly use
17300 @command{printf %s} instead of @command{echo -n}. For portable shell
17301 scripts, instead, it is suggested to use a here-document like this:
17303 @example
17304 cat <<EOF
17305 $foo
17307 @end example
17309 Alternatively, M4sh provides @code{AS_ECHO} and @code{AS_ECHO_N} macros
17310 which choose between various portable implementations: @samp{echo}
17311 or @samp{print} where they work, @command{printf} if it is available,
17312 or else other creative tricks in order to work around the above problems.
17315 @item @command{eval}
17316 @c -----------------
17317 @prindex @command{eval}
17318 The @command{eval} command is useful in limited circumstances, e.g.,
17319 using commands like @samp{eval table_$key=\$value} and @samp{eval
17320 value=table_$key} to simulate a hash table when the key is known to be
17321 alphanumeric.
17323 You should also be wary of common bugs in @command{eval} implementations.
17324 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17325 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17326 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17327 @samp{$?} is 0, so they exhibit behavior like this:
17329 @example
17330 $ @kbd{false; eval 'echo $?'}
17332 @end example
17334 The correct behavior here is to output a nonzero value,
17335 but portable scripts should not rely on this.
17337 You should not rely on @code{LINENO} within @command{eval}.
17338 @xref{Special Shell Variables}.
17340 Note that, even though these bugs are easily avoided,
17341 @command{eval} is tricky to use on arbitrary arguments.
17342 It is obviously unwise to use @samp{eval $cmd} if the string value of
17343 @samp{cmd} was derived from an untrustworthy source.  But even if the
17344 string value is valid, @samp{eval $cmd} might not work as intended,
17345 since it causes field splitting and file name expansion to occur twice,
17346 once for the @command{eval} and once for the command itself.  It is
17347 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17348 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17349 equivalent of @samp{cat test;.c} if there happens to be a file named
17350 @file{test;.c} in the current directory; and this in turn
17351 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17352 then execute the command @command{.c}.  To avoid this problem, use
17353 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17355 However, suppose that you want to output the text of the evaluated
17356 command just before executing it.  Assuming the previous example,
17357 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17358 this output doesn't show the user that @samp{test;.c} is the actual name
17359 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17360 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17361 since it mistakenly replaces the contents of @file{bar} by the
17362 string @samp{cat foo}.  No simple, general, and portable solution to
17363 this problem is known.
17365 @item @command{exec}
17366 @c -----------------
17367 @prindex @command{exec}
17368 Posix describes several categories of shell built-ins.  Special
17369 built-ins (such as @command{exit}) must impact the environment of the
17370 current shell, and need not be available through @command{exec}.  All
17371 other built-ins are regular, and must not propagate variable assignments
17372 to the environment of the current shell.  However, the group of regular
17373 built-ins is further distinguished by commands that do not require a
17374 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17375 are offered as a more efficient version of something that must still be
17376 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17377 clear on whether @command{exec} must work with the list of 17 utilities
17378 that are invoked without a @env{PATH} search, and many platforms lack an
17379 executable for some of those built-ins:
17381 @example
17382 $ @kbd{sh -c 'exec cd /tmp'}
17383 sh: line 0: exec: cd: not found
17384 @end example
17386 All other built-ins that provide utilities specified by Posix must have
17387 a counterpart executable that exists on @env{PATH}, although Posix
17388 allows @command{exec} to use the built-in instead of the executable.
17389 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17391 @example
17392 $ @kbd{bash -c 'pwd --version' | head -n1}
17393 bash: line 0: pwd: --: invalid option
17394 pwd: usage: pwd [-LP]
17395 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17396 pwd (GNU coreutils) 6.10
17397 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17398 pdksh: pwd: --: unknown option
17399 @end example
17401 When it is desired to avoid a regular shell built-in, the workaround is
17402 to use some other forwarding command, such as @command{env} or
17403 @command{nice}, that will ensure a path search:
17405 @example
17406 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17407 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17408 true (GNU coreutils) 6.10
17409 $ @kbd{pdksh -c 'env true --version' | head -n1}
17410 true (GNU coreutils) 6.10
17411 @end example
17413 @item @command{exit}
17414 @c -----------------
17415 @prindex @command{exit}
17416 The default value of @command{exit} is supposed to be @code{$?};
17417 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17418 perform @samp{exit 0}.
17420 @example
17421 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17422 fail
17423 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17424 fail
17425 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17426 bash-2.04$
17427 @end example
17429 Using @samp{exit $?} restores the expected behavior.
17431 Some shell scripts, such as those generated by @command{autoconf}, use a
17432 trap to clean up before exiting.  If the last shell command exited with
17433 nonzero status, the trap also exits with nonzero status so that the
17434 invoker can tell that an error occurred.
17436 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17437 trap ignores the @code{exit} command's argument.  In these shells, a trap
17438 cannot determine whether it was invoked by plain @code{exit} or by
17439 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17440 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17443 @anchor{export}
17444 @item @command{export}
17445 @c -------------------
17446 @prindex @command{export}
17447 The builtin @command{export} dubs a shell variable @dfn{environment
17448 variable}.  Each update of exported variables corresponds to an update
17449 of the environment variables.  Conversely, each environment variable
17450 received by the shell when it is launched should be imported as a shell
17451 variable marked as exported.
17453 Alas, many shells, such as Solaris @command{/bin/sh},
17454 IRIX 6.3, IRIX 5.2,
17455 AIX 4.1.5, and Digital Unix 4.0, forget to
17456 @command{export} the environment variables they receive.  As a result,
17457 two variables coexist: the environment variable and the shell
17458 variable.  The following code demonstrates this failure:
17460 @example
17461 #!/bin/sh
17462 echo $FOO
17463 FOO=bar
17464 echo $FOO
17465 exec /bin/sh $0
17466 @end example
17468 @noindent
17469 when run with @samp{FOO=foo} in the environment, these shells print
17470 alternately @samp{foo} and @samp{bar}, although they should print only
17471 @samp{foo} and then a sequence of @samp{bar}s.
17473 Therefore you should @command{export} again each environment variable
17474 that you update; the export can occur before or after the assignment.
17476 Posix is not clear on whether the @command{export} of an undefined
17477 variable causes the variable to be defined with the value of an empty
17478 string, or merely marks any future definition of a variable by that name
17479 for export.  Various shells behave differently in this regard:
17481 @example
17482 $ @kbd{sh -c 'export foo; env | grep foo'}
17483 $ @kbd{ash -c 'export foo; env | grep foo'}
17484 foo=
17485 @end example
17487 @item @command{false}
17488 @c ------------------
17489 @prindex @command{false}
17490 Don't expect @command{false} to exit with status 1: in native
17491 Solaris @file{/bin/false} exits with status 255.
17494 @item @command{for}
17495 @c ----------------
17496 @prindex @command{for}
17497 To loop over positional arguments, use:
17499 @example
17500 for arg
17502   echo "$arg"
17503 done
17504 @end example
17506 @noindent
17507 You may @emph{not} leave the @code{do} on the same line as @code{for},
17508 since some shells improperly grok:
17510 @example
17511 for arg; do
17512   echo "$arg"
17513 done
17514 @end example
17516 If you want to explicitly refer to the positional arguments, given the
17517 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17519 @example
17520 for arg in $@{1+"$@@"@}; do
17521   echo "$arg"
17522 done
17523 @end example
17525 @noindent
17526 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17527 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17528 item @samp{$@@}, for more.
17530 In Solaris @command{/bin/sh}, when the list of arguments of a
17531 @command{for} loop starts with @emph{unquoted} tokens looking like
17532 variable assignments, the loop is not executed on those tokens:
17534 @example
17535 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17538 @end example
17540 @noindent
17541 Thankfully, quoting the assignment-like tokens, or starting the list
17542 with other tokens (including unquoted variable expansion that results in
17543 an assignment-like result), avoids the problem, so it is easy to work
17544 around:
17546 @example
17547 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17549 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17552 @end example
17554 @anchor{if}
17555 @item @command{if}
17556 @c ---------------
17557 @prindex @command{if}
17558 Using @samp{!} is not portable.  Instead of:
17560 @example
17561 if ! cmp -s file file.new; then
17562   mv file.new file
17564 @end example
17566 @noindent
17567 use:
17569 @example
17570 if cmp -s file file.new; then :; else
17571   mv file.new file
17573 @end example
17575 @noindent
17576 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17577 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17578 of conditionals:
17580 @example
17581 AS_IF([cmp -s file file.new], [], [mv file.new file])
17582 @end example
17584 This is especially useful in other M4 macros, where the @dfn{then} and
17585 @dfn{else} branches might be macro arguments.
17587 Some very old shells did not reset the exit status from an @command{if}
17588 with no @command{else}:
17590 @example
17591 $ @kbd{if (exit 42); then true; fi; echo $?}
17593 @end example
17595 @noindent
17596 whereas a proper shell should have printed @samp{0}.  But this is no
17597 longer a portability problem; any shell that supports functions gets it
17598 correct.  However, it explains why some makefiles have lengthy
17599 constructs:
17601 @example
17602 if test -f "$file"; then
17603   install "$file" "$dest"
17604 else
17605   :
17607 @end example
17610 @item @command{printf}
17611 @c ------------------
17612 @prindex @command{printf}
17613 A format string starting with a @samp{-} can cause problems.
17614 Bash interprets it as an option and
17615 gives an error.  And @samp{--} to mark the end of options is not good
17616 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17617 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17618 or @samp{%s} is probably easiest:
17620 @example
17621 printf %s -foo
17622 @end example
17624 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17626 @example
17627 $ @kbd{printf '\045'}
17628 bash: printf: `%': missing format character
17629 @end example
17631 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17632 example, @file{/usr/bin/printf} is buggy, so when using
17633 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17634 core.
17636 Since @command{printf} is not always a shell builtin, there is a
17637 potential speed penalty for using @code{printf '%s\n'} as a replacement
17638 for an @command{echo} that does not interpret @samp{\} or leading
17639 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17640 -r --} for this role instead.
17642 For a discussion of portable alternatives to both @command{printf}
17643 and @command{echo}, @xref{echo, , Limitations of Shell Builtins}.
17646 @item @command{pwd}
17647 @c ----------------
17648 @prindex @command{pwd}
17649 With modern shells, plain @command{pwd} outputs a ``logical''
17650 directory name, some of whose components may be symbolic links.  These
17651 directory names are in contrast to ``physical'' directory names, whose
17652 components are all directories.
17654 Posix 1003.1-2001 requires that @command{pwd} must support
17655 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17656 with @option{-L} being the default.  However, traditional shells do
17657 not support these options, and their @command{pwd} command has the
17658 @option{-P} behavior.
17660 Portable scripts should assume neither option is supported, and should
17661 assume neither behavior is the default.  Also, on many hosts
17662 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17663 does not require this behavior and portable scripts should not rely on
17666 Typically it's best to use plain @command{pwd}.  On modern hosts this
17667 outputs logical directory names, which have the following advantages:
17669 @itemize @bullet
17670 @item
17671 Logical names are what the user specified.
17672 @item
17673 Physical names may not be portable from one installation
17674 host to another due to network file system gymnastics.
17675 @item
17676 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
17677 some parent directory, but plain @command{pwd} cannot fail for this
17678 reason.
17679 @end itemize
17681 Also please see the discussion of the @command{cd} command.
17684 @item @command{read}
17685 @c -----------------
17686 @prindex @command{read}
17687 No options are portable, not even support @option{-r} (Solaris
17688 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
17689 @command{read} as a special built-in, so it may exit if input is
17690 redirected from a non-existent or unreadable file.
17693 @anchor{set}
17694 @item @command{set}
17695 @c ----------------
17696 @prindex @command{set}
17697 With the FreeBSD 6.0 shell, the @command{set} command (without
17698 any options) does not sort its output.
17700 The @command{set} builtin faces the usual problem with arguments
17701 starting with a
17702 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
17703 the end of the options (any argument after @option{--} is a parameter,
17704 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
17705 10 @command{/bin/sh}) simply stop option
17706 processing as soon as a non-option argument is found.  Therefore, use
17707 @samp{dummy} or simply @samp{x} to end the option processing, and use
17708 @command{shift} to pop it out:
17710 @example
17711 set x $my_list; shift
17712 @end example
17714 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
17715 longer requires support for this command, and in traditional shells
17716 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
17717 makes scripts harder to debug.
17719 Some nonstandard shells do not recognize more than one option
17720 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
17721 better to combine them:
17723 @example
17724 set -ex
17725 @end example
17727 @cindex @command{set -e}
17728 The option @option{-e} has historically been underspecified, with enough
17729 ambiguities to cause numerous differences across various shell
17730 implementations; see for example
17731 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
17732 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
17733 documenting a change to Posix 2008 to match @command{ksh88} behavior.
17734 Note that mixing @code{set -e} and shell functions is asking for surprises:
17736 @example
17737 set -e
17738 doit()
17740   rm file
17741   echo one
17743 doit || echo two
17744 @end example
17746 @noindent
17747 According to the recommendation, @samp{one} should always be output
17748 regardless of whether the @command{rm} failed, because it occurs within
17749 the body of the shell function @samp{doit} invoked on the left side of
17750 @samp{||}, where the effects of @samp{set -e} are not enforced.
17751 Likewise, @samp{two} should never be printed, since the failure of
17752 @command{rm} does not abort the function, such that the status of
17753 @samp{doit} is 0.
17755 The BSD shell has had several problems with the @option{-e}
17756 option.  Older versions of the BSD
17757 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
17758 @samp{case} when @option{-e} was in effect, causing the shell to exit
17759 unexpectedly in some cases.  This was particularly a problem with
17760 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
17761 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
17762 wrapper works around the bug (@pxref{Failure in Make Rules}).
17764 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
17765 wrongly exit with @option{-e} if the last command within a compound
17766 statement fails and is guarded by an @samp{&&} only.  For example:
17768 @example
17769 #! /bin/sh
17770 set -e
17771 foo=''
17772 test -n "$foo" && exit 1
17773 echo one
17774 if :; then
17775   test -n "$foo" && exit 1
17776   echo two
17777   test -n "$foo" && exit 1
17779 echo three
17780 @end example
17782 @noindent
17783 does not print @samp{three}.  One workaround is to change the last
17784 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
17785 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
17786 users not to use @samp{sh -e}.
17788 When @samp{set -e} is in effect, a failed command substitution in
17789 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
17791 @example
17792 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
17793 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
17796 @end example
17798 @noindent
17799 Moreover, a command substitution, successful or not, causes this shell to
17800 exit from a failing outer command even in presence of an @samp{&&} list:
17802 @example
17803 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
17805 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
17807 @end example
17809 Portable scripts should not use @samp{set -e} if @command{trap} is used
17810 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
17811 sometimes enters the trap handler with the exit status of the command
17812 prior to the one that triggered the errexit handler:
17814 @example
17815 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
17817 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
17819 @end example
17821 @noindent
17822 Thus, when writing a script in M4sh, rather than trying to rely on
17823 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
17824 statement where it is desirable to abort on failure.
17826 @cindex @command{set -b}
17827 @cindex @command{set -m}
17828 Job control is not provided by all shells, so the use of @samp{set -m}
17829 or @samp{set -b} must be done with care.  When using @command{zsh} in
17830 native mode, asynchronous notification (@samp{set -b}) is enabled by
17831 default, and using @samp{emulate sh} to switch to Posix mode does not
17832 clear this setting (although asynchronous notification has no impact
17833 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
17834 earlier have a bug where job control can be manipulated in interactive
17835 shells, but not in subshells or scripts.  Furthermore, some shells, like
17836 @command{pdksh}, fail to treat subshells as interactive, even though the
17837 parent shell was.
17839 @example
17840 $ @kbd{echo $ZSH_VERSION}
17841 4.3.10
17842 $ @kbd{set -m; echo $?}
17844 $ @kbd{zsh -c 'set -m; echo $?'}
17845 set: can't change option: -m
17846 $ @kbd{(set -m); echo $?}
17847 set: can't change option: -m
17849 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
17852 @end example
17855 @item @command{shift}
17856 @c ------------------
17857 @prindex @command{shift}
17858 Not only is @command{shift}ing a bad idea when there is nothing left to
17859 shift, but in addition it is not portable: the shell of MIPS
17860 RISC/OS 4.52 refuses to do it.
17862 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
17863 it is also absent in many pre-Posix shells.
17866 @item @command{source}
17867 @c -------------------
17868 @prindex @command{source}
17869 This command is not portable, as Posix does not require it; use
17870 @command{.} instead.
17873 @item @command{test}
17874 @c -----------------
17875 @prindex @command{test}
17876 The @code{test} program is the way to perform many file and string
17877 tests.  It is often invoked by the alternate name @samp{[}, but using
17878 that name in Autoconf code is asking for trouble since it is an M4 quote
17879 character.
17881 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
17882 present in all implementations, and have been marked obsolete by Posix
17883 2008.  This is because there are inherent ambiguities in using them.
17884 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
17885 check whether two strings are both non-empty, but if @samp{$1} is the
17886 literal @samp{!}, then some implementations of @command{test} treat it
17887 as a negation of the unary operator @option{-a}.
17889 Thus, portable uses of @command{test} should never have more than four
17890 arguments, and scripts should use shell constructs like @samp{&&} and
17891 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
17892 statement, keep in mind that they have equal precedence, so it is often
17893 better to parenthesize even when this is redundant.  For example:
17895 @smallexample
17896 # Not portable:
17897 test "X$a" = "X$b" -a \
17898   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
17900 # Portable:
17901 test "X$a" = "X$b" &&
17902   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
17903 @end smallexample
17905 @command{test} does not process options like most other commands do; for
17906 example, it does not recognize the @option{--} argument as marking the
17907 end of options.
17909 It is safe to use @samp{!} as a @command{test} operator.  For example,
17910 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
17911 -d foo; @dots{}} is not.
17914 @item @command{test} (files)
17915 @c -------------------------
17916 To enable @command{configure} scripts to support cross-compilation, they
17917 shouldn't do anything that tests features of the build system instead of
17918 the host system.  But occasionally you may find it necessary to check
17919 whether some arbitrary file exists.  To do so, use @samp{test -f} or
17920 @samp{test -r}.  Do not use @samp{test -x}, because 4.3BSD does not
17921 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
17922 lacks it.  To test for symbolic links on systems that have them, use
17923 @samp{test -h} rather than @samp{test -L}; either form conforms to
17924 Posix 1003.1-2001, but older shells like Solaris 8
17925 @code{/bin/sh} support only @option{-h}.
17927 @item @command{test} (strings)
17928 @c ---------------------------
17929 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
17930 not null, but this usage is not portable to traditional platforms like
17931 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
17932 @samp{-n}.
17934 Posix also says that @samp{test ! "@var{string}"},
17935 @samp{test -n "@var{string}"} and
17936 @samp{test -z "@var{string}"} work with any string, but many
17937 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
17938 Digital Unix 4, etc.)@: get confused if
17939 @var{string} looks like an operator:
17941 @example
17942 $ @kbd{test -n =}
17943 test: argument expected
17944 $ @kbd{test ! -n}
17945 test: argument expected
17946 $ @kbd{test -z ")"; echo $?}
17948 @end example
17950 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
17951 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
17952 strings, but in practice this is not true for troublesome strings that
17953 look like operators or parentheses, or that begin with @samp{-}.
17955 It is best to protect such strings with a leading @samp{X}, e.g.,
17956 @samp{test "X@var{string}" != X} rather than @samp{test -n
17957 "@var{string}"} or @samp{test ! "@var{string}"}.
17959 It is common to find variations of the following idiom:
17961 @example
17962 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
17963   @var{action}
17964 @end example
17966 @noindent
17967 to take an action when a token matches a given pattern.  Such constructs
17968 should be avoided by using:
17970 @example
17971 case $ac_feature in
17972   *[!-a-zA-Z0-9_]*) @var{action};;
17973 esac
17974 @end example
17976 If the pattern is a complicated regular expression that cannot be
17977 expressed as a shell pattern, use something like this instead:
17979 @example
17980 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
17981   @var{action}
17982 @end example
17984 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
17985 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
17986 @samp{@var{foo}} contains backslashes.
17989 @anchor{trap}
17990 @item @command{trap}
17991 @c -----------------
17992 @prindex @command{trap}
17993 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
17994 trap 0, i.e., have the @command{trap} run when the script ends (either via an
17995 explicit @command{exit}, or the end of the script).  The trap for 0 should be
17996 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
17997 will invoke the trap at the end of this function.
17999 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18000 specified signals to their default values, but many common shells (e.g.,
18001 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18002 ``command'' named @command{-} when the specified conditions arise.
18003 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18004 reset traps, as this is supported by a larger set of shells, but there
18005 are still shells like @command{dash} that mistakenly try to execute
18006 @command{1} instead of resetting the traps.  Therefore, there is no
18007 portable workaround, except for @samp{trap - 0}, for which
18008 @samp{trap '' 0} is a portable substitute.
18010 Although Posix is not absolutely clear on this point, it is widely
18011 admitted that when entering the trap @samp{$?} should be set to the exit
18012 status of the last command run before the trap.  The ambiguity can be
18013 summarized as: ``when the trap is launched by an @command{exit}, what is
18014 the @emph{last} command run: that before @command{exit}, or
18015 @command{exit} itself?''
18017 Bash considers @command{exit} to be the last command, while Zsh and
18018 Solaris @command{/bin/sh} consider that when the trap is run it is
18019 @emph{still} in the @command{exit}, hence it is the previous exit status
18020 that the trap receives:
18022 @example
18023 $ @kbd{cat trap.sh}
18024 trap 'echo $?' 0
18025 (exit 42); exit 0
18026 $ @kbd{zsh trap.sh}
18028 $ @kbd{bash trap.sh}
18030 @end example
18032 The portable solution is then simple: when you want to @samp{exit 42},
18033 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18034 set the exit status to 42 for Zsh, and the second to trigger the trap
18035 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18036 @code{AS_EXIT}.
18038 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18039 reset to 0 by empty lines if the code is inside @command{trap}.
18041 @example
18042 $ @kbd{trap 'false}
18044 echo $?' 0
18045 $ @kbd{exit}
18047 @end example
18049 @noindent
18050 Fortunately, this bug only affects @command{trap}.
18052 Several shells fail to execute an exit trap that is defined inside a
18053 subshell, when the last command of that subshell is not a builtin.  A
18054 workaround is to use @samp{exit $?} as the shell builtin.
18056 @example
18057 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18059 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18060 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18062 @end example
18064 @noindent
18065 Likewise, older implementations of @command{bash} failed to preserve
18066 @samp{$?} across an exit trap consisting of a single cleanup command.
18068 @example
18069 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18071 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18073 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18075 @end example
18077 @item @command{true}
18078 @c -----------------
18079 @prindex @command{true}
18080 @c Info cannot handle `:' in index entries.
18081 @c @prindex @command{:}
18082 Don't worry: as far as we know @command{true} is portable.
18083 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18084 portable shell community tends to prefer using @command{:}.  This has a
18085 funny side effect: when asked whether @command{false} is more portable
18086 than @command{true} Alexandre Oliva answered:
18088 @quotation
18089 In a sense, yes, because if it doesn't exist, the shell will produce an
18090 exit status of failure, which is correct for @command{false}, but not
18091 for @command{true}.
18092 @end quotation
18094 Remember that even though @samp{:} ignores its arguments, it still takes
18095 time to compute those arguments.  It is a good idea to use double quotes
18096 around any arguments to @samp{:} to avoid time spent in field splitting
18097 and file name expansion.
18100 @anchor{unset}
18101 @item @command{unset}
18102 @c ------------------
18103 @prindex @command{unset}
18104 In some nonconforming shells (e.g., NetBSD 5.99.43 sh or Bash 2.05a),
18105 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18106 with @code{set -e} operation.  You can use
18108 @smallexample
18109 FOO=; unset FOO
18110 @end smallexample
18112 @noindent
18113 if you are not sure that @code{FOO} is set.
18115 A few ancient shells lack @command{unset} entirely.  For some variables
18116 such as @code{PS1}, you can use a neutralizing value instead:
18118 @smallexample
18119 PS1='$ '
18120 @end smallexample
18122 Usually, shells that do not support @command{unset} need less effort to
18123 make the environment sane, so for example is not a problem if you cannot
18124 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18125 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18126 So, you should do something like
18128 @smallexample
18129 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18130 @end smallexample
18132 @noindent
18133 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18134 @ref{export, , Limitations of Builtins}, for
18135 the case of environment variables.
18137 @item @command{wait}
18138 @c -----------------
18139 @prindex @command{wait}
18140 The exit status of @command{wait} is not always reliable.
18141 @end table
18143 @node Limitations of Usual Tools
18144 @section Limitations of Usual Tools
18145 @cindex Limitations of usual tools
18147 The small set of tools you can expect to find on any machine can still
18148 include some limitations you should be aware of.
18150 @comment Between this list and the list of builtins above, we should
18151 @comment mention all the tools in GNU Coding Standards ``Utilities in
18152 @comment Makefiles''.
18154 @c This table includes things like `@command{expr} (|)', so we can't
18155 @c use @table @command.
18156 @table @asis
18157 @anchor{awk}
18158 @item @command{awk}
18159 @c ----------------
18160 @prindex @command{awk}
18161 Don't leave white space before the opening parenthesis in a user function call.
18162 Posix does not allow this and GNU Awk rejects it:
18164 @example
18165 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18166         BEGIN @{ die () @}'}
18167 gawk: cmd. line:2:         BEGIN @{ die () @}
18168 gawk: cmd. line:2:                      ^ parse error
18169 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18170         BEGIN @{ die() @}'}
18171 Aaaaarg!
18172 @end example
18174 Posix says that if a program contains only @samp{BEGIN} actions, and
18175 contains no instances of @code{getline}, then the program merely
18176 executes the actions without reading input.  However, traditional Awk
18177 implementations (such as Solaris 10 @command{awk}) read and discard
18178 input in this case.  Portable scripts can redirect input from
18179 @file{/dev/null} to work around the problem.  For example:
18181 @example
18182 awk 'BEGIN @{print "hello world"@}' </dev/null
18183 @end example
18185 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18186 @samp{$1}) retain their value from the last record read, if no
18187 intervening @samp{getline} occurred.  However, some implementations
18188 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18189 @samp{awk}) reset these variables.  A workaround is to use an
18190 intermediate variable prior to the @samp{END} block.  For example:
18192 @example
18193 $ @kbd{cat end.awk}
18194 @{ tmp = $1 @}
18195 END @{ print "a", $1, $NF, "b", tmp @}
18196 $ @kbd{echo 1 | awk -f end.awk}
18197 a   b 1
18198 $ @kbd{echo 1 | gawk -f end.awk}
18199 a 1 1 b 1
18200 @end example
18202 If you want your program to be deterministic, don't depend on @code{for}
18203 on arrays:
18205 @example
18206 $ @kbd{cat for.awk}
18207 END @{
18208   arr["foo"] = 1
18209   arr["bar"] = 1
18210   for (i in arr)
18211     print i
18213 $ @kbd{gawk -f for.awk </dev/null}
18216 $ @kbd{nawk -f for.awk </dev/null}
18219 @end example
18221 Some Awk implementations, such as HP-UX 11.0's native one,
18222 mishandle anchors:
18224 @example
18225 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18226 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18228 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18229 xfoo
18230 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18232 @end example
18234 @noindent
18235 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18236 or use a simple test to reject such implementations.
18238 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18239 after @code{%u}:
18241 @example
18242 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18243 0 0
18244 @end example
18246 AIX version 5.2 has an arbitrary limit of 399 on the
18247 length of regular expressions and literal strings in an Awk program.
18249 Traditional Awk implementations derived from Unix version 7, such as
18250 Solaris @command{/bin/awk}, have many limitations and do not
18251 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18252 Programs}) finds you an Awk that doesn't have these problems, but if
18253 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18254 address them.  For more detailed descriptions, see @ref{Language
18255 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18257 Traditional Awk does not support multidimensional arrays or user-defined
18258 functions.
18260 Traditional Awk does not support the @option{-v} option.  You can use
18261 assignments after the program instead, e.g., @code{$AWK '@{print v
18262 $1@}' v=x}; however, don't forget that such assignments are not
18263 evaluated until they are encountered (e.g., after any @code{BEGIN}
18264 action).
18266 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18268 Traditional Awk does not support the expressions
18269 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18270 or @code{@var{a}^=@var{b}}.
18272 Traditional Awk does not support the predefined @code{CONVFMT} or
18273 @code{ENVIRON} variables.
18275 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18276 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18277 @code{sqrt}, and @code{substr}.
18279 Traditional Awk @code{getline} is not at all compatible with Posix;
18280 avoid it.
18282 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18283 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18285 In code portable to both traditional and modern Awk, @code{FS} must be a
18286 string containing just one ordinary character, and similarly for the
18287 field-separator argument to @code{split}.
18289 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18290 implementations, like Tru64's, split the input even if you don't refer
18291 to any field in the script, to circumvent this problem, set @samp{FS}
18292 to an unusual character and use @code{split}.
18294 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18295 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18296 dumps core.
18298 The original version of Awk had a limit of at most 99 bytes per
18299 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18300 per run of non-special characters in a @code{printf} format, but these
18301 bugs have been fixed on all practical hosts that we know of.
18303 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18304 of at most 3070 bytes.
18306 @item @command{basename}
18307 @c ---------------------
18308 @prindex @command{basename}
18309 Not all hosts have a working @command{basename}.
18310 You can use @command{expr} instead.
18312 @c AS_BASENAME is to be replaced by a better API.
18313 @ignore
18314 Not all hosts have a working @command{basename}, and you should instead
18315 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18316 @command{expr} if you need to strip a suffix.  For example:
18318 @example
18319 a=`basename "$aname"`       # This is not portable.
18320 a=`AS_BASENAME(["$aname"])` # This is more portable.
18322 # This is not portable.
18323 c=`basename "$cname" .c`
18325 # This is more portable.
18326 c=`AS_BASENAME(["$cname"])`
18327 case $c in
18328 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18329 esac
18330 @end example
18331 @end ignore
18334 @item @command{cat}
18335 @c ----------------
18336 @prindex @command{cat}
18337 Don't rely on any option.
18340 @item @command{cc}
18341 @c ---------------
18342 @prindex @command{cc}
18343 The command @samp{cc -c foo.c} traditionally produces an object file
18344 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18345 with @option{-o} to specify a different object file name, but
18346 Posix does not require this combination and a few compilers
18347 lack support for it.  @xref{C Compiler}, for how GNU Make
18348 tests for this feature with @code{AC_PROG_CC_C_O}.
18350 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18351 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18353 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18354 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18355 nothing.
18357 The default executable, produced by @samp{cc foo.c}, can be
18359 @itemize
18360 @item @file{a.out} --- usual Posix convention.
18361 @item @file{b.out} --- i960 compilers (including @command{gcc}).
18362 @item @file{a.exe} --- DJGPP port of @command{gcc}.
18363 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
18364 @item @file{foo.exe} --- various MS-DOS compilers.
18365 @end itemize
18367 The C compiler's traditional name is @command{cc}, but other names like
18368 @command{gcc} are common.  Posix 1003.1-2001 specifies the
18369 name @command{c99}, but older Posix editions specified
18370 @command{c89} and anyway these standard names are rarely used in
18371 practice.  Typically the C compiler is invoked from makefiles that use
18372 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18373 compiler name.
18375 @item @command{chgrp}
18376 @itemx @command{chown}
18377 @c -------------------
18378 @prindex @command{chgrp}
18379 @prindex @command{chown}
18380 It is not portable to change a file's group to a group that the owner
18381 does not belong to.
18383 @item @command{chmod}
18384 @c ------------------
18385 @prindex @command{chmod}
18386 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18387 instead, for two reasons.  First, plain @option{-w} does not necessarily
18388 make the file unwritable, since it does not affect mode bits that
18389 correspond to bits in the file mode creation mask.  Second,
18390 Posix says that the @option{-w} might be interpreted as an
18391 implementation-specific option, not as a mode; Posix suggests
18392 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18393 @samp{--} does not work on some older hosts.
18396 @item @command{cmp}
18397 @c ----------------
18398 @prindex @command{cmp}
18399 @command{cmp} performs a raw data comparison of two files, while
18400 @command{diff} compares two text files.  Therefore, if you might compare
18401 DOS files, even if only checking whether two files are different, use
18402 @command{diff} to avoid spurious differences due to differences of
18403 newline encoding.
18406 @item @command{cp}
18407 @c ---------------
18408 @prindex @command{cp}
18409 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18410 obsolescent and its behavior on special files is implementation-defined.
18411 Use @option{-R} instead.  On GNU hosts the two options
18412 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18413 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18414 corrupt its own memory with some directory hierarchies and error out or
18415 dump core:
18417 @example
18418 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18419 @kbd{touch 12345678/12345678/x}
18420 @kbd{cp -R 12345678 t}
18421 cp: 0653-440 12345678/12345678/: name too long.
18422 @end example
18424 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18425 trailing slashes at the end of nonexistent destination directories.  To
18426 avoid this problem, omit the trailing slashes.  For example, use
18427 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18428 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18430 @c This is thanks to Ian.
18431 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
18432 its @command{mv} does.
18434 @cindex timestamp resolution
18435 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18436 -p} copied the timestamps exactly.  However, many modern file systems
18437 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18438 @samp{cp -p} implementations truncate timestamps when copying files,
18439 which can cause the destination file to appear to be older than the
18440 source.  The exact amount of truncation depends on the resolution of
18441 the system calls that @command{cp} uses.  Traditionally this was
18442 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18443 implementations such as GNU Core Utilities 5.0.91 (2003) use
18444 @code{utimes}, which has 1-microsecond resolution.  Modern
18445 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18446 the full nanosecond resolution, using the modern system calls
18447 @code{futimens} and @code{utimensat} when they are available.  As of
18448 2011, though, many platforms do not yet fully support these new system
18449 calls.
18451 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18452 ownerships.  But whether it actually does copy ownerships or not is a
18453 system dependent policy decision implemented by the kernel.  If the
18454 kernel allows it then it happens.  If the kernel does not allow it then
18455 it does not happen.  It is not something @command{cp} itself has control
18456 over.
18458 In Unix System V any user can chown files to any other user, and System
18459 V also has a non-sticky @file{/tmp}.  That probably derives from the
18460 heritage of System V in a business environment without hostile users.
18461 BSD changed this
18462 to be a more secure model where only root can @command{chown} files and
18463 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18464 of BSD in a campus environment.
18466 GNU/Linux and Solaris by default follow BSD, but
18467 can be configured to allow a System V style @command{chown}.  On the
18468 other hand, HP-UX follows System V, but can
18469 be configured to use the modern security model and disallow
18470 @command{chown}.  Since it is an administrator-configurable parameter
18471 you can't use the name of the kernel as an indicator of the behavior.
18475 @item @command{date}
18476 @c -----------------
18477 @prindex @command{date}
18478 Some versions of @command{date} do not recognize special @samp{%} directives,
18479 and unfortunately, instead of complaining, they just pass them through,
18480 and exit with success:
18482 @example
18483 $ @kbd{uname -a}
18484 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18485 $ @kbd{date "+%s"}
18487 @end example
18490 @item @command{diff}
18491 @c -----------------
18492 @prindex @command{diff}
18493 Option @option{-u} is nonportable.
18495 Some implementations, such as Tru64's, fail when comparing to
18496 @file{/dev/null}.  Use an empty file instead.
18499 @item @command{dirname}
18500 @c --------------------
18501 @prindex @command{dirname}
18502 Not all hosts have a working @command{dirname}, and you should instead
18503 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18505 @example
18506 dir=`dirname "$file"`       # This is not portable.
18507 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18508 @end example
18511 @item @command{egrep}
18512 @c ------------------
18513 @prindex @command{egrep}
18514 Posix 1003.1-2001 no longer requires @command{egrep},
18515 but many hosts do not yet support the Posix
18516 replacement @code{grep -E}.  Also, some traditional implementations do
18517 not work on long input lines.  To work around these problems, invoke
18518 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18520 Portable extended regular expressions should use @samp{\} only to escape
18521 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18522 is not portable, even though it typically matches @samp{@}}.
18524 The empty alternative is not portable.  Use @samp{?} instead.  For
18525 instance with Digital Unix v5.0:
18527 @example
18528 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18529 |foo
18530 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18531 bar|
18532 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18534 |bar
18535 @end example
18537 @command{$EGREP} also suffers the limitations of @command{grep}
18538 (@pxref{grep, , Limitations of Usual Tools}).
18540 @item @command{expr}
18541 @c -----------------
18542 @prindex @command{expr}
18543 Not all implementations obey the Posix rule that @samp{--} separates
18544 options from arguments; likewise, not all implementations provide the
18545 extension to Posix that the first argument can be treated as part of a
18546 valid expression rather than an invalid option if it begins with
18547 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18548 @samp{$var} might be a negative number, to keep @command{expr} from
18549 interpreting it as an option.
18551 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18552 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18553 misinterpreting @var{word}.
18555 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18557 @item @command{expr} (@samp{|})
18558 @prindex @command{expr} (@samp{|})
18559 You can use @samp{|}.  Although Posix does require that @samp{expr
18560 ''} return the empty string, it does not specify the result when you
18561 @samp{|} together the empty string (or zero) with the empty string.  For
18562 example:
18564 @example
18565 expr '' \| ''
18566 @end example
18568 Posix 1003.2-1992 returns the empty string
18569 for this case, but traditional Unix returns @samp{0} (Solaris is
18570 one such example).  In Posix 1003.1-2001, the specification was
18571 changed to match traditional Unix's behavior (which is
18572 bizarre, but it's too late to fix this).  Please note that the same
18573 problem does arise when the empty string results from a computation,
18574 as in:
18576 @example
18577 expr bar : foo \| foo : bar
18578 @end example
18580 @noindent
18581 Avoid this portability problem by avoiding the empty string.
18584 @item @command{expr} (@samp{:})
18585 @c ----------------------------
18586 @prindex @command{expr}
18587 Portable @command{expr} regular expressions should use @samp{\} to
18588 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18589 For example, alternation, @samp{\|}, is common but Posix does not
18590 require its support, so it should be avoided in portable scripts.
18591 Similarly, @samp{\+} and @samp{\?} should be avoided.
18593 Portable @command{expr} regular expressions should not begin with
18594 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18595 not needed anyway.
18597 On the other hand, the behavior of the @samp{$} anchor is not portable
18598 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18599 each line, as was done in older versions of the GNU Core Utilities, or
18600 whether it applies only to the end of the overall string, as in
18601 Coreutils 6.0 and most other implementations.
18603 @example
18604 $ @kbd{baz='foo}
18605 > @kbd{bar'}
18606 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18608 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18610 @end example
18612 The Posix standard is ambiguous as to whether
18613 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18614 In practice, it outputs the empty string on most platforms, but portable
18615 scripts should not assume this.  For instance, the QNX 4.25 native
18616 @command{expr} returns @samp{0}.
18618 One might think that a way to get a uniform behavior would be to use
18619 the empty string as a default value:
18621 @example
18622 expr a : '\(b\)' \| ''
18623 @end example
18625 @noindent
18626 Unfortunately this behaves exactly as the original expression; see the
18627 @command{expr} (@samp{|}) entry for more information.
18629 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
18630 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
18631 @command{expr} to fail if the matched substring is longer than 120
18632 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
18633 @command{expr} fails.  Nowadays this is of practical importance only for
18634 the rare installer who mistakenly puts @file{/usr/ucb} before
18635 @file{/usr/bin} in @env{PATH}.
18637 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
18638 some cases.  For example, the command
18639 @example
18640 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
18641 @end example
18643 @noindent
18644 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
18645 This particular case can be worked around by substituting @samp{[^--]}
18646 for @samp{[^-]}.
18648 Don't leave, there is some more!
18650 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
18651 the empty string, has a funny behavior in its exit status: it's always 1
18652 when parentheses are used!
18654 @example
18655 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
18656 0: 1
18657 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
18658 1: 0
18660 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
18661 1: a
18662 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
18663 1: 0
18664 @end example
18666 @noindent
18667 In practice this can be a big problem if you are ready to catch failures
18668 of @command{expr} programs with some other method (such as using
18669 @command{sed}), since you may get twice the result.  For instance
18671 @example
18672 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
18673 @end example
18675 @noindent
18676 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
18677 simple workaround consists of testing @command{expr} and using a variable
18678 set to @command{expr} or to @command{false} according to the result.
18680 Tru64 @command{expr} incorrectly treats the result as a number, if it
18681 can be interpreted that way:
18683 @example
18684 $ @kbd{expr 00001 : '.*\(...\)'}
18686 @end example
18688 On HP-UX 11, @command{expr} only supports a single
18689 sub-expression.
18691 @example
18692 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
18693 expr: More than one '\(' was used.
18694 @end example
18697 @item @command{fgrep}
18698 @c ------------------
18699 @prindex @command{fgrep}
18700 Posix 1003.1-2001 no longer requires @command{fgrep},
18701 but many hosts do not yet support the Posix
18702 replacement @code{grep -F}.  Also, some traditional implementations do
18703 not work on long input lines.  To work around these problems, invoke
18704 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
18706 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
18709 @item @command{find}
18710 @c -----------------
18711 @prindex @command{find}
18712 The option @option{-maxdepth} seems to be GNU specific.
18713 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
18714 commands do not understand it.
18716 The replacement of @samp{@{@}} is guaranteed only if the argument is
18717 exactly @emph{@{@}}, not if it's only a part of an argument.  For
18718 instance on DU, and HP-UX 10.20 and HP-UX 11:
18720 @example
18721 $ @kbd{touch foo}
18722 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
18723 @{@}-@{@}
18724 @end example
18726 @noindent
18727 while GNU @command{find} reports @samp{./foo-./foo}.
18730 @anchor{grep}
18731 @item @command{grep}
18732 @c -----------------
18733 @prindex @command{grep}
18734 Portable scripts can rely on the @command{grep} options @option{-c},
18735 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
18736 options.  For example, don't use @option{-w}, as Posix does not require
18737 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
18738 portable scripts should not combine @option{-c} with @option{-l},
18739 as Posix does not allow this.
18741 Some of the options required by Posix are not portable in practice.
18742 Don't use @samp{grep -q} to suppress output, because many @command{grep}
18743 implementations (e.g., Solaris) do not support @option{-q}.
18744 Don't use @samp{grep -s} to suppress output either, because Posix
18745 says @option{-s} does not suppress output, only some error messages;
18746 also, the @option{-s} option of traditional @command{grep} behaved
18747 like @option{-q} does in most modern implementations.  Instead,
18748 redirect the standard output and standard error (in case the file
18749 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
18750 status of @code{grep} to determine whether it found a match.
18752 The QNX4 implementation fails to count lines with @code{grep -c '$'},
18753 but works with @code{grep -c '^'}.  Other alternatives for counting
18754 lines are to use @code{sed -n '$='} or @code{wc -l}.
18756 Some traditional @command{grep} implementations do not work on long
18757 input lines.  On AIX the default @code{grep} silently truncates long
18758 lines on the input before matching.
18760 Also, many implementations do not support multiple regexps
18761 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
18762 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
18763 work around these problems, invoke @code{AC_PROG_GREP} and then use
18764 @code{$GREP}.
18766 Another possible workaround for the multiple @option{-e} problem is to
18767 separate the patterns by newlines, for example:
18769 @example
18770 grep 'foo
18771 bar' in.txt
18772 @end example
18774 @noindent
18775 except that this fails with traditional @command{grep}
18776 implementations and with OpenBSD 3.8 @command{grep}.
18778 Traditional @command{grep} implementations (e.g., Solaris) do not
18779 support the @option{-E} or @option{-F} options.  To work around these
18780 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
18781 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
18782 willing to require support for Posix @command{grep}, your script should
18783 not use both @option{-E} and @option{-F}, since Posix does not allow
18784 this combination.
18786 Portable @command{grep} regular expressions should use @samp{\} only to
18787 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
18788 alternation, @samp{\|}, is common but Posix does not require its
18789 support in basic regular expressions, so it should be avoided in
18790 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
18791 Similarly, the following escape sequences should also be avoided:
18792 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
18793 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
18795 Posix does not specify the behavior of @command{grep} on binary files.
18796 An example where this matters is using BSD @command{grep} to
18797 search text that includes embedded ANSI escape sequences for
18798 colored output to terminals (@samp{\033[m} is the sequence to restore
18799 normal output); the behavior depends on whether input is seekable:
18801 @example
18802 $ @kbd{printf 'esc\033[mape\n' > sample}
18803 $ @kbd{grep . sample}
18804 Binary file sample matches
18805 $ @kbd{cat sample | grep .}
18806 escape
18807 @end example
18810 @item @command{join}
18811 @c -----------------
18812 @prindex @command{join}
18813 Solaris 8 @command{join} has bugs when the second operand is standard
18814 input, and when standard input is a pipe.  For example, the following
18815 shell script causes Solaris 8 @command{join} to loop forever:
18817 @example
18818 cat >file <<'EOF'
18819 1 x
18820 2 y
18822 cat file | join file -
18823 @end example
18825 Use @samp{join - file} instead.
18827 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
18828 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
18829 the workaround is to use @command{join -a1 file1 file2} instead.
18831 @item @command{ln}
18832 @c ---------------
18833 @prindex @command{ln}
18834 @cindex Symbolic links
18835 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
18836 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
18838 For versions of the DJGPP before 2.04,
18839 @command{ln} emulates symbolic links
18840 to executables by generating a stub that in turn calls the real
18841 program.  This feature also works with nonexistent files like in the
18842 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
18843 which attempts to call @file{file.exe} if run.  But this feature only
18844 works for executables, so @samp{cp -p} is used instead for these
18845 systems.  DJGPP versions 2.04 and later have full support
18846 for symbolic links.
18849 @item @command{ls}
18850 @c ---------------
18851 @prindex @command{ls}
18852 @cindex Listing directories
18853 The portable options are @option{-acdilrtu}.  Current practice is for
18854 @option{-l} to output both owner and group, even though ancient versions
18855 of @command{ls} omitted the group.
18857 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
18858 to standard output if @file{foo} did not exist.  Hence a shell command
18859 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
18860 was equivalent to @samp{sources='*.c not found'} in the absence of
18861 @samp{.c} files.  This is no longer a practical problem, since current
18862 @command{ls} implementations send diagnostics to standard error.
18864 The behavior of @command{ls} on a directory that is being concurrently
18865 modified is not always predictable, because of a data race where cached
18866 information returned by @code{readdir} does not match the current
18867 directory state.  In fact, MacOS 10.5 has an intermittent bug where
18868 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
18869 once if other files were added or removed from the directory immediately
18870 prior to the @command{ls} call.  Since @command{ls} already sorts its
18871 output, the duplicate entries can be avoided by piping the results
18872 through @code{uniq}.
18874 @anchor{mkdir}
18875 @item @command{mkdir}
18876 @c ------------------
18877 @prindex @command{mkdir}
18878 @cindex Making directories
18879 No @command{mkdir} option is portable to older systems.  Instead of
18880 @samp{mkdir -p @var{file-name}}, you should use
18881 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
18882 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
18884 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
18885 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
18886 @command{mkdir} incorrectly attempts to change the permissions of
18887 @var{dir} even if it already exists.  HP-UX 11.23 and
18888 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
18889 any newly-created parents of @var{dir}.
18891 Posix does not clearly specify whether @samp{mkdir -p foo}
18892 should succeed when @file{foo} is a symbolic link to an already-existing
18893 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
18894 succeeds, but Solaris @command{mkdir} fails.
18896 Traditional @code{mkdir -p} implementations suffer from race conditions.
18897 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
18898 at the same time, both processes might detect that @file{a} is missing,
18899 one might create @file{a}, then the other might try to create @file{a}
18900 and fail with a @code{File exists} diagnostic.  The GNU Core
18901 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
18902 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
18903 race-free when two processes invoke @code{mkdir -p} simultaneously, but
18904 earlier versions are vulnerable.  Solaris @command{mkdir} is still
18905 vulnerable as of Solaris 10, and other traditional Unix systems are
18906 probably vulnerable too.  This possible race is harmful in parallel
18907 builds when several Make rules call @code{mkdir -p} to
18908 construct directories.  You may use
18909 @code{install-sh -d} as a safe replacement, provided this script is
18910 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
18911 OK, but copies from older versions are vulnerable.
18914 @item @command{mkfifo}
18915 @itemx @command{mknod}
18916 @c -------------------
18917 @prindex @command{mkfifo}
18918 @prindex @command{mknod}
18919 The GNU Coding Standards state that @command{mknod} is safe to use on
18920 platforms where it has been tested to exist; but it is generally portable
18921 only for creating named FIFOs, since device numbers are
18922 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
18923 testsuites.  Posix states that behavior is unspecified when opening a
18924 named FIFO for both reading and writing; on at least Cygwin, this
18925 results in failure on any attempt to read or write to that file
18926 descriptor.
18928 @item @command{mktemp}
18929 @c -------------------
18930 @prindex @command{mktemp}
18931 @cindex Creating temporary files
18932 Shell scripts can use temporary files safely with @command{mktemp}, but
18933 it does not exist on all systems.  A portable way to create a safe
18934 temporary file name is to create a temporary directory with mode 700 and
18935 use a file inside this directory.  Both methods prevent attackers from
18936 gaining control, though @command{mktemp} is far less likely to fail
18937 gratuitously under attack.
18939 Here is sample code to create a new temporary directory @samp{$dir} safely:
18941 @example
18942 # Create a temporary directory $dir in $TMPDIR (default /tmp).
18943 # Use mktemp if possible; otherwise fall back on mkdir,
18944 # with $RANDOM to make collisions less likely.
18945 : "$@{TMPDIR:=/tmp@}"
18947   dir=`
18948     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
18949   ` &&
18950   test -d "$dir"
18951 @} || @{
18952   dir=$TMPDIR/foo$$-$RANDOM
18953 @c $$ restore font-lock
18954   (umask 077 && mkdir "$dir")
18955 @} || exit $?
18956 @end example
18959 @item @command{mv}
18960 @c ---------------
18961 @prindex @command{mv}
18962 @cindex Moving open files
18963 The only portable options are @option{-f} and @option{-i}.
18965 Moving individual files between file systems is portable (it was in Unix
18966 version 6),
18967 but it is not always atomic: when doing @samp{mv new existing}, there's
18968 a critical section where neither the old nor the new version of
18969 @file{existing} actually exists.
18971 On some systems moving files from @file{/tmp} can sometimes cause
18972 undesirable (but perfectly valid) warnings, even if you created these
18973 files.  This is because @file{/tmp} belongs to a group that ordinary
18974 users are not members of, and files created in @file{/tmp} inherit
18975 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
18976 a diagnostic without failing:
18978 @smallexample
18979 $ @kbd{touch /tmp/foo}
18980 $ @kbd{mv /tmp/foo .}
18981 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
18982 $ @kbd{echo $?}
18984 $ @kbd{ls foo}
18986 @end smallexample
18988 @noindent
18989 This annoying behavior conforms to Posix, unfortunately.
18991 Moving directories across mount points is not portable, use @command{cp}
18992 and @command{rm}.
18994 DOS variants cannot rename or remove open files, and do not
18995 support commands like @samp{mv foo bar >foo}, even though this is
18996 perfectly portable among Posix hosts.
18999 @item @command{od}
19000 @c ---------------
19001 @prindex @command{od}
19003 In Mac OS X 10.3, @command{od} does not support the
19004 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19005 @option{-t}, or the XSI option @option{-s}.  The only
19006 supported Posix option is @option{-v}, and the only supported
19007 XSI options are those in @option{-bcdox}.  The BSD
19008 @command{hexdump} program can be used instead.
19010 This problem no longer exists in Mac OS X 10.4.3.
19013 @item @command{rm}
19014 @c ---------------
19015 @prindex @command{rm}
19016 The @option{-f} and @option{-r} options are portable.
19018 It is not portable to invoke @command{rm} without operands.  For
19019 example, on many systems @samp{rm -f -r} (with no other arguments)
19020 silently succeeds without doing anything, but it fails with a diagnostic
19021 on NetBSD 2.0.2.
19023 A file might not be removed even if its parent directory is writable
19024 and searchable.  Many Posix hosts cannot remove a mount point, a named
19025 stream, a working directory, or a last link to a file that is being
19026 executed.
19028 DOS variants cannot rename or remove open files, and do not
19029 support commands like @samp{rm foo >foo}, even though this is
19030 perfectly portable among Posix hosts.
19032 @item @command{rmdir}
19033 @c ------------------
19034 @prindex @command{rmdir}
19035 Just as with @command{rm}, some platforms refuse to remove a working
19036 directory.
19038 @anchor{sed}
19039 @item @command{sed}
19040 @c ----------------
19041 @prindex @command{sed}
19042 Patterns should not include the separator (unless escaped), even as part
19043 of a character class.  In conformance with Posix, the Cray
19044 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19045 Even when escaped, patterns should not include separators that are also
19046 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19047 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19048 before evaluating the basic regular expression.
19050 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19051 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19052 them.
19054 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19056 Sed scripts should not use branch labels longer than 7 characters and
19057 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19058 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19059 48 labels, which can not be circumvented by using more than one script
19060 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19061 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19062 about 6000 bytes for the internal representation of commands.
19064 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19065 NetBSD 1.4.2's, incorrectly try to interpret the second
19066 @samp{;} as a command:
19068 @example
19069 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19070 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19071 @end example
19073 Input should not have unreasonably long lines, since some @command{sed}
19074 implementations have an input buffer limited to 4000 bytes.  Likewise,
19075 not all @command{sed} implementations can handle embedded @code{NUL} or
19076 a missing trailing newline.
19078 Remember that ranges within a bracket expression of a regular expression
19079 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19080 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19081 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19082 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19083 than to rely on @samp{[A-Z]}.
19085 Additionally, Posix states that regular expressions are only
19086 well-defined on characters.  Unfortunately, there exist platforms such
19087 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19088 even though that platform has a single-byte @samp{C} locale.  And Posix
19089 allows the existence of a multi-byte @samp{C} locale, although that does
19090 not yet appear to be a common implementation.  At any rate, it means
19091 that not all bytes will be matched by the regular expression @samp{.}:
19093 @example
19094 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19096 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19098 @end example
19100 Portable @command{sed} regular expressions should use @samp{\} only to escape
19101 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19102 alternation, @samp{\|}, is common but Posix does not require its
19103 support, so it should be avoided in portable scripts.  Solaris
19104 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19105 deletes only lines that contain the literal string @samp{a|b}.
19106 Similarly, @samp{\+} and @samp{\?} should be avoided.
19108 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19110 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19111 quite portable to current hosts, but was not supported by some ancient
19112 @command{sed} implementations like SVR3.
19114 Some @command{sed} implementations, e.g., Solaris, restrict the special
19115 role of the asterisk @samp{*} to one-character regular expressions and
19116 back-references, and the special role of interval expressions
19117 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19118 to one-character regular expressions.  This may lead to unexpected behavior:
19120 @example
19121 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19122 x2x4
19123 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19125 @end example
19127 The @option{-e} option is mostly portable.
19128 However, its argument
19129 cannot start with @samp{a}, @samp{c}, or @samp{i},
19130 as this runs afoul of a Tru64 5.1 bug.
19131 Also, its argument cannot be empty, as this fails on AIX 5.3.
19132 Some people prefer to use @samp{-e}:
19134 @example
19135 sed -e '@var{command-1}' \
19136     -e '@var{command-2}'
19137 @end example
19139 @noindent
19140 as opposed to the equivalent:
19142 @example
19143 sed '
19144   @var{command-1}
19145   @var{command-2}
19147 @end example
19149 @noindent
19150 The following usage is sometimes equivalent:
19152 @example
19153 sed '@var{command-1};@var{command-2}'
19154 @end example
19156 but Posix says that this use of a semicolon has undefined effect if
19157 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19158 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19159 should use semicolon only with simple scripts that do not use these
19160 verbs.
19162 Posix up to the 2008 revision requires the argument of the @option{-e}
19163 option to be a syntactically complete script.  GNU @command{sed} allows
19164 to pass multiple script fragments, each as argument of a separate
19165 @option{-e} option, that are then combined, with newlines between the
19166 fragments, and a future Posix revision may allow this as well.  This
19167 approach is not portable with script fragments ending in backslash; for
19168 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19169 don't allow splitting in this case:
19171 @example
19172 $ @kbd{echo a | sed -n -e 'i\}
19173 @kbd{0'}
19175 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19176 Unrecognized command: 0
19177 @end example
19179 @noindent
19180 In practice, however, this technique of joining fragments
19181 through @option{-e} works for multiple @command{sed} functions within
19182 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19184 @example
19185 @c The quote around the closing brace silences interactive zsh.
19186 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19188 @end example
19190 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19191 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19192 each command must be followed immediately by a newline, without any
19193 intervening blanks or semicolons.  The closing bracket must be alone on
19194 a line, other than white space preceding or following it.  However, a
19195 future version of Posix may standardize the use of addresses within brackets.
19197 Contrary to yet another urban legend, you may portably use @samp{&} in
19198 the replacement part of the @code{s} command to mean ``what was
19199 matched''.  All descendants of Unix version 7 @command{sed}
19200 (at least; we
19201 don't have first hand experience with older @command{sed} implementations) have
19202 supported it.
19204 Posix requires that you must not have any white space between
19205 @samp{!} and the following command.  It is OK to have blanks between
19206 the address and the @samp{!}.  For instance, on Solaris:
19208 @example
19209 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19210 @error{}Unrecognized command: /bar/ ! p
19211 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19212 @error{}Unrecognized command: /bar/! p
19213 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19215 @end example
19217 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19218 you use @samp{!}, it is best to put it on a command that is delimited by
19219 newlines rather than @samp{;}.
19221 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19222 @samp{w} commands be followed by exactly one space before their argument.
19223 On the other hand, no white space is allowed between @samp{:} and the
19224 subsequent label name.
19226 If a sed script is specified on the command line and ends in an
19227 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19228 should be followed by a newline.  Otherwise some @command{sed}
19229 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19230 inserted text.
19232 Many @command{sed} implementations (e.g., MacOS X 10.4,
19233 OpenBSD 3.9, Solaris 10
19234 @command{/usr/ucb/sed}) strip leading white space from the text of
19235 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19236 work around this incompatibility with Posix:
19238 @example
19239 $ @kbd{echo flushleft | sed 'a\}
19240 > @kbd{   indented}
19241 > @kbd{'}
19242 flushleft
19243 indented
19244 $ @kbd{echo foo | sed 'a\}
19245 > @kbd{\   indented}
19246 > @kbd{'}
19247 flushleft
19248    indented
19249 @end example
19251 Posix requires that with an empty regular expression, the last non-empty
19252 regular expression from either an address specification or substitution
19253 command is applied.  However, busybox 1.6.1 complains when using a
19254 substitution command with a replacement containing a back-reference to
19255 an empty regular expression; the workaround is repeating the regular
19256 expression.
19258 @example
19259 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19260 sed: No previous regexp.
19261 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19263 @end example
19266 @item @command{sed} (@samp{t})
19267 @c ---------------------------
19268 @prindex @command{sed} (@samp{t})
19269 Some old systems have @command{sed} that ``forget'' to reset their
19270 @samp{t} flag when starting a new cycle.  For instance on MIPS
19271 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19272 script (the line numbers are not actual part of the texts):
19274 @example
19275 s/keep me/kept/g  # a
19276 t end             # b
19277 s/.*/deleted/g    # c
19278 :end              # d
19279 @end example
19281 @noindent
19284 @example
19285 delete me         # 1
19286 delete me         # 2
19287 keep me           # 3
19288 delete me         # 4
19289 @end example
19291 @noindent
19292 you get
19294 @example
19295 deleted
19296 delete me
19297 kept
19298 deleted
19299 @end example
19301 @noindent
19302 instead of
19304 @example
19305 deleted
19306 deleted
19307 kept
19308 deleted
19309 @end example
19311 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19312 flag, and the output is produced.  When processing
19313 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19314 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19315 flag when a substitution fails.  Command (b) sees that the flag is set,
19316 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19317 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19318 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19319 Finally, since the flag is clear, line 4 is processed properly.
19321 There are two things one should remember about @samp{t} in @command{sed}.
19322 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19323 succeeded, not only the immediately preceding substitution.  Therefore,
19324 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19325 line, to reset the @samp{t} flag where needed.
19327 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19328 cycle.
19330 One portable implementation of the script above is:
19332 @example
19333 t clear
19334 :clear
19335 s/keep me/kept/g
19336 t end
19337 s/.*/deleted/g
19338 :end
19339 @end example
19341 @item @command{sleep}
19342 @c ------------------
19343 @prindex @command{sleep}
19344 Using @command{sleep} is generally portable.  However, remember that
19345 adding a @command{sleep} to work around timestamp issues, with a minimum
19346 granularity of one second, doesn't scale well for parallel builds on
19347 modern machines with sub-second process completion.
19349 @item @command{sort}
19350 @c -----------------
19351 @prindex @command{sort}
19352 Remember that sort order is influenced by the current locale.  Inside
19353 @file{configure}, the C locale is in effect, but in Makefile snippets,
19354 you may need to specify @code{LC_ALL=C sort}.
19356 @item @command{tar}
19357 @c ----------------
19358 @prindex @command{tar}
19359 There are multiple file formats for @command{tar}; if you use Automake,
19360 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19361 level of portability to use.
19363 @anchor{touch}
19364 @item @command{touch}
19365 @c ------------------
19366 @prindex @command{touch}
19367 @cindex timestamp resolution
19368 If you specify the desired timestamp (e.g., with the @option{-r}
19369 option), older @command{touch} implementations use the @code{utime} or
19370 @code{utimes} system call, which can result in the same kind of
19371 timestamp truncation problems that @samp{cp -p} has.
19373 On ancient BSD systems, @command{touch} or any command that
19374 results in an empty file does not update the timestamps, so use a
19375 command like @command{echo} as a workaround.
19376 Also,
19377 GNU @command{touch} 3.16r (and presumably all before that)
19378 fails to work on SunOS 4.1.3 when the empty file is on an
19379 NFS-mounted 4.2 volume.
19380 However, these problems are no longer of practical concern.
19382 @item @command{tr}
19383 @c ---------------
19384 @prindex @command{tr}
19385 @cindex carriage return, deleting
19386 @cindex newline, deleting
19387 @cindex deleting carriage return
19388 Not all versions of @command{tr} handle all backslash character escapes.
19389 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19390 Solaris contains more modern @command{tr} in other locations.
19391 Using octal escapes is more portable for carriage returns, since
19392 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19393 literal carriage returns in scripts causes a number of other problems.
19394 But for other characters, like newline, using octal escapes ties the
19395 operation to ASCII, so it is better to use literal characters.
19397 @example
19398 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19400 light
19401 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19402 moonlight
19403 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19404 moonlight
19405 $ @kbd{nl='}
19406 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19407 moonlight
19408 @end example
19410 Not all versions of @command{tr} recognize direct ranges of characters: at
19411 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19412 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19413 transliterate to themselves).
19415 @example
19416 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19417 HAZy FAntAZy
19418 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19419 HAZY FANTAZY
19420 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19421 HAZY FANTAZY
19422 @end example
19424 When providing two arguments, be sure the second string is at least as
19425 long as the first.
19427 @example
19428 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19430 $ @kbd{echo abc | coreutils/tr bc d}
19432 @end example
19434 Posix requires @command{tr} to operate on binary files.  But at least
19435 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19436 @code{NUL} in the input prior to doing any translation.  When using
19437 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19438 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19439 @command{/usr/xpg6/bin/tr} if that is available.
19441 @example
19442 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19443  61 62
19444 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19445  61 62
19446 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19447  61 00 62
19448 @end example
19450 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19451 octal escape for @code{NUL}.
19453 @example
19454 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19455  61 62 63
19456 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19457  61 00 64
19458 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19459  61 00 64
19460 @end example
19462 @end table
19465 @node Portable Make
19466 @chapter Portable Make Programming
19467 @prindex @command{make}
19468 @cindex Limitations of @command{make}
19470 Writing portable makefiles is an art.  Since a makefile's commands are
19471 executed by the shell, you must consider the shell portability issues
19472 already mentioned.  However, other issues are specific to @command{make}
19473 itself.
19475 @menu
19476 * $< in Ordinary Make Rules::   $< in ordinary rules
19477 * Failure in Make Rules::       Failing portably in rules
19478 * Special Chars in Names::      Special Characters in Macro Names
19479 * Backslash-Newline-Newline::   Empty last lines in macro definitions
19480 * Backslash-Newline Comments::  Spanning comments across line boundaries
19481 * Long Lines in Makefiles::     Line length limitations
19482 * Macros and Submakes::         @code{make macro=value} and submakes
19483 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19484 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19485 * Parallel Make::               Parallel @command{make} quirks
19486 * Comments in Make Rules::      Other problems with Make comments
19487 * Newlines in Make Rules::      Using literal newlines in rules
19488 * Comments in Make Macros::     Other problems with Make comments in macros
19489 * Trailing whitespace in Make Macros::  Macro substitution problems
19490 * Command-line Macros and whitespace::  Whitespace trimming of values
19491 * obj/ and Make::               Don't name a subdirectory @file{obj}
19492 * make -k Status::              Exit status of @samp{make -k}
19493 * VPATH and Make::              @code{VPATH} woes
19494 * Single Suffix Rules::         Single suffix rules and separated dependencies
19495 * Timestamps and Make::         Subsecond timestamp resolution
19496 @end menu
19498 @node $< in Ordinary Make Rules
19499 @section @code{$<} in Ordinary Make Rules
19501 Posix says that the @samp{$<} construct in makefiles can be
19502 used only in inference rules and in the @samp{.DEFAULT} rule; its
19503 meaning in ordinary rules is unspecified.  Solaris @command{make}
19504 for instance replaces it with the empty string.  OpenBSD (3.0 and
19505 later) @command{make} diagnoses these uses and errors out.
19507 @node Failure in Make Rules
19508 @section Failure in Make Rules
19510 Posix 2008 requires that @command{make} must invoke each command with
19511 the equivalent of a @samp{sh -e -c} subshell, which causes the
19512 subshell to exit immediately if a subsidiary simple-command fails,
19513 although not all @command{make} implementations have historically
19514 followed this rule.  For
19515 example, the command @samp{touch T; rm -f U} may attempt to
19516 remove @file{U} even if the @command{touch} fails, although this is not
19517 permitted with Posix make.  One way to work around failures in simple
19518 commands is to reword them so that they always succeed, e.g., @samp{touch
19519 T || :; rm -f U}.
19520 However, even this approach can run into common bugs in BSD
19521 implementations of the @option{-e} option of @command{sh} and
19522 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19523 are worried
19524 about porting to buggy BSD shells it may be simpler to migrate
19525 complicated @command{make} actions into separate scripts.
19527 @node Special Chars in Names
19528 @section Special Characters in Make Macro Names
19530 Posix limits macro names to nonempty strings containing only
19531 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19532 @command{make} implementations allow a wider variety of characters, but
19533 portable makefiles should avoid them.  It is portable to start a name
19534 with a special character, e.g., @samp{$(.FOO)}.
19536 Some ancient @command{make} implementations don't support leading
19537 underscores in macro names.  An example is NEWS-OS 4.2R.
19539 @example
19540 $ @kbd{cat Makefile}
19541 _am_include = #
19542 _am_quote =
19543 all:; @@echo this is test
19544 $ @kbd{make}
19545 Make: Must be a separator on rules line 2.  Stop.
19546 $ @kbd{cat Makefile2}
19547 am_include = #
19548 am_quote =
19549 all:; @@echo this is test
19550 $ @kbd{make -f Makefile2}
19551 this is test
19552 @end example
19554 @noindent
19555 However, this problem is no longer of practical concern.
19557 @node Backslash-Newline-Newline
19558 @section Backslash-Newline-Newline in Make Macro Values
19560 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19561 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19562 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19563 On some versions of HP-UX, @command{make} reads multiple newlines
19564 following a backslash, continuing to the next non-empty line.  For
19565 example,
19567 @example
19568 FOO = one \
19570 BAR = two
19572 test:
19573         : FOO is "$(FOO)"
19574         : BAR is "$(BAR)"
19575 @end example
19577 @noindent
19578 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19579 sensibly let a backslash continue only to the immediately following
19580 line.
19582 @node Backslash-Newline Comments
19583 @section Backslash-Newline in Make Comments
19585 According to Posix, Make comments start with @code{#}
19586 and continue until an unescaped newline is reached.
19588 @example
19589 $ @kbd{cat Makefile}
19590 # A = foo \
19591       bar \
19592       baz
19594 all:
19595         @@echo ok
19596 $ @kbd{make}   # GNU make
19598 @end example
19600 @noindent
19601 However this is not always the case.  Some implementations
19602 discard everything from @code{#} through the end of the line, ignoring any
19603 trailing backslash.
19605 @example
19606 $ @kbd{pmake}  # BSD make
19607 "Makefile", line 3: Need an operator
19608 Fatal errors encountered -- cannot continue
19609 @end example
19611 @noindent
19612 Therefore, if you want to comment out a multi-line definition, prefix each
19613 line with @code{#}, not only the first.
19615 @example
19616 # A = foo \
19617 #     bar \
19618 #     baz
19619 @end example
19621 @node Long Lines in Makefiles
19622 @section Long Lines in Makefiles
19624 Tru64 5.1's @command{make} has been reported to crash when given a
19625 makefile with lines longer than around 20 kB.  Earlier versions are
19626 reported to exit with @code{Line too long} diagnostics.
19628 @node Macros and Submakes
19629 @section @code{make macro=value} and Submakes
19631 A command-line variable definition such as @code{foo=bar} overrides any
19632 definition of @code{foo} in a makefile.  Some @command{make}
19633 implementations (such as GNU @command{make}) propagate this
19634 override to subsidiary invocations of @command{make}.  Some other
19635 implementations do not pass the substitution along to submakes.
19637 @example
19638 $ @kbd{cat Makefile}
19639 foo = foo
19640 one:
19641         @@echo $(foo)
19642         $(MAKE) two
19643 two:
19644         @@echo $(foo)
19645 $ @kbd{make foo=bar}            # GNU make 3.79.1
19647 make two
19648 make[1]: Entering directory `/home/adl'
19650 make[1]: Leaving directory `/home/adl'
19651 $ @kbd{pmake foo=bar}           # BSD make
19653 pmake two
19655 @end example
19657 You have a few possibilities if you do want the @code{foo=bar} override
19658 to propagate to submakes.  One is to use the @option{-e}
19659 option, which causes all environment variables to have precedence over
19660 the makefile macro definitions, and declare foo as an environment
19661 variable:
19663 @example
19664 $ @kbd{env foo=bar make -e}
19665 @end example
19667 The @option{-e} option is propagated to submakes automatically,
19668 and since the environment is inherited between @command{make}
19669 invocations, the @code{foo} macro is overridden in
19670 submakes as expected.
19672 This syntax (@code{foo=bar make -e}) is portable only when used
19673 outside of a makefile, for instance from a script or from the
19674 command line.  When run inside a @command{make} rule, GNU
19675 @command{make} 3.80 and prior versions forget to propagate the
19676 @option{-e} option to submakes.
19678 Moreover, using @option{-e} could have unexpected side effects if your
19679 environment contains some other macros usually defined by the
19680 makefile.  (See also the note about @code{make -e} and @code{SHELL}
19681 below.)
19683 If you can foresee all macros that a user might want to override, then
19684 you can propagate them to submakes manually, from your makefile:
19686 @example
19687 foo = foo
19688 one:
19689         @@echo $(foo)
19690         $(MAKE) foo=$(foo) two
19691 two:
19692         @@echo $(foo)
19693 @end example
19695 Another way to propagate a variable to submakes in a portable way is to
19696 expand an extra variable in every invocation of @samp{$(MAKE)} within
19697 your makefile:
19699 @example
19700 foo = foo
19701 one:
19702         @@echo $(foo)
19703         $(MAKE) $(SUBMAKEFLAGS) two
19704 two:
19705         @@echo $(foo)
19706 @end example
19708 Users must be aware that this technique is in use to take advantage of
19709 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
19710 allows any macro to be overridden.  Makefiles generated by
19711 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
19712 on the command lines of submakes (@pxref{Subdirectories, , Automake,
19713 automake, GNU Automake}).
19715 @node The Make Macro MAKEFLAGS
19716 @section The Make Macro MAKEFLAGS
19717 @cindex @code{MAKEFLAGS} and @command{make}
19718 @cindex @command{make} and @code{MAKEFLAGS}
19720 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
19721 current and recursive invocations of make, but allows implementations
19722 several formats for the variable.  It is tricky to parse
19723 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
19724 or @option{-k} for continued execution are in effect.  For example, you
19725 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
19726 contains single-letter options, since in the Cygwin version of
19727 GNU @command{make} it is either @option{--unix} or
19728 @option{--win32} with the second word containing single-letter options.
19730 @example
19731 $ @kbd{cat Makefile}
19732 all:
19733         @@echo MAKEFLAGS = $(MAKEFLAGS)
19734 $ @kbd{make}
19735 MAKEFLAGS = --unix
19736 $ @kbd{make -k}
19737 MAKEFLAGS = --unix -k
19738 @end example
19740 @node The Make Macro SHELL
19741 @section The Make Macro @code{SHELL}
19742 @cindex @code{SHELL} and @command{make}
19743 @cindex @command{make} and @code{SHELL}
19745 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
19746 macro to spawn shell processes and execute Make rules.  This
19747 is a builtin macro supplied by @command{make}, but it can be modified
19748 by a makefile or by a command-line argument.
19750 Not all @command{make} implementations define this @code{SHELL} macro.
19751 Tru64
19752 @command{make} is an example; this implementation always uses
19753 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
19754 your makefiles.  If you use Autoconf, do
19756 @example
19757 SHELL = @@SHELL@@
19758 @end example
19760 @noindent
19761 If you use Automake, this is done for you.
19763 Do not force @code{SHELL = /bin/sh} because that is not correct
19764 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
19765 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
19766 Additionally, DJGPP lacks @code{/bin/sh}, and when its
19767 GNU @command{make} port sees such a setting it enters a
19768 special emulation mode where features like pipes and redirections are
19769 emulated on top of DOS's @command{command.com}.  Unfortunately this
19770 emulation is incomplete; for instance it does not handle command
19771 substitutions.  Using @code{@@SHELL@@} means that your makefile will
19772 benefit from the same improved shell, such as @command{bash} or
19773 @command{ksh}, that was discovered during @command{configure}, so that
19774 you aren't fighting two different sets of shell bugs between the two
19775 contexts.
19777 Posix-compliant @command{make} should never acquire the value of
19778 $(SHELL) from the environment, even when @code{make -e} is used
19779 (otherwise, think about what would happen to your rules if
19780 @code{SHELL=/bin/tcsh}).
19782 However not all @command{make} implementations have this exception.
19783 For instance it's not surprising that Tru64 @command{make} doesn't
19784 protect @code{SHELL}, since it doesn't use it.
19786 @example
19787 $ @kbd{cat Makefile}
19788 SHELL = /bin/sh
19789 FOO = foo
19790 all:
19791         @@echo $(SHELL)
19792         @@echo $(FOO)
19793 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
19794 /bin/tcsh
19796 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
19797 /bin/sh
19799 @end example
19801 Conversely, @command{make} is not supposed to export any changes to the
19802 macro @code{SHELL} to child processes.  Again, many implementations
19803 break this rule:
19805 @example
19806 $ @kbd{cat Makefile}
19807 all:
19808         @@echo $(SHELL)
19809         @@printenv SHELL
19810 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
19811 /bin/ksh
19812 /bin/ksh
19813 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
19814 /bin/ksh
19816 @end example
19818 @node Parallel Make
19819 @section Parallel Make
19820 @cindex Parallel @command{make}
19822 Support for parallel execution in @command{make} implementation varies.
19823 Generally, using GNU make is your best bet.
19825 Some make implementations (among them, FreeBSD @command{make}, NetBSD
19826 @command{make}, and Solaris @command{dmake}), when invoked with a
19827 @option{-j@var{N}} option, connect the standard output and standard
19828 error of all their child processes to pipes or temporary regular
19829 files.  This can lead to subtly different semantics in the behaviour
19830 of the spawned processes.  For example, even if the @command{make}
19831 standard output is connected to a tty, the recipe command will not be:
19833 @example
19834 $ @kbd{cat Makefile}
19835 all:
19836         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
19837 $ @kbd{make -j 2} # FreeBSD make
19838 Is not a tty
19839 $ @kbd{make -j 2} # NetBSD make
19840 --- all ---
19841 Is not a tty
19842 $ @kbd{dmake -j 2} # Solaris dmake
19843 @var{hostname} --> 1 job
19844 @var{hostname} --> Job output
19845 Is not a tty
19846 @end example
19848 @noindent
19849 On the other hand:
19851 @example
19852 $ @kbd{make -j 2} # GNU make, Heirloom make
19853 Is a tty
19854 @end example
19856 Furthermore, parallel runs of those @command{make} implementations will
19857 route standard error from commands that they spawn into their own
19858 standard output, and may remove leading whitespace from output lines.
19860 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
19861 reuse the same shell for multiple commands within one recipe.  This can
19862 have unexpected consequences. For example, change of directories or
19863 variables persist between commands:
19865 @example
19866 all:
19867         @@var=value; cd /; pwd; echo $$var; echo $$$$
19868         @@pwd; echo $$var; echo $$$$
19869 @end example
19871 @noindent
19872 may output the following with @code{make -j1}:
19874 @example
19875 --- all ---
19877 value
19878 32235
19880 value
19881 32235
19882 @end example
19884 while without @option{-j1}, or with @option{-B}, the output looks less
19885 surprising:
19887 @example
19889 value
19890 32238
19891 /tmp
19893 32239
19894 @end example
19896 Another consequence of this is that, if one command in a recipe uses
19897 @code{exit 0} to indicate a successful exit, the shell will be gone
19898 and the remaining commands of this recipe will not be executed.
19900 The above example also shows additional status output produced by NetBSD
19901 @command{make} (but @emph{not} by FreeBSD @command{make}) in parallel
19902 mode for targets being updated.
19904 You can avoid these issues by using the @option{-B} option to enable
19905 compatibility semantics.  However, that will effectively also disable
19906 all parallelism as that will cause prerequisites to be updated in the
19907 order they are listed in a rule.
19909 @node Comments in Make Rules
19910 @section Comments in Make Rules
19911 @cindex Comments in @file{Makefile} rules
19912 @cindex @file{Makefile} rules and comments
19914 Never put comments in a rule.
19916 Some @command{make} treat anything starting with a tab as a command for
19917 the current rule, even if the tab is immediately followed by a @code{#}.
19918 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
19919 makefile runs @code{# foo} through the shell.
19921 @example
19922 all:
19923         # foo
19924 @end example
19926 As a workaround, you can use the @command{:} no-op command with a string
19927 argument that gets ignored:
19929 @example
19930 all:
19931         : "foo"
19932 @end example
19934 Conversely, if you want to use the @samp{#} character in some command,
19935 you can only do so by expanding it inside a rule (@pxref{Comments in
19936 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
19937 @command{config.status} as @samp{#}, then the following substitutes
19938 @samp{@@COMMENT_CHAR@@} in a generated header:
19940 @example
19941 foo.h: foo.h.in
19942         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
19943             $(srcdir)/foo.h.in > $@@
19944 @end example
19946 The funny shell quoting avoids a substitution at @command{config.status}
19947 run time of the left-hand side of the @command{sed} @samp{s} command.
19949 @node Newlines in Make Rules
19950 @section Newlines in Make Rules
19951 @cindex Newlines in @file{Makefile} rules
19952 @cindex @file{Makefile} rules and newlines
19954 In shell scripts, newlines can be used inside string literals.  But in
19955 the shell statements of @file{Makefile} rules, this is not possible:
19956 A newline not preceded by a backslash is a separator between shell
19957 statements.  Whereas a newline that is preceded by a backslash becomes
19958 part of the shell statement according to POSIX, but gets replaced,
19959 together with the backslash that precedes it, by a space in GNU
19960 @command{make} 3.80 and older.  So, how can a newline be used in a string
19961 literal?
19963 The trick is to set up a shell variable that contains a newline:
19965 @example
19966 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
19967 @end example
19969 For example, in order to create a multiline @samp{sed} expression that
19970 inserts a blank line after every line of a file, this code can be used:
19972 @example
19973 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
19974 sed -e "s/\$$/\\$$@{nl@}/" < input > output
19975 @end example
19977 @node Comments in Make Macros
19978 @section Comments in Make Macros
19979 @cindex Comments in @file{Makefile} macros
19980 @cindex @file{Makefile} macros and comments
19982 Avoid putting comments in macro values as far as possible.  Posix
19983 specifies that the text starting from the @samp{#} sign until the end of
19984 the line is to be ignored, which has the unfortunate effect of
19985 disallowing them even within quotes.  Thus, the following might lead to
19986 a syntax error at compile time:
19988 @example
19989 CPPFLAGS = "-DCOMMENT_CHAR='#'"
19990 @end example
19992 @noindent
19993 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
19994 Luckily, most @command{make} implementations disregard this and treat
19995 single and double quotes specially here; @pxref{Comments in Make Rules},
19996 for a more portable alternative.
19998 Even without quoting involved, comments can have surprising effects,
19999 because the whitespace before them is part of the variable value:
20001 @example
20002 foo = bar # trailing comment
20003 print: ; @@echo "$(foo)."
20004 @end example
20006 @noindent
20007 prints @samp{bar .}, which is usually not intended, and can expose
20008 @command{make} bugs as described below.
20010 @node Trailing whitespace in Make Macros
20011 @section Trailing whitespace in Make Macros
20012 @cindex whitespace in @file{Makefile} macros
20013 @cindex @file{Makefile} macros and whitespace
20015 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20016 substitutions and appends another spurious suffix:
20018 @example
20019 empty =
20020 foo = bar $(empty)
20021 print: ; @@echo $(foo:=.test)
20022 @end example
20024 @noindent
20025 prints @samp{bar.test .test}.
20027 BSD and Solaris @command{make} implementations do not honor trailing
20028 whitespace in macro definitions as Posix requires:
20030 @example
20031 foo = bar # Note the space after "bar".
20032 print: ; @@echo $(foo)t
20033 @end example
20035 @noindent
20036 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20037 can use a helper macro as in the previous example.
20040 @node Command-line Macros and whitespace
20041 @section Command-line Macros and whitespace
20042 @cindex whitespace in command-line macros
20043 @cindex command-line, macros set on
20044 @cindex environment, macros set from
20046 Some @command{make} implementations may strip trailing whitespace off
20047 of macros set on the command line in addition to leading whitespace.
20048 Further, some may strip leading whitespace off of macros set from
20049 environment variables:
20051 @example
20052 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20053   foo=' f f ' make -f - bar=' b b '}
20054 x f f xb b x  # AIX, BSD, GNU make
20055 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20056 x f f xb bx   # Solaris make
20057 @end example
20060 @node obj/ and Make
20061 @section The @file{obj/} Subdirectory and Make
20062 @cindex @file{obj/}, subdirectory
20063 @cindex BSD @command{make} and @file{obj/}
20065 Never name one of your subdirectories @file{obj/} if you don't like
20066 surprises.
20068 If an @file{obj/} directory exists, BSD @command{make} enters it
20069 before reading the makefile.  Hence the makefile in the
20070 current directory is not read.
20072 @example
20073 $ @kbd{cat Makefile}
20074 all:
20075         echo Hello
20076 $ @kbd{cat obj/Makefile}
20077 all:
20078         echo World
20079 $ @kbd{make}      # GNU make
20080 echo Hello
20081 Hello
20082 $ @kbd{pmake}     # BSD make
20083 echo World
20084 World
20085 @end example
20087 @node make -k Status
20088 @section Exit Status of @code{make -k}
20089 @cindex @code{make -k}
20091 Do not rely on the exit status of @code{make -k}.  Some implementations
20092 reflect whether they encountered an error in their exit status; other
20093 implementations always succeed.
20095 @example
20096 $ @kbd{cat Makefile}
20097 all:
20098         false
20099 $ @kbd{make -k; echo exit status: $?}    # GNU make
20100 false
20101 make: *** [all] Error 1
20102 exit status: 2
20103 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20104 false
20105 *** Error code 1 (continuing)
20106 exit status: 0
20107 @end example
20109 @node VPATH and Make
20110 @section @code{VPATH} and Make
20111 @cindex @code{VPATH}
20113 Posix does not specify the semantics of @code{VPATH}.  Typically,
20114 @command{make} supports @code{VPATH}, but its implementation is not
20115 consistent.
20117 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20118 portable to recent-enough popular implementations of @command{make}, but
20119 to keep the resulting makefiles portable, a package's makefile
20120 prototypes must take the following issues into account.  These issues
20121 are complicated and are often poorly understood, and installers who use
20122 @code{VPATH} should expect to find many bugs in this area.  If you use
20123 @code{VPATH}, the simplest way to avoid these portability bugs is to
20124 stick with GNU @command{make}, since it is the most
20125 commonly-used @command{make} among Autoconf users.
20127 Here are some known issues with some @code{VPATH}
20128 implementations.
20130 @menu
20131 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20132 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20133 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20134 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20135 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20136 * Make Target Lookup::          More details about @code{VPATH} lookup
20137 @end menu
20139 @node Variables listed in VPATH
20140 @subsection Variables listed in @code{VPATH}
20141 @cindex @code{VPATH} and variables
20142 @cindex variables and @code{VPATH}
20144 Do not set @code{VPATH} to the value of another variable, for example
20145 @samp{VPATH = $(srcdir)}, because some ancient versions of
20146 @command{make} do not do variable substitutions on the value of
20147 @code{VPATH}.  For example, use this
20149 @example
20150 srcdir = @@srcdir@@
20151 VPATH = @@srcdir@@
20152 @end example
20154 @noindent
20155 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20156 Automake, there is no need to set this yourself.
20158 @node VPATH and Double-colon
20159 @subsection @code{VPATH} and Double-colon Rules
20160 @cindex @code{VPATH} and double-colon rules
20161 @cindex double-colon rules and @code{VPATH}
20163 With ancient versions of Sun @command{make},
20164 any assignment to @code{VPATH} causes @command{make} to execute only
20165 the first set of double-colon rules.
20166 However, this problem is no longer of practical concern.
20168 @node $< in Explicit Rules
20169 @subsection @code{$<} Not Supported in Explicit Rules
20170 @cindex explicit rules, @code{$<}, and @code{VPATH}
20171 @cindex @code{$<}, explicit rules, and @code{VPATH}
20172 @cindex @code{VPATH}, explicit rules, and @code{$<}
20174 Using @code{$<} in explicit rules is not portable.
20175 The prerequisite file must be named explicitly in the rule.  If you want
20176 to find the prerequisite via a @code{VPATH} search, you have to code the
20177 whole thing manually.  @xref{Build Directories}.
20179 @node Automatic Rule Rewriting
20180 @subsection Automatic Rule Rewriting
20181 @cindex @code{VPATH} and automatic rule rewriting
20182 @cindex automatic rule rewriting and @code{VPATH}
20184 Some @command{make} implementations, such as Solaris and Tru64,
20185 search for prerequisites in @code{VPATH} and
20186 then rewrite each occurrence as a plain word in the rule.
20187 For instance:
20189 @example
20190 # This isn't portable to GNU make.
20191 VPATH = ../pkg/src
20192 f.c: if.c
20193         cp if.c f.c
20194 @end example
20196 @noindent
20197 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20198 found in @file{../pkg/src}.
20200 However, this rule leads to real problems in practice.  For example, if
20201 the source directory contains an ordinary file named @file{test} that is
20202 used in a dependency, Solaris @command{make} rewrites commands like
20203 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20204 @dots{}}, which is typically undesirable.  To avoid this problem,
20205 portable makefiles should never mention a source file whose name is that
20206 of a shell keyword like @file{until} or a shell command like
20207 @command{cat} or @command{gcc} or @command{test}.
20209 Because of these problems GNU @command{make} and many other
20210 @command{make} implementations do not rewrite commands, so portable
20211 makefiles should
20212 search @code{VPATH} manually.  It is tempting to write this:
20214 @smallexample
20215 # This isn't portable to Solaris make.
20216 VPATH = ../pkg/src
20217 f.c: if.c
20218         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20219 @end smallexample
20221 @noindent
20222 However, the ``prerequisite rewriting'' still applies here.  So if
20223 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20224 execute
20226 @smallexample
20227 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20228 @end smallexample
20230 @noindent
20231 which reduces to
20233 @example
20234 cp if.c f.c
20235 @end example
20237 @noindent
20238 and thus fails.  Oops.
20240 A simple workaround, and good practice anyway, is to use @samp{$?} and
20241 @samp{$@@} when possible:
20243 @smallexample
20244 VPATH = ../pkg/src
20245 f.c: if.c
20246         cp $? $@@
20247 @end smallexample
20249 @noindent
20250 but this does not generalize well to commands with multiple
20251 prerequisites.  A more general workaround is to rewrite the rule so that
20252 the prerequisite @file{if.c} never appears as a plain word.  For
20253 example, these three rules would be safe, assuming @file{if.c} is in
20254 @file{../pkg/src} and the other files are in the working directory:
20256 @smallexample
20257 VPATH = ../pkg/src
20258 f.c: if.c f1.c
20259         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20260 g.c: if.c g1.c
20261         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20262 h.c: if.c h1.c
20263         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20264 @end smallexample
20266 Things get worse when your prerequisites are in a macro.
20268 @example
20269 VPATH = ../pkg/src
20270 HEADERS = f.h g.h h.h
20271 install-HEADERS: $(HEADERS)
20272         for i in $(HEADERS); do \
20273           $(INSTALL) -m 644 \
20274             `test -f $$i || echo $(VPATH)/`$$i \
20275             $(DESTDIR)$(includedir)/$$i; \
20276 @c $$ restore font-lock
20277         done
20278 @end example
20280 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20281 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20282 where @code{f.h} and @code{g.h} are plain words and are hence
20283 subject to @code{VPATH} adjustments.
20285 If the three files are in @file{../pkg/src}, the rule is run as:
20287 @example
20288 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20289   install -m 644 \
20290      `test -f $i || echo ../pkg/src/`$i \
20291      /usr/local/include/$i; \
20292 done
20293 @end example
20295 where the two first @command{install} calls fail.  For instance,
20296 consider the @code{f.h} installation:
20298 @example
20299 install -m 644 \
20300   `test -f ../pkg/src/f.h || \
20301     echo ../pkg/src/ \
20302   `../pkg/src/f.h \
20303   /usr/local/include/../pkg/src/f.h;
20304 @end example
20306 @noindent
20307 It reduces to:
20309 @example
20310 install -m 644 \
20311   ../pkg/src/f.h \
20312   /usr/local/include/../pkg/src/f.h;
20313 @end example
20315 Note that the manual @code{VPATH} search did not cause any problems here;
20316 however this command installs @file{f.h} in an incorrect directory.
20318 Trying to quote @code{$(HEADERS)} in some way, as we did for
20319 @code{foo.c} a few makefiles ago, does not help:
20321 @example
20322 install-HEADERS: $(HEADERS)
20323         headers='$(HEADERS)'; \
20324         for i in $$headers; do \
20325           $(INSTALL) -m 644 \
20326             `test -f $$i || echo $(VPATH)/`$$i \
20327             $(DESTDIR)$(includedir)/$$i; \
20328         done
20329 @end example
20331 Now, @code{headers='$(HEADERS)'} macro-expands to:
20333 @example
20334 headers='f.h g.h h.h'
20335 @end example
20337 @noindent
20338 but @code{g.h} is still a plain word.  (As an aside, the idiom
20339 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20340 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20341 syntax error on @code{for i in;}.)
20343 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20345 @example
20346 VPATH = ../pkg/src
20347 HEADERS = f.h g.h h.h
20348 install-HEADERS: $(HEADERS)
20349         headers='$(HEADERS)'; \
20350         for i in $$headers; do \
20351           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20352           $(INSTALL) -m 644 \
20353             `test -f $$i || echo $(VPATH)/`$$i \
20354             $(DESTDIR)$(includedir)/$$i; \
20355 @c $$ restore font-lock
20356         done
20357 @end example
20359 Automake does something similar.  However the above hack works only if
20360 the files listed in @code{HEADERS} are in the current directory or a
20361 subdirectory; they should not be in an enclosing directory.  If we had
20362 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20363 build with Tru64 @command{make}.  The reason is that not only does
20364 Tru64 @command{make} rewrite dependencies, but it also simplifies
20365 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20366 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20367 a leading @file{../pkg/src/} component.
20369 The following example makes the behavior of Tru64 @command{make}
20370 more apparent.
20372 @example
20373 $ @kbd{cat Makefile}
20374 VPATH = sub
20375 all: ../foo
20376         echo ../foo
20377 $ @kbd{ls}
20378 Makefile foo
20379 $ @kbd{make}
20380 echo foo
20382 @end example
20384 @noindent
20385 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20386 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20387 directory does not even exist, this just means that the simplification
20388 occurred before the file was checked for.)
20390 For the record here is how SunOS 4 @command{make} behaves on this
20391 example.
20393 @smallexample
20394 $ @kbd{make}
20395 make: Fatal error: Don't know how to make target `../foo'
20396 $ @kbd{mkdir sub}
20397 $ @kbd{make}
20398 echo sub/../foo
20399 sub/../foo
20400 @end smallexample
20403 @node Tru64 Directory Magic
20404 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20405 @cindex @code{VPATH} and prerequisite directories
20406 @cindex prerequisite directories and @code{VPATH}
20408 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20409 @command{make} creates it in the current directory.
20411 @example
20412 $ @kbd{mkdir -p foo/bar build}
20413 $ @kbd{cd build}
20414 $ @kbd{cat >Makefile <<END
20415 VPATH = ..
20416 all: foo/bar
20417 END}
20418 $ @kbd{make}
20419 mkdir foo
20420 mkdir foo/bar
20421 @end example
20423 This can yield unexpected results if a rule uses a manual @code{VPATH}
20424 search as presented before.
20426 @example
20427 VPATH = ..
20428 all : foo/bar
20429         command `test -d foo/bar || echo ../`foo/bar
20430 @end example
20432 The above @command{command} is run on the empty @file{foo/bar}
20433 directory that was created in the current directory.
20435 @node Make Target Lookup
20436 @subsection Make Target Lookup
20437 @cindex @code{VPATH}, resolving target pathnames
20439 GNU @command{make} uses a complex algorithm to decide when it
20440 should use files found via a @code{VPATH} search.  @xref{Search
20441 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20442 Manual}.
20444 If a target needs to be rebuilt, GNU @command{make} discards the
20445 file name found during the @code{VPATH} search for this target, and
20446 builds the file locally using the file name given in the makefile.
20447 If a target does not need to be rebuilt, GNU @command{make} uses the
20448 file name found during the @code{VPATH} search.
20450 Other @command{make} implementations, like NetBSD @command{make}, are
20451 easier to describe: the file name found during the @code{VPATH} search
20452 is used whether the target needs to be rebuilt or not.  Therefore
20453 new files are created locally, but existing files are updated at their
20454 @code{VPATH} location.
20456 OpenBSD and FreeBSD @command{make}, however,
20457 never perform a
20458 @code{VPATH} search for a dependency that has an explicit rule.
20459 This is extremely annoying.
20461 When attempting a @code{VPATH} build for an autoconfiscated package
20462 (e.g., @code{mkdir build && cd build && ../configure}), this means
20464 @command{make} builds everything locally in the @file{build}
20465 directory, while BSD @command{make} builds new files locally and
20466 updates existing files in the source directory.
20468 @example
20469 $ @kbd{cat Makefile}
20470 VPATH = ..
20471 all: foo.x bar.x
20472 foo.x bar.x: newer.x
20473         @@echo Building $@@
20474 $ @kbd{touch ../bar.x}
20475 $ @kbd{touch ../newer.x}
20476 $ @kbd{make}        # GNU make
20477 Building foo.x
20478 Building bar.x
20479 $ @kbd{pmake}       # NetBSD make
20480 Building foo.x
20481 Building ../bar.x
20482 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20483 Building foo.x
20484 Building bar.x
20485 $ @kbd{tmake}       # Tru64 make
20486 Building foo.x
20487 Building bar.x
20488 $ @kbd{touch ../bar.x}
20489 $ @kbd{make}        # GNU make
20490 Building foo.x
20491 $ @kbd{pmake}       # NetBSD make
20492 Building foo.x
20493 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20494 Building foo.x
20495 Building bar.x
20496 $ @kbd{tmake}       # Tru64 make
20497 Building foo.x
20498 Building bar.x
20499 @end example
20501 Note how NetBSD @command{make} updates @file{../bar.x} in its
20502 VPATH location, and how FreeBSD, OpenBSD, and Tru64
20503 @command{make} always
20504 update @file{bar.x}, even when @file{../bar.x} is up to date.
20506 Another point worth mentioning is that once GNU @command{make} has
20507 decided to ignore a @code{VPATH} file name (e.g., it ignored
20508 @file{../bar.x} in the above example) it continues to ignore it when
20509 the target occurs as a prerequisite of another rule.
20511 The following example shows that GNU @command{make} does not look up
20512 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20513 because it ignored the @code{VPATH} result of @file{bar.x} while running
20514 the @code{bar.x: newer.x} rule.
20516 @example
20517 $ @kbd{cat Makefile}
20518 VPATH = ..
20519 all: bar.y
20520 bar.x: newer.x
20521         @@echo Building $@@
20522 .SUFFIXES: .x .y
20523 .x.y:
20524         cp $< $@@
20525 $ @kbd{touch ../bar.x}
20526 $ @kbd{touch ../newer.x}
20527 $ @kbd{make}        # GNU make
20528 Building bar.x
20529 cp bar.x bar.y
20530 cp: cannot stat `bar.x': No such file or directory
20531 make: *** [bar.y] Error 1
20532 $ @kbd{pmake}       # NetBSD make
20533 Building ../bar.x
20534 cp ../bar.x bar.y
20535 $ @kbd{rm bar.y}
20536 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20537 echo Building bar.x
20538 cp bar.x bar.y
20539 cp: cannot stat `bar.x': No such file or directory
20540 *** Error code 1
20541 $ @kbd{tmake}       # Tru64 make
20542 Building bar.x
20543 cp: bar.x: No such file or directory
20544 *** Exit 1
20545 @end example
20547 Note that if you drop away the command from the @code{bar.x: newer.x}
20548 rule, GNU @command{make} magically starts to work: it
20549 knows that @code{bar.x} hasn't been updated, therefore it doesn't
20550 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
20551 uses.  Tru64 also works, but FreeBSD and OpenBSD
20552 still don't.
20554 @example
20555 $ @kbd{cat Makefile}
20556 VPATH = ..
20557 all: bar.y
20558 bar.x: newer.x
20559 .SUFFIXES: .x .y
20560 .x.y:
20561         cp $< $@@
20562 $ @kbd{touch ../bar.x}
20563 $ @kbd{touch ../newer.x}
20564 $ @kbd{make}        # GNU make
20565 cp ../bar.x bar.y
20566 $ @kbd{rm bar.y}
20567 $ @kbd{pmake}       # NetBSD make
20568 cp ../bar.x bar.y
20569 $ @kbd{rm bar.y}
20570 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20571 cp bar.x bar.y
20572 cp: cannot stat `bar.x': No such file or directory
20573 *** Error code 1
20574 $ @kbd{tmake}       # Tru64 make
20575 cp ../bar.x bar.y
20576 @end example
20578 It seems the sole solution that would please every @command{make}
20579 implementation is to never rely on @code{VPATH} searches for targets.
20580 In other words, @code{VPATH} should be reserved to unbuilt sources.
20583 @node Single Suffix Rules
20584 @section Single Suffix Rules and Separated Dependencies
20585 @cindex Single Suffix Inference Rule
20586 @cindex Rule, Single Suffix Inference
20587 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
20588 (@samp{.from.to:}), but which @emph{destination} suffix is empty
20589 (@samp{.from:}).
20591 @cindex Separated Dependencies
20592 @dfn{Separated dependencies} simply refers to listing the prerequisite
20593 of a target, without defining a rule.  Usually one can list on the one
20594 hand side, the rules, and on the other hand side, the dependencies.
20596 Solaris @command{make} does not support separated dependencies for
20597 targets defined by single suffix rules:
20599 @example
20600 $ @kbd{cat Makefile}
20601 .SUFFIXES: .in
20602 foo: foo.in
20603 .in:
20604         cp $< $@@
20605 $ @kbd{touch foo.in}
20606 $ @kbd{make}
20607 $ @kbd{ls}
20608 Makefile  foo.in
20609 @end example
20611 @noindent
20612 while GNU Make does:
20614 @example
20615 $ @kbd{gmake}
20616 cp foo.in foo
20617 $ @kbd{ls}
20618 Makefile  foo       foo.in
20619 @end example
20621 Note it works without the @samp{foo: foo.in} dependency.
20623 @example
20624 $ @kbd{cat Makefile}
20625 .SUFFIXES: .in
20626 .in:
20627         cp $< $@@
20628 $ @kbd{make foo}
20629 cp foo.in foo
20630 @end example
20632 @noindent
20633 and it works with double suffix inference rules:
20635 @example
20636 $ @kbd{cat Makefile}
20637 foo.out: foo.in
20638 .SUFFIXES: .in .out
20639 .in.out:
20640         cp $< $@@
20641 $ @kbd{make}
20642 cp foo.in foo.out
20643 @end example
20645 As a result, in such a case, you have to write target rules.
20647 @node Timestamps and Make
20648 @section Timestamp Resolution and Make
20649 @cindex timestamp resolution
20650 Traditionally, file timestamps had 1-second resolution, and
20651 @command{make} used those timestamps to determine whether one file was
20652 newer than the other.  However, many modern file systems have
20653 timestamps with 1-nanosecond resolution.  Some @command{make}
20654 implementations look at the entire timestamp; others ignore the
20655 fractional part, which can lead to incorrect results.  Normally this
20656 is not a problem, but in some extreme cases you may need to use tricks
20657 like @samp{sleep 1} to work around timestamp truncation bugs.
20659 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
20660 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
20661 Tools}).  Hence you should be wary of rules like this:
20663 @example
20664 dest: src
20665         cp -p src dest
20666 @end example
20668 as @file{dest} often appears to be older than @file{src} after the
20669 timestamp is truncated, and this can cause @command{make} to do
20670 needless rework the next time it is invoked.  To work around this
20671 problem, you can use a timestamp file, e.g.:
20673 @example
20674 dest-stamp: src
20675         cp -p src dest
20676         date >dest-stamp
20677 @end example
20679 Apart from timestamp resolution, there are also differences in handling
20680 equal timestamps.  HP-UX @command{make} updates targets if it has the
20681 same time stamp as one of its prerequisites, in violation of Posix rules.
20683 This can cause spurious rebuilds for repeated runs of @command{make}.
20684 This in turn can cause @command{make} to fail if it tries to rebuild
20685 generated files in a possibly read-only source tree with tools not
20686 present on the end-user machine.  Use GNU @command{make} instead.
20690 @c ======================================== Portable C and C++ Programming
20692 @node Portable C and C++
20693 @chapter Portable C and C++ Programming
20694 @cindex Portable C and C++ programming
20696 C and C++ programs often use low-level features of the underlying
20697 system, and therefore are often more difficult to make portable to other
20698 platforms.
20700 Several standards have been developed to help make your programs more
20701 portable.  If you write programs with these standards in mind, you can
20702 have greater confidence that your programs work on a wide variety
20703 of systems.
20704 @ifhtml
20705 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
20706 Standards Supported by GCC}
20707 @end ifhtml
20708 @ifnothtml
20709 @xref{Standards, , Language Standards Supported by
20710 GCC, gcc, Using the GNU Compiler Collection
20711 (GCC)},
20712 @end ifnothtml
20713 for a list of C-related standards.  Many programs also assume the
20714 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
20716 Some old code is written to be portable to K&R C, which predates any C
20717 standard.  K&R C compilers are no longer of practical interest, though,
20718 and the rest of section assumes at least C89, the first C standard.
20720 Program portability is a huge topic, and this section can only briefly
20721 introduce common pitfalls.  @xref{System Portability, , Portability
20722 between System Types, standards, The GNU Coding Standards}, for
20723 more information.
20725 @menu
20726 * Varieties of Unportability::  How to make your programs unportable
20727 * Integer Overflow::            When integers get too large
20728 * Preprocessor Arithmetic::     @code{#if} expression problems
20729 * Null Pointers::               Properties of null pointers
20730 * Buffer Overruns::             Subscript errors and the like
20731 * Volatile Objects::            @code{volatile} and signals
20732 * Floating Point Portability::  Portable floating-point arithmetic
20733 * Exiting Portably::            Exiting and the exit status
20734 @end menu
20736 @node Varieties of Unportability
20737 @section Varieties of Unportability
20738 @cindex portability
20740 Autoconf tests and ordinary programs often need to test what is allowed
20741 on a system, and therefore they may need to deliberately exceed the
20742 boundaries of what the standards allow, if only to see whether an
20743 optional feature is present.  When you write such a program, you should
20744 keep in mind the difference between constraints, unspecified behavior,
20745 and undefined behavior.
20747 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
20748 example constraint is that C programs must not declare a bit-field with
20749 negative width.  Tests can therefore reliably assume that programs with
20750 negative-width bit-fields are rejected by a compiler that conforms
20751 to the standard.
20753 @dfn{Unspecified behavior} is valid behavior, where the standard allows
20754 multiple possibilities.  For example, the order of evaluation of
20755 function arguments is unspecified.  Some unspecified behavior is
20756 @dfn{implementation-defined}, i.e., documented by the implementation,
20757 but since Autoconf tests cannot read the documentation they cannot
20758 distinguish between implementation-defined and other unspecified
20759 behavior.  It is common for Autoconf tests to probe implementations to
20760 determine otherwise-unspecified behavior.
20762 @dfn{Undefined behavior} is invalid behavior, where the standard allows
20763 the implementation to do anything it pleases.  For example,
20764 dereferencing a null pointer leads to undefined behavior.  If possible,
20765 test programs should avoid undefined behavior, since a program with
20766 undefined behavior might succeed on a test that should fail.
20768 The above rules apply to programs that are intended to conform to the
20769 standard.  However, strictly-conforming programs are quite rare, since
20770 the standards are so limiting.  A major goal of Autoconf is to support
20771 programs that use implementation features not described by the standard,
20772 and it is fairly common for test programs to violate the above rules, if
20773 the programs work well enough in practice.
20775 @node Integer Overflow
20776 @section Integer Overflow
20777 @cindex integer overflow
20778 @cindex overflow, signed integer
20779 @cindex signed integer overflow
20780 @cindex wraparound arithmetic
20782 In practice many portable C programs assume that signed integer overflow wraps
20783 around reliably using two's complement arithmetic.  Yet the C standard
20784 says that program behavior is undefined on overflow, and in a few cases
20785 C programs do not work on some modern implementations because their
20786 overflows do not wrap around as their authors expected.  Conversely, in
20787 signed integer remainder, the C standard requires overflow
20788 behavior that is commonly not implemented.
20790 @menu
20791 * Integer Overflow Basics::     Why integer overflow is a problem
20792 * Signed Overflow Examples::    Examples of code assuming wraparound
20793 * Optimization and Wraparound::  Optimizations that break uses of wraparound
20794 * Signed Overflow Advice::      Practical advice for signed overflow issues
20795 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
20796 @end menu
20798 @node Integer Overflow Basics
20799 @subsection Basics of Integer Overflow
20800 @cindex integer overflow
20801 @cindex overflow, signed integer
20802 @cindex signed integer overflow
20803 @cindex wraparound arithmetic
20805 In languages like C, unsigned integer overflow reliably wraps around;
20806 e.g., @code{UINT_MAX + 1} yields zero.
20807 This is guaranteed by the C standard and is
20808 portable in practice, unless you specify aggressive,
20809 nonstandard optimization options
20810 suitable only for special applications.
20812 In contrast, the C standard says that signed integer overflow leads to
20813 undefined behavior where a program can do anything, including dumping
20814 core or overrunning a buffer.  The misbehavior can even precede the
20815 overflow.  Such an overflow can occur during addition, subtraction,
20816 multiplication, division, and left shift.
20818 Despite this requirement of the standard, many C programs and Autoconf
20819 tests assume that signed integer overflow silently wraps around modulo a
20820 power of two, using two's complement arithmetic, so long as you cast the
20821 resulting value to a signed integer type or store it into a signed
20822 integer variable.  If you use conservative optimization flags, such
20823 programs are generally portable to the vast majority of modern
20824 platforms, with a few exceptions discussed later.
20826 For historical reasons the C standard also allows implementations with
20827 ones' complement or signed magnitude arithmetic, but it is safe to
20828 assume two's complement nowadays.
20830 Also, overflow can occur when converting an out-of-range value to a
20831 signed integer type.  Here a standard implementation must define what
20832 happens, but this might include raising an exception.  In practice all
20833 known implementations support silent wraparound in this case, so you need
20834 not worry about other possibilities.
20836 @node Signed Overflow Examples
20837 @subsection Examples of Code Assuming Wraparound Overflow
20838 @cindex integer overflow
20839 @cindex overflow, signed integer
20840 @cindex signed integer overflow
20841 @cindex wraparound arithmetic
20843 There has long been a tension between what the C standard requires for
20844 signed integer overflow, and what C programs commonly assume.  The
20845 standard allows aggressive optimizations based on assumptions that
20846 overflow never occurs, but many practical C programs rely on overflow
20847 wrapping around.  These programs do not conform to the standard, but
20848 they commonly work in practice because compiler writers are
20849 understandably reluctant to implement optimizations that would break
20850 many programs, unless perhaps a user specifies aggressive optimization.
20852 The C Standard says that if a program has signed integer overflow its
20853 behavior is undefined, and the undefined behavior can even precede the
20854 overflow.  To take an extreme example:
20856 @c Inspired by Robert Dewar's example in
20857 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
20858 @example
20859 if (password == expected_password)
20860   allow_superuser_privileges ();
20861 else if (counter++ == INT_MAX)
20862   abort ();
20863 else
20864   printf ("%d password mismatches\n", counter);
20865 @end example
20867 @noindent
20868 If the @code{int} variable @code{counter} equals @code{INT_MAX},
20869 @code{counter++} must overflow and the behavior is undefined, so the C
20870 standard allows the compiler to optimize away the test against
20871 @code{INT_MAX} and the @code{abort} call.
20872 Worse, if an earlier bug in the program lets the compiler deduce that
20873 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
20874 the C standard allows the compiler to optimize away the password test
20875 and generate code that allows superuser privileges unconditionally.
20877 Despite this requirement by the standard, it has long been common for C
20878 code to assume wraparound arithmetic after signed overflow, and all
20879 known practical C implementations support some C idioms that assume
20880 wraparound signed arithmetic, even if the idioms do not conform
20881 strictly to the standard.  If your code looks like the following
20882 examples it will almost surely work with real-world compilers.
20884 Here is an example derived from the 7th Edition Unix implementation of
20885 @code{atoi} (1979-01-10):
20887 @example
20888 char *p;
20889 int f, n;
20890 @dots{}
20891 while (*p >= '0' && *p <= '9')
20892   n = n * 10 + *p++ - '0';
20893 return (f ? -n : n);
20894 @end example
20896 @noindent
20897 Even if the input string is in range, on most modern machines this has
20898 signed overflow when computing the most negative integer (the @code{-n}
20899 overflows) or a value near an extreme integer (the first @code{+}
20900 overflows).
20902 Here is another example, derived from the 7th Edition implementation of
20903 @code{rand} (1979-01-10).  Here the programmer expects both
20904 multiplication and addition to wrap on overflow:
20906 @example
20907 static long int randx = 1;
20908 @dots{}
20909 randx = randx * 1103515245 + 12345;
20910 return (randx >> 16) & 077777;
20911 @end example
20913 In the following example, derived from the GNU C Library 2.5
20914 implementation of @code{mktime} (2006-09-09), the code assumes
20915 wraparound arithmetic in @code{+} to detect signed overflow:
20917 @example
20918 time_t t, t1, t2;
20919 int sec_requested, sec_adjustment;
20920 @dots{}
20921 t1 = t + sec_requested;
20922 t2 = t1 + sec_adjustment;
20923 if (((t1 < t) != (sec_requested < 0))
20924     | ((t2 < t1) != (sec_adjustment < 0)))
20925   return -1;
20926 @end example
20928 If your code looks like these examples, it is probably safe even though
20929 it does not strictly conform to the C standard.  This might lead one to
20930 believe that one can generally assume wraparound on overflow, but that
20931 is not always true, as can be seen in the next section.
20933 @node Optimization and Wraparound
20934 @subsection Optimizations That Break Wraparound Arithmetic
20935 @cindex loop induction
20937 Compilers sometimes generate code that is incompatible with wraparound
20938 integer arithmetic.  A simple example is an algebraic simplification: a
20939 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
20940 because it assumes that @code{i * 2000} does not overflow.  The
20941 translation is not equivalent to the original when overflow occurs:
20942 e.g., in the typical case of 32-bit signed two's complement wraparound
20943 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
20944 the original expression returns @minus{}2147483 but the optimized
20945 version returns the mathematically correct value 2147484.
20947 More subtly, loop induction optimizations often exploit the undefined
20948 behavior of signed overflow.  Consider the following contrived function
20949 @code{sumc}:
20951 @example
20953 sumc (int lo, int hi)
20955   int sum = 0;
20956   int i;
20957   for (i = lo; i <= hi; i++)
20958     sum ^= i * 53;
20959   return sum;
20961 @end example
20963 @noindent
20964 To avoid multiplying by 53 each time through the loop, an optimizing
20965 compiler might internally transform @code{sumc} to the equivalent of the
20966 following:
20968 @example
20970 transformed_sumc (int lo, int hi)
20972   int sum = 0;
20973   int hic = hi * 53;
20974   int ic;
20975   for (ic = lo * 53; ic <= hic; ic += 53)
20976     sum ^= ic;
20977   return sum;
20979 @end example
20981 @noindent
20982 This transformation is allowed by the C standard, but it is invalid for
20983 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
20984 overflow in computing expressions like @code{hi * 53} can cause the
20985 expression @code{i <= hi} to yield a different value from the
20986 transformed expression @code{ic <= hic}.
20988 For this reason, compilers that use loop induction and similar
20989 techniques often do not support reliable wraparound arithmetic when a
20990 loop induction variable like @code{ic} is involved.  Since loop
20991 induction variables are generated by the compiler, and are not visible
20992 in the source code, it is not always trivial to say whether the problem
20993 affects your code.
20995 Hardly any code actually depends on wraparound arithmetic in cases like
20996 these, so in practice these loop induction optimizations are almost
20997 always useful.  However, edge cases in this area can cause problems.
20998 For example:
21000 @example
21001 int j;
21002 for (j = 1; 0 < j; j *= 2)
21003   test (j);
21004 @end example
21006 @noindent
21007 Here, the loop attempts to iterate through all powers of 2 that
21008 @code{int} can represent, but the C standard allows a compiler to
21009 optimize away the comparison and generate an infinite loop,
21010 under the argument that behavior is undefined on overflow.  As of this
21011 writing this optimization is not done by any production version of
21012 GCC with @option{-O2}, but it might be performed by other
21013 compilers, or by more aggressive GCC optimization options,
21014 and the GCC developers have not decided whether it will
21015 continue to work with GCC and @option{-O2}.
21017 @node Signed Overflow Advice
21018 @subsection Practical Advice for Signed Overflow Issues
21019 @cindex integer overflow
21020 @cindex overflow, signed integer
21021 @cindex signed integer overflow
21022 @cindex wraparound arithmetic
21024 Ideally the safest approach is to avoid signed integer overflow
21025 entirely.  For example, instead of multiplying two signed integers, you
21026 can convert them to unsigned integers, multiply the unsigned values,
21027 then test whether the result is in signed range.
21029 Rewriting code in this way will be inconvenient, though, particularly if
21030 the signed values might be negative.  Also, it may hurt
21031 performance.  Using unsigned arithmetic to check for overflow is
21032 particularly painful to do portably and efficiently when dealing with an
21033 integer type like @code{uid_t} whose width and signedness vary from
21034 platform to platform.
21036 Furthermore, many C applications pervasively assume wraparound behavior
21037 and typically it is not easy to find and remove all these assumptions.
21038 Hence it is often useful to maintain nonstandard code that assumes
21039 wraparound on overflow, instead of rewriting the code.  The rest of this
21040 section attempts to give practical advice for this situation.
21042 If your code wants to detect signed integer overflow in @code{sum = a +
21043 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21044 < 0)}.
21046 If your code uses a signed loop index, make sure that the index cannot
21047 overflow, along with all signed expressions derived from the index.
21048 Here is a contrived example of problematic code with two instances of
21049 overflow.
21051 @example
21052 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21053   if (i + 1 < 0)
21054     @{
21055       report_overflow ();
21056       break;
21057     @}
21058 @end example
21060 @noindent
21061 Because of the two overflows, a compiler might optimize away or
21062 transform the two comparisons in a way that is incompatible with the
21063 wraparound assumption.
21065 If your code uses an expression like @code{(i * 2000) / 1000} and you
21066 actually want the multiplication to wrap around on overflow, use
21067 unsigned arithmetic
21068 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21070 If your code assumes wraparound behavior and you want to insulate it
21071 against any GCC optimizations that would fail to support that
21072 behavior, you should use GCC's @option{-fwrapv} option, which
21073 causes signed overflow to wrap around reliably (except for division and
21074 remainder, as discussed in the next section).
21076 If you need to port to platforms where signed integer overflow does not
21077 reliably wrap around (e.g., due to hardware overflow checking, or to
21078 highly aggressive optimizations), you should consider debugging with
21079 GCC's @option{-ftrapv} option, which causes signed overflow to
21080 raise an exception.
21082 @node Signed Integer Division
21083 @subsection Signed Integer Division and Integer Overflow
21084 @cindex division, integer
21086 Overflow in signed
21087 integer division is not always harmless: for example, on CPUs of the
21088 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21089 which by default terminates the program.  Worse, taking the remainder
21090 of these two values typically yields the same signal on these CPUs,
21091 even though the C standard requires @code{INT_MIN % -1} to yield zero
21092 because the expression does not overflow.
21094 @node Preprocessor Arithmetic
21095 @section Preprocessor Arithmetic
21096 @cindex preprocessor arithmetic
21098 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
21099 be evaluated as if all signed values are of type @code{intmax_t} and all
21100 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21101 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21102 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21103 @code{long long int}.  Also, some older preprocessors mishandle
21104 constants ending in @code{LL}.  To work around these problems, you can
21105 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21106 @code{configure}-time rather than at @code{#if}-time.
21108 @node Null Pointers
21109 @section Properties of Null Pointers
21110 @cindex null pointers
21112 Most modern hosts reliably fail when you attempt to dereference a null
21113 pointer.
21115 On almost all modern hosts, null pointers use an all-bits-zero internal
21116 representation, so you can reliably use @code{memset} with 0 to set all
21117 the pointers in an array to null values.
21119 If @code{p} is a null pointer to an object type, the C expression
21120 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21121 the standard says that it has undefined behavior.
21123 @node Buffer Overruns
21124 @section Buffer Overruns and Subscript Errors
21125 @cindex buffer overruns
21127 Buffer overruns and subscript errors are the most common dangerous
21128 errors in C programs.  They result in undefined behavior because storing
21129 outside an array typically modifies storage that is used by some other
21130 object, and most modern systems lack runtime checks to catch these
21131 errors.  Programs should not rely on buffer overruns being caught.
21133 There is one exception to the usual rule that a portable program cannot
21134 address outside an array.  In C, it is valid to compute the address just
21135 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21136 so long as you do not dereference the resulting pointer.  But it is not
21137 valid to compute the address just before an object, e.g., @code{&a[-1]};
21138 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21139 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21140 reliable in general, and it is usually easy enough to avoid the
21141 potential portability problem, e.g., by allocating an extra unused array
21142 element at the start or end.
21144 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21146 users might also consider using the @option{-fmudflap} option to catch
21147 overruns.
21149 Buffer overruns are usually caused by off-by-one errors, but there are
21150 more subtle ways to get them.
21152 Using @code{int} values to index into an array or compute array sizes
21153 causes problems on typical 64-bit hosts where an array index might
21154 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21155 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21156 are signed, and are wide enough in practice.
21158 If you add or multiply two numbers to calculate an array size, e.g.,
21159 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21160 multiplication overflows.
21162 Many implementations of the @code{alloca} function silently misbehave
21163 and can generate buffer overflows if given sizes that are too large.
21164 The size limits are implementation dependent, but are at least 4000
21165 bytes on all platforms that we know about.
21167 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21168 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21169 portable code should not use them unless the inputs are known to be
21170 within certain limits.  The time-related functions can overflow their
21171 buffers if given timestamps out of range (e.g., a year less than -999
21172 or greater than 9999).  Time-related buffer overflows cannot happen with
21173 recent-enough versions of the GNU C library, but are possible
21174 with other
21175 implementations.  The @code{gets} function is the worst, since it almost
21176 invariably overflows its buffer when presented with an input line larger
21177 than the buffer.
21179 @node Volatile Objects
21180 @section Volatile Objects
21181 @cindex volatile objects
21183 The keyword @code{volatile} is often misunderstood in portable code.
21184 Its use inhibits some memory-access optimizations, but programmers often
21185 wish that it had a different meaning than it actually does.
21187 @code{volatile} was designed for code that accesses special objects like
21188 memory-mapped device registers whose contents spontaneously change.
21189 Such code is inherently low-level, and it is difficult to specify
21190 portably what @code{volatile} means in these cases.  The C standard
21191 says, ``What constitutes an access to an object that has
21192 volatile-qualified type is implementation-defined,'' so in theory each
21193 implementation is supposed to fill in the gap by documenting what
21194 @code{volatile} means for that implementation.  In practice, though,
21195 this documentation is usually absent or incomplete.
21197 One area of confusion is the distinction between objects defined with
21198 volatile types, and volatile lvalues.  From the C standard's point of
21199 view, an object defined with a volatile type has externally visible
21200 behavior.  You can think of such objects as having little oscilloscope
21201 probes attached to them, so that the user can observe some properties of
21202 accesses to them, just as the user can observe data written to output
21203 files.  However, the standard does not make it clear whether users can
21204 observe accesses by volatile lvalues to ordinary objects.  For example:
21206 @example
21207 /* Declare and access a volatile object.
21208    Accesses to X are "visible" to users.  */
21209 static int volatile x;
21210 x = 1;
21212 /* Access two ordinary objects via a volatile lvalue.
21213    It's not clear whether accesses to *P are "visible".  */
21214 int y;
21215 int *z = malloc (sizeof (int));
21216 int volatile *p;
21217 p = &y;
21218 *p = 1;
21219 p = z;
21220 *p = 1;
21221 @end example
21223 Programmers often wish that @code{volatile} meant ``Perform the memory
21224 access here and now, without merging several memory accesses, without
21225 changing the memory word size, and without reordering.''  But the C
21226 standard does not require this.  For objects defined with a volatile
21227 type, accesses must be done before the next sequence point; but
21228 otherwise merging, reordering, and word-size change is allowed.  Worse,
21229 it is not clear from the standard whether volatile lvalues provide more
21230 guarantees in general than nonvolatile lvalues, if the underlying
21231 objects are ordinary.
21233 Even when accessing objects defined with a volatile type,
21234 the C standard allows only
21235 extremely limited signal handlers: the behavior is undefined if a signal
21236 handler reads any nonlocal object, or writes to any nonlocal object
21237 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21238 library function other than @code{abort}, @code{signal}, and (if C99)
21239 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21240 disturbing ordinary computation, unless the computation accesses a
21241 @code{sig_atomic_t volatile} lvalue that is not a local variable.
21242 (There is an obscure exception for accesses via a pointer to a volatile
21243 character, since it may point into part of a @code{sig_atomic_t
21244 volatile} object.)  Posix
21245 adds to the list of library functions callable from a portable signal
21246 handler, but otherwise is like the C standard in this area.
21248 Some C implementations allow memory-access optimizations within each
21249 translation unit, such that actual behavior agrees with the behavior
21250 required by the standard only when calling a function in some other
21251 translation unit, and a signal handler acts like it was called from a
21252 different translation unit.  The C standard hints that in these
21253 implementations, objects referred to by signal handlers ``would require
21254 explicit specification of @code{volatile} storage, as well as other
21255 implementation-defined restrictions.''  But unfortunately even for this
21256 special case these other restrictions are often not documented well.
21257 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21258 GNU Compiler Collection (GCC)}, for some
21259 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21260 Defining Signal Handlers, libc, The GNU C Library}, for some
21261 restrictions imposed by the GNU C library.  Restrictions
21262 differ on other platforms.
21264 If possible, it is best to use a signal handler that fits within the
21265 limits imposed by the C and Posix standards.
21267 If this is not practical, you can try the following rules of thumb.  A
21268 signal handler should access only volatile lvalues, preferably lvalues
21269 that refer to objects defined with a volatile type, and should not
21270 assume that the accessed objects have an internally consistent state
21271 if they are larger than a machine word.  Furthermore, installers
21272 should employ compilers and compiler options that are commonly used
21273 for building operating system kernels, because kernels often need more
21274 from @code{volatile} than the C Standard requires, and installers who
21275 compile an application in a similar environment can sometimes benefit
21276 from the extra constraints imposed by kernels on compilers.
21277 Admittedly we are handwaving somewhat here, as there are few
21278 guarantees in this area; the rules of thumb may help to fix some bugs
21279 but there is a good chance that they will not fix them all.
21281 For @code{volatile}, C++ has the same problems that C does.
21282 Multithreaded applications have even more problems with @code{volatile},
21283 but they are beyond the scope of this section.
21285 The bottom line is that using @code{volatile} typically hurts
21286 performance but should not hurt correctness.  In some cases its use
21287 does help correctness, but these cases are often so poorly understood
21288 that all too often adding @code{volatile} to a data structure merely
21289 alleviates some symptoms of a bug while not fixing the bug in general.
21291 @node Floating Point Portability
21292 @section Floating Point Portability
21293 @cindex floating point
21295 Almost all modern systems use IEEE-754 floating point, and it is safe to
21296 assume IEEE-754 in most portable code these days.  For more information,
21297 please see David Goldberg's classic paper
21298 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21299 Scientist Should Know About Floating-Point Arithmetic}.
21301 @node Exiting Portably
21302 @section Exiting Portably
21303 @cindex exiting portably
21305 A C or C++ program can exit with status @var{N} by returning
21306 @var{N} from the @code{main} function.  Portable programs are supposed
21307 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21308 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21309 fail by exiting with status 1, and test programs that assume Posix can
21310 fail by exiting with status values from 1 through 255.  Programs on
21311 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21312 status when @code{main} returned nonzero, but ancient systems like these
21313 are no longer of practical concern.
21315 A program can also exit with status @var{N} by passing @var{N} to the
21316 @code{exit} function, and a program can fail by calling the @code{abort}
21317 function.  If a program is specialized to just some platforms, it can fail
21318 by calling functions specific to those platforms, e.g., @code{_exit}
21319 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
21320 function should be declared, typically by including a header.  For
21321 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21322 either directly or via the default includes (@pxref{Default Includes}).
21324 A program can fail due to undefined behavior such as dereferencing a null
21325 pointer, but this is not recommended as undefined behavior allows an
21326 implementation to do whatever it pleases and this includes exiting
21327 successfully.
21330 @c ================================================== Manual Configuration
21332 @node Manual Configuration
21333 @chapter Manual Configuration
21335 A few kinds of features can't be guessed automatically by running test
21336 programs.  For example, the details of the object-file format, or
21337 special options that need to be passed to the compiler or linker.  You
21338 can check for such features using ad-hoc means, such as having
21339 @command{configure} check the output of the @code{uname} program, or
21340 looking for libraries that are unique to particular systems.  However,
21341 Autoconf provides a uniform method for handling unguessable features.
21343 @menu
21344 * Specifying Target Triplets::  Specifying target triplets
21345 * Canonicalizing::              Getting the canonical system type
21346 * Using System Type::           What to do with the system type
21347 @end menu
21349 @node Specifying Target Triplets
21350 @section Specifying target triplets
21351 @cindex System type
21352 @cindex Target triplet
21353 @c This node used to be named Specifying Names.  The @anchor allows old
21354 @c links to still work.
21355 @anchor{Specifying Names}
21357 Autoconf-generated
21358 @command{configure} scripts can make decisions based on a canonical name
21359 for the system type, or @dfn{target triplet}, which has the form:
21360 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21361 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21363 @command{configure} can usually guess the canonical name for the type of
21364 system it's running on.  To do so it runs a script called
21365 @command{config.guess}, which infers the name using the @code{uname}
21366 command or symbols predefined by the C preprocessor.
21368 Alternately, the user can specify the system type with command line
21369 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21370 necessary when
21371 cross-compiling.  In the most complex case of cross-compiling, three
21372 system types are involved.  The options to specify them are:
21374 @table @option
21375 @item --build=@var{build-type}
21376 the type of system on which the package is being configured and
21377 compiled.  It defaults to the result of running @command{config.guess}.
21379 @item --host=@var{host-type}
21380 the type of system on which the package runs.  By default it is the
21381 same as the build machine.  Specifying it enables the cross-compilation
21382 mode.
21384 @item --target=@var{target-type}
21385 the type of system for which any compiler tools in the package
21386 produce code (rarely needed).  By default, it is the same as host.
21387 @end table
21389 If you mean to override the result of @command{config.guess}, use
21390 @option{--build}, not @option{--host}, since the latter enables
21391 cross-compilation.  For historical reasons,
21392 whenever you specify @option{--host},
21393 be sure to specify @option{--build} too; this will be fixed in the
21394 future.  So, to enter cross-compilation mode, use a command like this
21396 @example
21397 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21398 @end example
21400 @noindent
21401 Note that if you do not specify @option{--host}, @command{configure}
21402 fails if it can't run the code generated by the specified compiler.  For
21403 example, configuring as follows fails:
21405 @example
21406 ./configure CC=m68k-coff-gcc
21407 @end example
21409 When cross-compiling, @command{configure} will warn about any tools
21410 (compilers, linkers, assemblers) whose name is not prefixed with the
21411 host type.  This is an aid to users performing cross-compilation.
21412 Continuing the example above, if a cross-compiler named @command{cc} is
21413 used with a native @command{pkg-config}, then libraries found by
21414 @command{pkg-config} will likely cause subtle build failures; but using
21415 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21416 avoids any confusion.  Avoiding the warning is as simple as creating the
21417 correct symlinks naming the cross tools.
21419 @cindex @command{config.sub}
21420 @command{configure} recognizes short aliases for many system types; for
21421 example, @samp{decstation} can be used instead of
21422 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21423 @command{config.sub} to canonicalize system type aliases.
21425 This section deliberately omits the description of the obsolete
21426 interface; see @ref{Hosts and Cross-Compilation}.
21429 @node Canonicalizing
21430 @section Getting the Canonical System Type
21431 @cindex System type
21432 @cindex Canonical system type
21434 The following macros make the system type available to @command{configure}
21435 scripts.
21437 @ovindex build_alias
21438 @ovindex host_alias
21439 @ovindex target_alias
21441 The variables @samp{build_alias}, @samp{host_alias}, and
21442 @samp{target_alias} are always exactly the arguments of @option{--build},
21443 @option{--host}, and @option{--target}; in particular, they are left empty
21444 if the user did not use them, even if the corresponding
21445 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21446 variables anywhere.  These are the variables that should be used when in
21447 interaction with the user.
21449 If you need to recognize some special environments based on their system
21450 type, run the following macros to get canonical system names.  These
21451 variables are not set before the macro call.
21453 If you use these macros, you must distribute @command{config.guess} and
21454 @command{config.sub} along with your source code.  @xref{Output}, for
21455 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21456 to control in which directory @command{configure} looks for those scripts.
21459 @defmac AC_CANONICAL_BUILD
21460 @acindex{CANONICAL_BUILD}
21461 @ovindex build
21462 @ovindex build_cpu
21463 @ovindex build_vendor
21464 @ovindex build_os
21465 Compute the canonical build-system type variable, @code{build}, and its
21466 three individual parts @code{build_cpu}, @code{build_vendor}, and
21467 @code{build_os}.
21469 If @option{--build} was specified, then @code{build} is the
21470 canonicalization of @code{build_alias} by @command{config.sub},
21471 otherwise it is determined by the shell script @command{config.guess}.
21472 @end defmac
21474 @defmac AC_CANONICAL_HOST
21475 @acindex{CANONICAL_HOST}
21476 @ovindex host
21477 @ovindex host_cpu
21478 @ovindex host_vendor
21479 @ovindex host_os
21480 Compute the canonical host-system type variable, @code{host}, and its
21481 three individual parts @code{host_cpu}, @code{host_vendor}, and
21482 @code{host_os}.
21484 If @option{--host} was specified, then @code{host} is the
21485 canonicalization of @code{host_alias} by @command{config.sub},
21486 otherwise it defaults to @code{build}.
21487 @end defmac
21489 @defmac AC_CANONICAL_TARGET
21490 @acindex{CANONICAL_TARGET}
21491 @ovindex target
21492 @ovindex target_cpu
21493 @ovindex target_vendor
21494 @ovindex target_os
21495 Compute the canonical target-system type variable, @code{target}, and its
21496 three individual parts @code{target_cpu}, @code{target_vendor}, and
21497 @code{target_os}.
21499 If @option{--target} was specified, then @code{target} is the
21500 canonicalization of @code{target_alias} by @command{config.sub},
21501 otherwise it defaults to @code{host}.
21502 @end defmac
21504 Note that there can be artifacts due to the backward compatibility
21505 code.  @xref{Hosts and Cross-Compilation}, for more.
21507 @node Using System Type
21508 @section Using the System Type
21510 In @file{configure.ac} the system type is generally used by one or more
21511 @code{case} statements to select system-specifics.  Shell wildcards can
21512 be used to match a group of system types.
21514 For example, an extra assembler code object file could be chosen, giving
21515 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
21516 following would be used in a makefile to add the object to a
21517 program or library.
21519 @example
21520 AS_CASE([$host],
21521   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
21522   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
21523   [CYCLE_OBJ=""]
21525 AC_SUBST([CYCLE_OBJ])
21526 @end example
21528 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
21529 to select variant source files, for example optimized code for some
21530 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
21531 so some runtime capability checks may be necessary too.
21533 @example
21534 case $host in
21535   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
21536   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
21537   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
21538 esac
21539 @end example
21541 The host system type can also be used to find cross-compilation tools
21542 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
21544 The above examples all show @samp{$host}, since this is where the code
21545 is going to run.  Only rarely is it necessary to test @samp{$build}
21546 (which is where the build is being done).
21548 Whenever you're tempted to use @samp{$host} it's worth considering
21549 whether some sort of probe would be better.  New system types come along
21550 periodically or previously missing features are added.  Well-written
21551 probes can adapt themselves to such things, but hard-coded lists of
21552 names can't.  Here are some guidelines,
21554 @itemize @bullet
21555 @item
21556 Availability of libraries and library functions should always be checked
21557 by probing.
21558 @item
21559 Variant behavior of system calls is best identified with runtime tests
21560 if possible, but bug workarounds or obscure difficulties might have to
21561 be driven from @samp{$host}.
21562 @item
21563 Assembler code is inevitably highly CPU-specific and is best selected
21564 according to @samp{$host_cpu}.
21565 @item
21566 Assembler variations like underscore prefix on globals or ELF versus
21567 COFF type directives are however best determined by probing, perhaps
21568 even examining the compiler output.
21569 @end itemize
21571 @samp{$target} is for use by a package creating a compiler or similar.
21572 For ordinary packages it's meaningless and should not be used.  It
21573 indicates what the created compiler should generate code for, if it can
21574 cross-compile.  @samp{$target} generally selects various hard-coded CPU
21575 and system conventions, since usually the compiler or tools under
21576 construction themselves determine how the target works.
21579 @c ===================================================== Site Configuration.
21581 @node Site Configuration
21582 @chapter Site Configuration
21584 @command{configure} scripts support several kinds of local configuration
21585 decisions.  There are ways for users to specify where external software
21586 packages are, include or exclude optional features, install programs
21587 under modified names, and set default values for @command{configure}
21588 options.
21590 @menu
21591 * Help Formatting::             Customizing @samp{configure --help}
21592 * External Software::           Working with other optional software
21593 * Package Options::             Selecting optional features
21594 * Pretty Help Strings::         Formatting help string
21595 * Option Checking::             Controlling checking of @command{configure} options
21596 * Site Details::                Configuring site details
21597 * Transforming Names::          Changing program names when installing
21598 * Site Defaults::               Giving @command{configure} local defaults
21599 @end menu
21601 @node Help Formatting
21602 @section Controlling Help Output
21604 Users consult @samp{configure --help} to learn of configuration
21605 decisions specific to your package.  By default, @command{configure}
21606 breaks this output into sections for each type of option; within each
21607 section, help strings appear in the order @file{configure.ac} defines
21608 them:
21610 @example
21611 Optional Features:
21612   @dots{}
21613   --enable-bar            include bar
21615 Optional Packages:
21616   @dots{}
21617   --with-foo              use foo
21618 @end example
21620 @defmac AC_PRESERVE_HELP_ORDER
21621 @acindex{PRESERVE_HELP_ORDER}
21623 Request an alternate @option{--help} format, in which options of all
21624 types appear together, in the order defined.  Call this macro before any
21625 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
21627 @example
21628 Optional Features and Packages:
21629   @dots{}
21630   --enable-bar            include bar
21631   --with-foo              use foo
21632 @end example
21634 @end defmac
21636 @node External Software
21637 @section Working With External Software
21638 @cindex External software
21640 Some packages require, or can optionally use, other software packages
21641 that are already installed.  The user can give @command{configure}
21642 command line options to specify which such external software to use.
21643 The options have one of these forms:
21645 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21646 @c awful.
21647 @example
21648 --with-@var{package}@r{[}=@var{arg}@r{]}
21649 --without-@var{package}
21650 @end example
21652 For example, @option{--with-gnu-ld} means work with the GNU linker
21653 instead of some other linker.  @option{--with-x} means work with The X
21654 Window System.
21656 The user can give an argument by following the package name with
21657 @samp{=} and the argument.  Giving an argument of @samp{no} is for
21658 packages that are used by default; it says to @emph{not} use the
21659 package.  An argument that is neither @samp{yes} nor @samp{no} could
21660 include a name or number of a version of the other package, to specify
21661 more precisely which other package this program is supposed to work
21662 with.  If no argument is given, it defaults to @samp{yes}.
21663 @option{--without-@var{package}} is equivalent to
21664 @option{--with-@var{package}=no}.
21666 Normally @command{configure} scripts complain about
21667 @option{--with-@var{package}} options that they do not support.
21668 @xref{Option Checking}, for details, and for how to override the
21669 defaults.
21671 For each external software package that may be used, @file{configure.ac}
21672 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
21673 user asked to use it.  Whether each package is used or not by default,
21674 and which arguments are valid, is up to you.
21676 @anchor{AC_ARG_WITH}
21677 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
21678   @ovar{action-if-given}, @ovar{action-if-not-given})
21679 @acindex{ARG_WITH}
21680 If the user gave @command{configure} the option @option{--with-@var{package}}
21681 or @option{--without-@var{package}}, run shell commands
21682 @var{action-if-given}.  If neither option was given, run shell commands
21683 @var{action-if-not-given}.  The name @var{package} indicates another
21684 software package that this program should work with.  It should consist
21685 only of alphanumeric characters, dashes, plus signs, and dots.
21687 The option's argument is available to the shell commands
21688 @var{action-if-given} in the shell variable @code{withval}, which is
21689 actually just the value of the shell variable named
21690 @code{with_@var{package}}, with any non-alphanumeric characters in
21691 @var{package} changed into @samp{_}.  You may use that variable instead,
21692 if you wish.
21694 The argument @var{help-string} is a description of the option that
21695 looks like this:
21696 @example
21697   --with-readline         support fancy command line editing
21698 @end example
21700 @noindent
21701 @var{help-string} may be more than one line long, if more detail is
21702 needed.  Just make sure the columns line up in @samp{configure
21703 --help}.  Avoid tabs in the help string.  The easiest way to provide the
21704 proper leading whitespace is to format your @var{help-string} with the macro
21705 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21707 The following example shows how to use the @code{AC_ARG_WITH} macro in
21708 a common situation.  You want to let the user decide whether to enable
21709 support for an external library (e.g., the readline library); if the user
21710 specified neither @option{--with-readline} nor @option{--without-readline},
21711 you want to enable support for readline only if the library is available
21712 on the system.
21714 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21715 @example
21716 AC_ARG_WITH([readline],
21717   [AS_HELP_STRING([--with-readline],
21718     [support fancy command line editing @@<:@@default=check@@:>@@])],
21719   [],
21720   [with_readline=check])
21722 LIBREADLINE=
21723 AS_IF([test "x$with_readline" != xno],
21724   [AC_CHECK_LIB([readline], [main],
21725     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21726      AC_DEFINE([HAVE_LIBREADLINE], [1],
21727                [Define if you have libreadline])
21728     ],
21729     [if test "x$with_readline" != xcheck; then
21730        AC_MSG_FAILURE(
21731          [--with-readline was given, but test for readline failed])
21732      fi
21733     ], -lncurses)])
21734 @end example
21736 The next example shows how to use @code{AC_ARG_WITH} to give the user the
21737 possibility to enable support for the readline library, in case it is still
21738 experimental and not well tested, and is therefore disabled by default.
21740 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21741 @example
21742 AC_ARG_WITH([readline],
21743   [AS_HELP_STRING([--with-readline],
21744     [enable experimental support for readline])],
21745   [],
21746   [with_readline=no])
21748 LIBREADLINE=
21749 AS_IF([test "x$with_readline" != xno],
21750   [AC_CHECK_LIB([readline], [main],
21751     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21752      AC_DEFINE([HAVE_LIBREADLINE], [1],
21753                [Define if you have libreadline])
21754     ],
21755     [AC_MSG_FAILURE(
21756        [--with-readline was given, but test for readline failed])],
21757     [-lncurses])])
21758 @end example
21760 The last example shows how to use @code{AC_ARG_WITH} to give the user the
21761 possibility to disable support for the readline library, given that it is
21762 an important feature and that it should be enabled by default.
21764 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
21765 @example
21766 AC_ARG_WITH([readline],
21767   [AS_HELP_STRING([--without-readline],
21768     [disable support for readline])],
21769   [],
21770   [with_readline=yes])
21772 LIBREADLINE=
21773 AS_IF([test "x$with_readline" != xno],
21774   [AC_CHECK_LIB([readline], [main],
21775     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
21776      AC_DEFINE([HAVE_LIBREADLINE], [1],
21777                [Define if you have libreadline])
21778     ],
21779     [AC_MSG_FAILURE(
21780        [readline test failed (--without-readline to disable)])],
21781     [-lncurses])])
21782 @end example
21784 These three examples can be easily adapted to the case where
21785 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
21786 @ref{Package Options}).
21787 @end defmac
21789 @node Package Options
21790 @section Choosing Package Options
21791 @cindex Package options
21792 @cindex Options, package
21794 If a software package has optional compile-time features, the user can
21795 give @command{configure} command line options to specify whether to
21796 compile them.  The options have one of these forms:
21798 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
21799 @c awful.
21800 @example
21801 --enable-@var{feature}@r{[}=@var{arg}@r{]}
21802 --disable-@var{feature}
21803 @end example
21805 These options allow users to choose which optional features to build and
21806 install.  @option{--enable-@var{feature}} options should never make a
21807 feature behave differently or cause one feature to replace another.
21808 They should only cause parts of the program to be built rather than left
21809 out.
21811 The user can give an argument by following the feature name with
21812 @samp{=} and the argument.  Giving an argument of @samp{no} requests
21813 that the feature @emph{not} be made available.  A feature with an
21814 argument looks like @option{--enable-debug=stabs}.  If no argument is
21815 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
21816 equivalent to @option{--enable-@var{feature}=no}.
21818 Normally @command{configure} scripts complain about
21819 @option{--enable-@var{package}} options that they do not support.
21820 @xref{Option Checking}, for details, and for how to override the
21821 defaults.
21823 For each optional feature, @file{configure.ac} should call
21824 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
21825 to include it.  Whether each feature is included or not by default, and
21826 which arguments are valid, is up to you.
21828 @anchor{AC_ARG_ENABLE}
21829 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
21830   @ovar{action-if-given}, @ovar{action-if-not-given})
21831 @acindex{ARG_ENABLE}
21832 If the user gave @command{configure} the option
21833 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
21834 shell commands @var{action-if-given}.  If neither option was given, run
21835 shell commands @var{action-if-not-given}.  The name @var{feature}
21836 indicates an optional user-level facility.  It should consist only of
21837 alphanumeric characters, dashes, plus signs, and dots.
21839 The option's argument is available to the shell commands
21840 @var{action-if-given} in the shell variable @code{enableval}, which is
21841 actually just the value of the shell variable named
21842 @code{enable_@var{feature}}, with any non-alphanumeric characters in
21843 @var{feature} changed into @samp{_}.  You may use that variable instead,
21844 if you wish.  The @var{help-string} argument is like that of
21845 @code{AC_ARG_WITH} (@pxref{External Software}).
21847 You should format your @var{help-string} with the macro
21848 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
21850 See the examples suggested with the definition of @code{AC_ARG_WITH}
21851 (@pxref{External Software}) to get an idea of possible applications of
21852 @code{AC_ARG_ENABLE}.
21853 @end defmac
21855 @node Pretty Help Strings
21856 @section Making Your Help Strings Look Pretty
21857 @cindex Help strings
21859 Properly formatting the @samp{help strings} which are used in
21860 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
21861 (@pxref{Package Options}) can be challenging.  Specifically, you want
21862 your own @samp{help strings} to line up in the appropriate columns of
21863 @samp{configure --help} just like the standard Autoconf @samp{help
21864 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
21866 @anchor{AS_HELP_STRING}
21867 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
21868   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
21869 @asindex{HELP_STRING}
21871 Expands into a help string that looks pretty when the user executes
21872 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
21873 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
21874 Options}).  The following example makes this clearer.
21876 @example
21877 AC_ARG_WITH([foo],
21878   [AS_HELP_STRING([--with-foo],
21879      [use foo (default is no)])],
21880   [use_foo=$withval],
21881   [use_foo=no])
21882 @end example
21884 Then the last few lines of @samp{configure --help} appear like
21885 this:
21887 @example
21888 --enable and --with options recognized:
21889   --with-foo              use foo (default is no)
21890 @end example
21892 Macro expansion is performed on the first argument.  However, the second
21893 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
21894 list of text to be reformatted, and is not subject to macro expansion.
21895 Since it is not expanded, it should not be double quoted.
21896 @xref{Autoconf Language}, for a more detailed explanation.
21898 The @code{AS_HELP_STRING} macro is particularly helpful when the
21899 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
21900 arguments, as shown in the following example.  Be aware that
21901 @var{left-hand-side} may not expand to unbalanced quotes,
21902 although quadrigraphs can be used.
21904 @example
21905 AC_DEFUN([MY_ARG_WITH],
21906   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
21907      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
21908                      [use $1 (default is $2)])],
21909      [use_[]$1=$withval],
21910      [use_[]$1=$2])])
21911 MY_ARG_WITH([a_b], [no])
21912 @end example
21913 @noindent
21914 Here, the last few lines of @samp{configure --help} will include:
21916 @example
21917 --enable and --with options recognized:
21918   --with-a-b              use a_b (default is no)
21919 @end example
21921 The parameters @var{indent-column} and @var{wrap-column} were introduced
21922 in Autoconf 2.62.  Generally, they should not be specified; they exist
21923 for fine-tuning of the wrapping.
21924 @example
21925 AS_HELP_STRING([--option], [description of option])
21926 @result{}  --option                description of option
21927 AS_HELP_STRING([--option], [description of option], [15], [30])
21928 @result{}  --option     description of
21929 @result{}               option
21930 @end example
21931 @end defmac
21934 @node Option Checking
21935 @section Controlling Checking of @command{configure} Options
21936 @cindex Options, Package
21938 The @command{configure} script checks its command-line options against a
21939 list of known options, like @option{--help} or @option{--config-cache}.
21940 An unknown option ordinarily indicates a mistake by the user and
21941 @command{configure} halts with an error.  However, by default unknown
21942 @option{--with-@var{package}} and @option{--enable-@var{feature}}
21943 options elicit only a warning, to support configuring entire source
21944 trees.
21946 Source trees often contain multiple packages with a top-level
21947 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
21948 (@pxref{Subdirectories}).  Because the packages generally support
21949 different @option{--with-@var{package}} and
21950 @option{--enable-@var{feature}} options, the GNU Coding
21951 Standards say they must accept unrecognized options without halting.
21952 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
21953 automatically disables the warnings.
21955 This default behavior may be modified in two ways.  First, the installer
21956 can invoke @code{configure --disable-option-checking} to disable
21957 these warnings, or invoke @code{configure --enable-option-checking=fatal}
21958 options to turn them into fatal errors, respectively.  Second, the
21959 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
21961 @defmac AC_DISABLE_OPTION_CHECKING
21962 @acindex{DISABLE_OPTION_CHECKING}
21964 By default, disable warnings related to any unrecognized
21965 @option{--with-@var{package}} or @option{--enable-@var{feature}}
21966 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
21968 The installer can override this behavior by passing
21969 @option{--enable-option-checking} (enable warnings) or
21970 @option{--enable-option-checking=fatal} (enable errors) to
21971 @command{configure}.
21972 @end defmac
21975 @node Site Details
21976 @section Configuring Site Details
21977 @cindex Site details
21979 Some software packages require complex site-specific information.  Some
21980 examples are host names to use for certain services, company names, and
21981 email addresses to contact.  Since some configuration scripts generated
21982 by Metaconfig ask for such information interactively, people sometimes
21983 wonder how to get that information in Autoconf-generated configuration
21984 scripts, which aren't interactive.
21986 Such site configuration information should be put in a file that is
21987 edited @emph{only by users}, not by programs.  The location of the file
21988 can either be based on the @code{prefix} variable, or be a standard
21989 location such as the user's home directory.  It could even be specified
21990 by an environment variable.  The programs should examine that file at
21991 runtime, rather than at compile time.  Runtime configuration is more
21992 convenient for users and makes the configuration process simpler than
21993 getting the information while configuring.  @xref{Directory Variables, ,
21994 Variables for Installation Directories, standards, The GNU Coding
21995 Standards}, for more information on where to put data files.
21997 @node Transforming Names
21998 @section Transforming Program Names When Installing
21999 @cindex Transforming program names
22000 @cindex Program names, transforming
22002 Autoconf supports changing the names of programs when installing them.
22003 In order to use these transformations, @file{configure.ac} must call the
22004 macro @code{AC_ARG_PROGRAM}.
22006 @defmac AC_ARG_PROGRAM
22007 @acindex{ARG_PROGRAM}
22008 @ovindex program_transform_name
22009 Place in output variable @code{program_transform_name} a sequence of
22010 @code{sed} commands for changing the names of installed programs.
22012 If any of the options described below are given to @command{configure},
22013 program names are transformed accordingly.  Otherwise, if
22014 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22015 is given, the target type followed by a dash is used as a prefix.
22016 Otherwise, no program name transformation is done.
22017 @end defmac
22019 @menu
22020 * Transformation Options::      @command{configure} options to transform names
22021 * Transformation Examples::     Sample uses of transforming names
22022 * Transformation Rules::        Makefile uses of transforming names
22023 @end menu
22025 @node Transformation Options
22026 @subsection Transformation Options
22028 You can specify name transformations by giving @command{configure} these
22029 command line options:
22031 @table @option
22032 @item --program-prefix=@var{prefix}
22033 prepend @var{prefix} to the names;
22035 @item --program-suffix=@var{suffix}
22036 append @var{suffix} to the names;
22038 @item --program-transform-name=@var{expression}
22039 perform @code{sed} substitution @var{expression} on the names.
22040 @end table
22042 @node Transformation Examples
22043 @subsection Transformation Examples
22045 These transformations are useful with programs that can be part of a
22046 cross-compilation development environment.  For example, a
22047 cross-assembler running on a Sun 4 configured with
22048 @option{--target=i960-vxworks} is normally installed as
22049 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22050 with a native Sun 4 assembler.
22052 You can force a program name to begin with @file{g}, if you don't want
22053 GNU programs installed on your system to shadow other programs with
22054 the same name.  For example, if you configure GNU @code{diff} with
22055 @option{--program-prefix=g}, then when you run @samp{make install} it is
22056 installed as @file{/usr/local/bin/gdiff}.
22058 As a more sophisticated example, you could use
22060 @example
22061 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22062 @end example
22063 @noindent
22065 to prepend @samp{g} to most of the program names in a source tree,
22066 excepting those like @code{gdb} that already have one and those like
22067 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22068 assuming that you have a source tree containing those programs that is
22069 set up to use this feature.)
22071 One way to install multiple versions of some programs simultaneously is
22072 to append a version number to the name of one or both.  For example, if
22073 you want to keep Autoconf version 1 around for awhile, you can configure
22074 Autoconf version 2 using @option{--program-suffix=2} to install the
22075 programs as @file{/usr/local/bin/autoconf2},
22076 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22077 that only the binaries are renamed, therefore you'd have problems with
22078 the library files which might overlap.
22080 @node Transformation Rules
22081 @subsection Transformation Rules
22083 Here is how to use the variable @code{program_transform_name} in a
22084 @file{Makefile.in}:
22086 @example
22087 PROGRAMS = cp ls rm
22088 transform = @@program_transform_name@@
22089 install:
22090         for p in $(PROGRAMS); do \
22091           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22092                                               sed '$(transform)'`; \
22093         done
22095 uninstall:
22096         for p in $(PROGRAMS); do \
22097           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22098 @c $$ restore font-lock
22099         done
22100 @end example
22102 It is guaranteed that @code{program_transform_name} is never empty, and
22103 that there are no useless separators.  Therefore you may safely embed
22104 @code{program_transform_name} within a sed program using @samp{;}:
22106 @example
22107 transform = @@program_transform_name@@
22108 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22109 @end example
22111 Whether to do the transformations on documentation files (Texinfo or
22112 @code{man}) is a tricky question; there seems to be no perfect answer,
22113 due to the several reasons for name transforming.  Documentation is not
22114 usually particular to a specific architecture, and Texinfo files do not
22115 conflict with system documentation.  But they might conflict with
22116 earlier versions of the same files, and @code{man} pages sometimes do
22117 conflict with system documentation.  As a compromise, it is probably
22118 best to do name transformations on @code{man} pages but not on Texinfo
22119 manuals.
22121 @node Site Defaults
22122 @section Setting Site Defaults
22123 @cindex Site defaults
22124 @cindex config.site
22126 Autoconf-generated @command{configure} scripts allow your site to provide
22127 default values for some configuration values.  You do this by creating
22128 site- and system-wide initialization files.
22130 @evindex CONFIG_SITE
22131 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22132 uses its value as the name of a shell script to read; it is recommended
22133 that this be an absolute file name.  Otherwise, it
22134 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22135 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22136 settings in machine-specific files override those in machine-independent
22137 ones in case of conflict.
22139 Site files can be arbitrary shell scripts, but only certain kinds of
22140 code are really appropriate to be in them.  Because @command{configure}
22141 reads any cache file after it has read any site files, a site file can
22142 define a default cache file to be shared between all Autoconf-generated
22143 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22144 you set a default cache file in a site file, it is a good idea to also
22145 set the output variable @code{CC} in that site file, because the cache
22146 file is only valid for a particular compiler, but many systems have
22147 several available.
22149 You can examine or override the value set by a command line option to
22150 @command{configure} in a site file; options set shell variables that have
22151 the same names as the options, with any dashes turned into underscores.
22152 The exceptions are that @option{--without-} and @option{--disable-} options
22153 are like giving the corresponding @option{--with-} or @option{--enable-}
22154 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22155 sets the variable @code{cache_file} to the value @samp{localcache};
22156 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22157 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22158 variable @code{prefix} to the value @samp{/usr}; etc.
22160 Site files are also good places to set default values for other output
22161 variables, such as @code{CFLAGS}, if you need to give them non-default
22162 values: anything you would normally do, repetitively, on the command
22163 line.  If you use non-default values for @var{prefix} or
22164 @var{exec_prefix} (wherever you locate the site file), you can set them
22165 in the site file if you specify it with the @code{CONFIG_SITE}
22166 environment variable.
22168 You can set some cache values in the site file itself.  Doing this is
22169 useful if you are cross-compiling, where it is impossible to check features
22170 that require running a test program.  You could ``prime the cache'' by
22171 setting those values correctly for that system in
22172 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22173 variables you need to set, see the documentation of the respective
22174 Autoconf macro.  If the variables or their semantics are undocumented,
22175 you may need to look for shell variables with @samp{_cv_} in their names
22176 in the affected @command{configure} scripts, or in the Autoconf M4
22177 source code for those macros; but in that case, their name or semantics
22178 may change in a future Autoconf version.
22180 The cache file is careful to not override any variables set in the site
22181 files.  Similarly, you should not override command-line options in the
22182 site files.  Your code should check that variables such as @code{prefix}
22183 and @code{cache_file} have their default values (as set near the top of
22184 @command{configure}) before changing them.
22186 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22187 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22188 file (if @code{CONFIG_SITE} is not set to a different file).
22190 @example
22191 # /usr/share/local/gnu/share/config.site for configure
22193 # Change some defaults.
22194 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22195 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22196 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22197 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22199 # Give Autoconf 2.x generated configure scripts a shared default
22200 # cache file for feature test results, architecture-specific.
22201 if test "$cache_file" = /dev/null; then
22202   cache_file="$prefix/var/config.cache"
22203   # A cache file is only valid for one C compiler.
22204   CC=gcc
22206 @end example
22208 @cindex Filesystem Hierarchy Standard
22209 @cindex FHS
22211 Another use of @file{config.site} is for priming the directory variables
22212 in a manner consistent with the Filesystem Hierarchy Standard
22213 (FHS).  Once the following file is installed at
22214 @file{/usr/share/config.site}, a user can execute simply
22215 @code{./configure --prefix=/usr} to get all the directories chosen in
22216 the locations recommended by FHS.
22218 @example
22219 # /usr/share/config.site for FHS defaults when installing below /usr,
22220 # and the respective settings were not changed on the command line.
22221 if test "$prefix" = /usr; then
22222   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22223   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22224   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22226 @end example
22228 @cindex @file{lib64}
22229 @cindex 64-bit libraries
22230 Likewise, on platforms where 64-bit libraries are built by default, then
22231 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22232 it is appropriate to install @file{/usr/local/@/share/config.site}:
22234 @example
22235 # /usr/local/share/config.site for platforms that prefer
22236 # the directory /usr/local/lib64 over /usr/local/lib.
22237 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22238 @end example
22241 @c ============================================== Running configure Scripts.
22243 @node Running configure Scripts
22244 @chapter Running @command{configure} Scripts
22245 @cindex @command{configure}
22247 Below are instructions on how to configure a package that uses a
22248 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22249 file in the package.  A plain-text version of @file{INSTALL} which you
22250 may use comes with Autoconf.
22252 @menu
22253 * Basic Installation::          Instructions for typical cases
22254 * Compilers and Options::       Selecting compilers and optimization
22255 * Multiple Architectures::      Compiling for multiple architectures at once
22256 * Installation Names::          Installing in different directories
22257 * Optional Features::           Selecting optional features
22258 * Particular Systems::          Particular systems
22259 * System Type::                 Specifying the system type
22260 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22261 * Defining Variables::          Specifying the compiler etc.
22262 * configure Invocation::        Changing how @command{configure} runs
22263 @end menu
22265 @set autoconf
22266 @include install.texi
22269 @c ============================================== config.status Invocation
22271 @node config.status Invocation
22272 @chapter config.status Invocation
22273 @cindex @command{config.status}
22275 The @command{configure} script creates a file named @file{config.status},
22276 which actually configures, @dfn{instantiates}, the template files.  It
22277 also records the configuration options that were specified when the
22278 package was last configured in case reconfiguring is needed.
22280 Synopsis:
22281 @example
22282 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22283 @end example
22285 It configures each @var{tag}; if none are specified, all the templates
22286 are instantiated.  A @var{tag} refers to a file or other tag associated
22287 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22288 macro (@pxref{Configuration Actions}).  The files must be specified
22289 without their dependencies, as in
22291 @example
22292 ./config.status foobar
22293 @end example
22295 @noindent
22298 @example
22299 ./config.status foobar:foo.in:bar.in
22300 @end example
22302 The supported options are:
22304 @table @option
22305 @item --help
22306 @itemx -h
22307 Print a summary of the command line options, the list of the template
22308 files, and exit.
22310 @item --version
22311 @itemx -V
22312 Print the version number of Autoconf and the configuration settings,
22313 and exit.
22315 @item --config
22316 Print the configuration settings in reusable way, quoted for the shell,
22317 and exit.  For example, for a debugging build that otherwise reuses the
22318 configuration from a different build directory @var{build-dir} of a
22319 package in @var{src-dir}, you could use the following:
22321 @example
22322 args=`@var{build-dir}/config.status --config`
22323 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22324 @end example
22326 @noindent
22327 Note that it may be necessary to override a @option{--srcdir} setting
22328 that was saved in the configuration, if the arguments are used in a
22329 different build directory.
22331 @item --silent
22332 @itemx --quiet
22333 @itemx -q
22334 Do not print progress messages.
22336 @item --debug
22337 @itemx -d
22338 Don't remove the temporary files.
22340 @item --file=@var{file}[:@var{template}]
22341 Require that @var{file} be instantiated as if
22342 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22343 @var{file} and @var{template} may be @samp{-} in which case the standard
22344 output and/or standard input, respectively, is used.  If a
22345 @var{template} file name is relative, it is first looked for in the build
22346 tree, and then in the source tree.  @xref{Configuration Actions}, for
22347 more details.
22349 This option and the following ones provide one way for separately
22350 distributed packages to share the values computed by @command{configure}.
22351 Doing so can be useful if some of the packages need a superset of the
22352 features that one of them, perhaps a common library, does.  These
22353 options allow a @file{config.status} file to create files other than the
22354 ones that its @file{configure.ac} specifies, so it can be used for a
22355 different package, or for extracting a subset of values.  For example,
22357 @example
22358 echo '@@CC@@' | ./config.status --file=-
22359 @end example
22361 @noindent
22362 provides the value of @code{@@CC@@} on standard output.
22364 @item --header=@var{file}[:@var{template}]
22365 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22367 @item --recheck
22368 Ask @file{config.status} to update itself and exit (no instantiation).
22369 This option is useful if you change @command{configure}, so that the
22370 results of some tests might be different from the previous run.  The
22371 @option{--recheck} option reruns @command{configure} with the same arguments
22372 you used before, plus the @option{--no-create} option, which prevents
22373 @command{configure} from running @file{config.status} and creating
22374 @file{Makefile} and other files, and the @option{--no-recursion} option,
22375 which prevents @command{configure} from running other @command{configure}
22376 scripts in subdirectories.  (This is so other Make rules can
22377 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22378 for an example).
22379 @end table
22381 @file{config.status} checks several optional environment variables that
22382 can alter its behavior:
22384 @anchor{CONFIG_SHELL}
22385 @defvar CONFIG_SHELL
22386 @evindex CONFIG_SHELL
22387 The shell with which to run @command{configure} for the @option{--recheck}
22388 option.  It must be Bourne-compatible.  The default is a shell that
22389 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
22390 Invoking @command{configure} by hand bypasses this setting, so you may
22391 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
22392 to insure that the same shell is used everywhere.  The absolute name of the
22393 shell should be passed.
22394 @end defvar
22396 @defvar CONFIG_STATUS
22397 @evindex CONFIG_STATUS
22398 The file name to use for the shell script that records the
22399 configuration.  The default is @file{./config.status}.  This variable is
22400 useful when one package uses parts of another and the @command{configure}
22401 scripts shouldn't be merged because they are maintained separately.
22402 @end defvar
22404 You can use @file{./config.status} in your makefiles.  For example, in
22405 the dependencies given above (@pxref{Automatic Remaking}),
22406 @file{config.status} is run twice when @file{configure.ac} has changed.
22407 If that bothers you, you can make each run only regenerate the files for
22408 that rule:
22409 @example
22410 @group
22411 config.h: stamp-h
22412 stamp-h: config.h.in config.status
22413         ./config.status config.h
22414         echo > stamp-h
22416 Makefile: Makefile.in config.status
22417         ./config.status Makefile
22418 @end group
22419 @end example
22421 The calling convention of @file{config.status} has changed; see
22422 @ref{Obsolete config.status Use}, for details.
22425 @c =================================================== Obsolete Constructs
22427 @node Obsolete Constructs
22428 @chapter Obsolete Constructs
22429 @cindex Obsolete constructs
22431 Autoconf changes, and throughout the years some constructs have been
22432 obsoleted.  Most of the changes involve the macros, but in some cases
22433 the tools themselves, or even some concepts, are now considered
22434 obsolete.
22436 You may completely skip this chapter if you are new to Autoconf.  Its
22437 intention is mainly to help maintainers updating their packages by
22438 understanding how to move to more modern constructs.
22440 @menu
22441 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
22442 * acconfig Header::             Additional entries in @file{config.h.in}
22443 * autoupdate Invocation::       Automatic update of @file{configure.ac}
22444 * Obsolete Macros::             Backward compatibility macros
22445 * Autoconf 1::                  Tips for upgrading your files
22446 * Autoconf 2.13::               Some fresher tips
22447 @end menu
22449 @node Obsolete config.status Use
22450 @section Obsolete @file{config.status} Invocation
22452 @file{config.status} now supports arguments to specify the files to
22453 instantiate; see @ref{config.status Invocation}, for more details.
22454 Before, environment variables had to be used.
22456 @defvar CONFIG_COMMANDS
22457 @evindex CONFIG_COMMANDS
22458 The tags of the commands to execute.  The default is the arguments given
22459 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
22460 @file{configure.ac}.
22461 @end defvar
22463 @defvar CONFIG_FILES
22464 @evindex CONFIG_FILES
22465 The files in which to perform @samp{@@@var{variable}@@} substitutions.
22466 The default is the arguments given to @code{AC_OUTPUT} and
22467 @code{AC_CONFIG_FILES} in @file{configure.ac}.
22468 @end defvar
22470 @defvar CONFIG_HEADERS
22471 @evindex CONFIG_HEADERS
22472 The files in which to substitute C @code{#define} statements.  The
22473 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
22474 macro was not called, @file{config.status} ignores this variable.
22475 @end defvar
22477 @defvar CONFIG_LINKS
22478 @evindex CONFIG_LINKS
22479 The symbolic links to establish.  The default is the arguments given to
22480 @code{AC_CONFIG_LINKS}; if that macro was not called,
22481 @file{config.status} ignores this variable.
22482 @end defvar
22484 In @ref{config.status Invocation}, using this old interface, the example
22485 would be:
22487 @example
22488 @group
22489 config.h: stamp-h
22490 stamp-h: config.h.in config.status
22491         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
22492           CONFIG_HEADERS=config.h ./config.status
22493         echo > stamp-h
22495 Makefile: Makefile.in config.status
22496         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
22497           CONFIG_FILES=Makefile ./config.status
22498 @end group
22499 @end example
22501 @noindent
22502 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
22503 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
22504 for @code{CONFIG_COMMANDS}, etc.)
22507 @node acconfig Header
22508 @section @file{acconfig.h}
22510 @cindex @file{acconfig.h}
22511 @cindex @file{config.h.top}
22512 @cindex @file{config.h.bot}
22514 In order to produce @file{config.h.in}, @command{autoheader} needs to
22515 build or to find templates for each symbol.  Modern releases of Autoconf
22516 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
22517 Macros}), but in older releases a file, @file{acconfig.h}, contained the
22518 list of needed templates.  @command{autoheader} copied comments and
22519 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
22520 the current directory, if present.  This file used to be mandatory if
22521 you @code{AC_DEFINE} any additional symbols.
22523 Modern releases of Autoconf also provide @code{AH_TOP} and
22524 @code{AH_BOTTOM} if you need to prepend/append some information to
22525 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
22526 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
22527 @command{autoheader} copies the lines before the line containing
22528 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
22529 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
22530 @command{autoheader} copies the lines after that line to the end of the
22531 file it generates.  Either or both of those strings may be omitted.  An
22532 even older alternate way to produce the same effect in ancient versions
22533 of Autoconf is to create the files @file{@var{file}.top} (typically
22534 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
22535 directory.  If they exist, @command{autoheader} copies them to the
22536 beginning and end, respectively, of its output.
22538 In former versions of Autoconf, the files used in preparing a software
22539 package for distribution were:
22540 @example
22541 @group
22542 configure.ac --.   .------> autoconf* -----> configure
22543                +---+
22544 [aclocal.m4] --+   `---.
22545 [acsite.m4] ---'       |
22546                        +--> [autoheader*] -> [config.h.in]
22547 [acconfig.h] ----.     |
22548                  +-----'
22549 [config.h.top] --+
22550 [config.h.bot] --'
22551 @end group
22552 @end example
22554 Using only the @code{AH_} macros, @file{configure.ac} should be
22555 self-contained, and should not depend upon @file{acconfig.h} etc.
22558 @node autoupdate Invocation
22559 @section Using @command{autoupdate} to Modernize @file{configure.ac}
22560 @cindex @command{autoupdate}
22562 The @command{autoupdate} program updates a @file{configure.ac} file that
22563 calls Autoconf macros by their old names to use the current macro names.
22564 In version 2 of Autoconf, most of the macros were renamed to use a more
22565 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
22566 description of the new scheme.  Although the old names still work
22567 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
22568 new names), you can make your @file{configure.ac} files more readable
22569 and make it easier to use the current Autoconf documentation if you
22570 update them to use the new macro names.
22572 @evindex SIMPLE_BACKUP_SUFFIX
22573 If given no arguments, @command{autoupdate} updates @file{configure.ac},
22574 backing up the original version with the suffix @file{~} (or the value
22575 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
22576 set).  If you give @command{autoupdate} an argument, it reads that file
22577 instead of @file{configure.ac} and writes the updated file to the
22578 standard output.
22580 @noindent
22581 @command{autoupdate} accepts the following options:
22583 @table @option
22584 @item --help
22585 @itemx -h
22586 Print a summary of the command line options and exit.
22588 @item --version
22589 @itemx -V
22590 Print the version number of Autoconf and exit.
22592 @item --verbose
22593 @itemx -v
22594 Report processing steps.
22596 @item --debug
22597 @itemx -d
22598 Don't remove the temporary files.
22600 @item --force
22601 @itemx -f
22602 Force the update even if the file has not changed.  Disregard the cache.
22604 @item --include=@var{dir}
22605 @itemx -I @var{dir}
22606 Also look for input files in @var{dir}.  Multiple invocations accumulate.
22607 Directories are browsed from last to first.
22609 @item --prepend-include=@var{dir}
22610 @itemx -B @var{dir}
22611 Prepend directory @var{dir} to the search path.  This is used to include
22612 the language-specific files before any third-party macros.
22613 @end table
22615 @node Obsolete Macros
22616 @section Obsolete Macros
22618 Several macros are obsoleted in Autoconf, for various reasons (typically
22619 they failed to quote properly, couldn't be extended for more recent
22620 issues, etc.).  They are still supported, but deprecated: their use
22621 should be avoided.
22623 During the jump from Autoconf version 1 to version 2, most of the
22624 macros were renamed to use a more uniform and descriptive naming scheme,
22625 but their signature did not change.  @xref{Macro Names}, for a
22626 description of the new naming scheme.  Below, if there is just the mapping
22627 from old names to new names for these macros, the reader is invited to
22628 refer to the definition of the new macro for the signature and the
22629 description.
22631 @defmac AC_AIX
22632 @acindex{AIX}
22633 @cvindex _ALL_SOURCE
22634 This macro is a platform-specific subset of
22635 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22636 @end defmac
22638 @defmac AC_ALLOCA
22639 @acindex{ALLOCA}
22640 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
22641 @end defmac
22643 @defmac AC_ARG_ARRAY
22644 @acindex{ARG_ARRAY}
22645 Removed because of limited usefulness.
22646 @end defmac
22648 @defmac AC_C_CROSS
22649 @acindex{C_CROSS}
22650 This macro is obsolete; it does nothing.
22651 @end defmac
22653 @defmac AC_C_LONG_DOUBLE
22654 @acindex{C_LONG_DOUBLE}
22655 @cvindex HAVE_LONG_DOUBLE
22656 If the C compiler supports a working @code{long double} type with more
22657 range or precision than the @code{double} type, define
22658 @code{HAVE_LONG_DOUBLE}.
22660 You should use @code{AC_TYPE_LONG_DOUBLE} or
22661 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
22662 @end defmac
22664 @defmac AC_CANONICAL_SYSTEM
22665 @acindex{CANONICAL_SYSTEM}
22666 Determine the system type and set output variables to the names of the
22667 canonical system types.  @xref{Canonicalizing}, for details about the
22668 variables this macro sets.
22670 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
22671 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
22672 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
22673 other macros (@pxref{Canonicalizing}).
22674 @end defmac
22676 @defmac AC_CHAR_UNSIGNED
22677 @acindex{CHAR_UNSIGNED}
22678 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
22679 @end defmac
22681 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
22682 @acindex{CHECK_TYPE}
22683 Autoconf, up to 2.13, used to provide this version of
22684 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
22685 it is a member of the @code{CHECK} clan, it does
22686 more than just checking.  Secondly, missing types are defined
22687 using @code{#define}, not @code{typedef}, and this can lead to
22688 problems in the case of pointer types.
22690 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
22691 @ref{Generic Types}, for the description of the current macro.
22693 If the type @var{type} is not defined, define it to be the C (or C++)
22694 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
22696 This macro is equivalent to:
22698 @example
22699 AC_CHECK_TYPE([@var{type}], [],
22700   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
22701      [Define to `@var{default}'
22702       if <sys/types.h> does not define.])])
22703 @end example
22705 In order to keep backward compatibility, the two versions of
22706 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
22708 @enumerate
22709 @item
22710 If there are three or four arguments, the modern version is used.
22712 @item
22713 If the second argument appears to be a C or C++ type, then the
22714 obsolete version is used.  This happens if the argument is a C or C++
22715 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
22716 followed by one of @samp{[(* } and then by a string of zero or more
22717 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
22719 @item
22720 If the second argument is spelled with the alphabet of valid C and C++
22721 types, the user is warned and the modern version is used.
22723 @item
22724 Otherwise, the modern version is used.
22725 @end enumerate
22727 @noindent
22728 You are encouraged either to use a valid builtin type, or to use the
22729 equivalent modern code (see above), or better yet, to use
22730 @code{AC_CHECK_TYPES} together with
22732 @example
22733 #ifndef HAVE_LOFF_T
22734 typedef loff_t off_t;
22735 #endif
22736 @end example
22737 @end defmac
22738 @c end of AC_CHECK_TYPE
22740 @defmac AC_CHECKING (@var{feature-description})
22741 @acindex{CHECKING}
22742 Same as
22744 @example
22745 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
22746 @end example
22748 @noindent
22749 @xref{AC_MSG_NOTICE}.
22750 @end defmac
22752 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
22753   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
22754 @acindex{COMPILE_CHECK}
22755 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
22756 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
22757 addition that it prints @samp{checking for @var{echo-text}} to the
22758 standard output first, if @var{echo-text} is non-empty.  Use
22759 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
22760 messages (@pxref{Printing Messages}).
22761 @end defmac
22763 @defmac AC_CONST
22764 @acindex{CONST}
22765 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
22766 @end defmac
22768 @defmac AC_CROSS_CHECK
22769 @acindex{CROSS_CHECK}
22770 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
22771 @code{:-)}.
22772 @end defmac
22774 @defmac AC_CYGWIN
22775 @acindex{CYGWIN}
22776 @evindex CYGWIN
22777 Check for the Cygwin environment in which case the shell variable
22778 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
22779 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
22780 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
22782 @example
22783 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
22784 case $host_os in
22785   *cygwin* ) CYGWIN=yes;;
22786          * ) CYGWIN=no;;
22787 esac
22788 @end example
22790 Beware that the variable @env{CYGWIN} has a special meaning when
22791 running Cygwin, and should not be changed.  That's yet another reason
22792 not to use this macro.
22793 @end defmac
22795 @defmac AC_DECL_SYS_SIGLIST
22796 @acindex{DECL_SYS_SIGLIST}
22797 @cvindex SYS_SIGLIST_DECLARED
22798 Same as:
22800 @example
22801 AC_CHECK_DECLS([sys_siglist], [], [],
22802 [#include <signal.h>
22803 /* NetBSD declares sys_siglist in unistd.h.  */
22804 #ifdef HAVE_UNISTD_H
22805 # include <unistd.h>
22806 #endif
22808 @end example
22810 @noindent
22811 @xref{AC_CHECK_DECLS}.
22812 @end defmac
22814 @defmac AC_DECL_YYTEXT
22815 @acindex{DECL_YYTEXT}
22816 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
22817 @end defmac
22819 @defmac AC_DIR_HEADER
22820 @acindex{DIR_HEADER}
22821 @cvindex DIRENT
22822 @cvindex SYSNDIR
22823 @cvindex SYSDIR
22824 @cvindex NDIR
22825 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
22826 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
22827 (@pxref{AC_HEADER_DIRENT}),
22828 but defines a different set of C preprocessor macros to indicate which
22829 header file is found:
22831 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
22832 @item Header            @tab Old Symbol     @tab New Symbol
22833 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
22834 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
22835 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
22836 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
22837 @end multitable
22838 @end defmac
22840 @defmac AC_DYNIX_SEQ
22841 @acindex{DYNIX_SEQ}
22842 If on DYNIX/ptx, add @option{-lseq} to output variable
22843 @code{LIBS}.  This macro used to be defined as
22845 @example
22846 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
22847 @end example
22849 @noindent
22850 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
22851 @end defmac
22853 @defmac AC_EXEEXT
22854 @acindex{EXEEXT}
22855 @ovindex EXEEXT
22856 Defined the output variable @code{EXEEXT} based on the output of the
22857 compiler, which is now done automatically.  Typically set to empty
22858 string if Posix and @samp{.exe} if a DOS variant.
22859 @end defmac
22861 @defmac AC_EMXOS2
22862 @acindex{EMXOS2}
22863 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
22864 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
22865 check the nature of the host is using @code{AC_CANONICAL_HOST}
22866 (@pxref{Canonicalizing}).
22867 @end defmac
22869 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
22870   @ovar{action-if-not-given})
22871 @acindex{ENABLE}
22872 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
22873 support providing a help string (@pxref{AC_ARG_ENABLE}).
22874 @end defmac
22876 @defmac AC_ERROR
22877 @acindex{ERROR}
22878 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
22879 @end defmac
22881 @defmac AC_FIND_X
22882 @acindex{FIND_X}
22883 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
22884 @end defmac
22886 @defmac AC_FIND_XTRA
22887 @acindex{FIND_XTRA}
22888 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
22889 @end defmac
22891 @defmac AC_FOREACH
22892 @acindex{FOREACH}
22893 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
22894 @end defmac
22896 @defmac AC_FUNC_CHECK
22897 @acindex{FUNC_CHECK}
22898 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
22899 @end defmac
22901 @anchor{AC_FUNC_SETVBUF_REVERSED}
22902 @defmac AC_FUNC_SETVBUF_REVERSED
22903 @acindex{FUNC_SETVBUF_REVERSED}
22904 @cvindex SETVBUF_REVERSED
22905 @c @fuindex setvbuf
22906 @prindex @code{setvbuf}
22907 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
22908 the buffering type as its second argument and the buffer pointer as the
22909 third, instead of the other way around, and defined
22910 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
22911 were those based on SVR2, which became obsolete in 1987, and the macro
22912 is no longer needed.
22913 @end defmac
22915 @defmac AC_FUNC_WAIT3
22916 @acindex{FUNC_WAIT3}
22917 @cvindex HAVE_WAIT3
22918 @c @fuindex wait3
22919 @prindex @code{wait3}
22920 If @code{wait3} is found and fills in the contents of its third argument
22921 (a @samp{struct rusage *}), which HP-UX does not do, define
22922 @code{HAVE_WAIT3}.
22924 These days portable programs should use @code{waitpid}, not
22925 @code{wait3}, as @code{wait3} has been removed from Posix.
22926 @end defmac
22928 @defmac AC_GCC_TRADITIONAL
22929 @acindex{GCC_TRADITIONAL}
22930 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
22931 @end defmac
22933 @defmac AC_GETGROUPS_T
22934 @acindex{GETGROUPS_T}
22935 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
22936 @end defmac
22938 @defmac AC_GETLOADAVG
22939 @acindex{GETLOADAVG}
22940 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
22941 @end defmac
22943 @defmac AC_GNU_SOURCE
22944 @acindex{GNU_SOURCE}
22945 @cvindex _GNU_SOURCE
22946 This macro is a platform-specific subset of
22947 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
22948 @end defmac
22950 @defmac AC_HAVE_FUNCS
22951 @acindex{HAVE_FUNCS}
22952 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
22953 @end defmac
22955 @defmac AC_HAVE_HEADERS
22956 @acindex{HAVE_HEADERS}
22957 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
22958 @end defmac
22960 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
22961   @ovar{action-if-not-found}, @ovar{other-libraries})
22962 @acindex{HAVE_LIBRARY}
22963 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
22964 @var{function} argument of @code{main}.  In addition, @var{library} can
22965 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
22966 all of those cases, the compiler is passed @option{-lfoo}.  However,
22967 @var{library} cannot be a shell variable; it must be a literal name.
22968 @xref{AC_CHECK_LIB}.
22969 @end defmac
22971 @defmac AC_HAVE_POUNDBANG
22972 @acindex{HAVE_POUNDBANG}
22973 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
22974 @end defmac
22976 @defmac AC_HEADER_CHECK
22977 @acindex{HEADER_CHECK}
22978 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
22979 @end defmac
22981 @defmac AC_HEADER_EGREP
22982 @acindex{HEADER_EGREP}
22983 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
22984 @end defmac
22986 @defmac AC_HELP_STRING
22987 @acindex{HELP_STRING}
22988 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
22989 @end defmac
22991 @defmac AC_INIT (@var{unique-file-in-source-dir})
22992 @acindex{INIT}
22993 Formerly @code{AC_INIT} used to have a single argument, and was
22994 equivalent to:
22996 @example
22997 AC_INIT
22998 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
22999 @end example
23000 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23001 @end defmac
23003 @defmac AC_INLINE
23004 @acindex{INLINE}
23005 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23006 @end defmac
23008 @defmac AC_INT_16_BITS
23009 @acindex{INT_16_BITS}
23010 @cvindex INT_16_BITS
23011 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23012 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23013 @end defmac
23015 @defmac AC_IRIX_SUN
23016 @acindex{IRIX_SUN}
23017 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23018 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23019 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23020 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23021 getpwnam)}.  Up to Autoconf 2.13, it used to be
23023 @example
23024 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23025 @end example
23027 @noindent
23028 now it is defined as
23030 @example
23031 AC_FUNC_GETMNTENT
23032 AC_CHECK_LIB([sun], [getpwnam])
23033 @end example
23035 @noindent
23036 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23037 @end defmac
23039 @defmac AC_ISC_POSIX
23040 @acindex{ISC_POSIX}
23041 @ovindex LIBS
23042 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23043 necessary for Posix facilities.  Sun dropped support for the obsolete
23044 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23045 need not use this macro.  It is implemented as
23046 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23047 @end defmac
23049 @defmac AC_LANG_C
23050 @acindex{LANG_C}
23051 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23052 @end defmac
23054 @defmac AC_LANG_CPLUSPLUS
23055 @acindex{LANG_CPLUSPLUS}
23056 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23057 @end defmac
23059 @defmac AC_LANG_FORTRAN77
23060 @acindex{LANG_FORTRAN77}
23061 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23062 @end defmac
23064 @defmac AC_LANG_RESTORE
23065 @acindex{LANG_RESTORE}
23066 Select the @var{language} that is saved on the top of the stack, as set
23067 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23068 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23069 preferred way to change languages.
23070 @end defmac
23072 @defmac AC_LANG_SAVE
23073 @acindex{LANG_SAVE}
23074 Remember the current language (as set by @code{AC_LANG}) on a stack.
23075 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23076 (@pxref{AC_LANG_PUSH}).
23077 @end defmac
23079 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23080 @acindex{LINK_FILES}
23081 This is an obsolete version of @code{AC_CONFIG_LINKS}
23082 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23084 @example
23085 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23086               host.h            object.h)
23087 @end example
23089 @noindent
23092 @example
23093 AC_CONFIG_LINKS([host.h:config/$machine.h
23094                 object.h:config/$obj_format.h])
23095 @end example
23096 @end defmac
23098 @defmac AC_LN_S
23099 @acindex{LN_S}
23100 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23101 @end defmac
23103 @defmac AC_LONG_64_BITS
23104 @acindex{LONG_64_BITS}
23105 @cvindex LONG_64_BITS
23106 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23107 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23108 (@pxref{AC_CHECK_SIZEOF}).
23109 @end defmac
23111 @defmac AC_LONG_DOUBLE
23112 @acindex{LONG_DOUBLE}
23113 If the C compiler supports a working @code{long double} type with more
23114 range or precision than the @code{double} type, define
23115 @code{HAVE_LONG_DOUBLE}.
23117 You should use @code{AC_TYPE_LONG_DOUBLE} or
23118 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23119 @end defmac
23121 @defmac AC_LONG_FILE_NAMES
23122 @acindex{LONG_FILE_NAMES}
23123 Replaced by
23124 @example
23125 AC_SYS_LONG_FILE_NAMES
23126 @end example
23127 @noindent
23128 @xref{AC_SYS_LONG_FILE_NAMES}.
23129 @end defmac
23131 @defmac AC_MAJOR_HEADER
23132 @acindex{MAJOR_HEADER}
23133 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23134 @end defmac
23136 @defmac AC_MEMORY_H
23137 @acindex{MEMORY_H}
23138 @cvindex NEED_MEMORY_H
23139 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23140 defined in @file{memory.h}.  Today it is equivalent to
23141 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23142 your code to depend upon
23143 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
23144 Symbols}.
23145 @end defmac
23147 @defmac AC_MINGW32
23148 @acindex{MINGW32}
23149 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23150 environment and sets @code{MINGW32}.  Don't use this macro, the
23151 dignified means to check the nature of the host is using
23152 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23153 @end defmac
23155 @defmac AC_MINIX
23156 @acindex{MINIX}
23157 @cvindex _MINIX
23158 @cvindex _POSIX_SOURCE
23159 @cvindex _POSIX_1_SOURCE
23160 This macro is a platform-specific subset of
23161 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23162 @end defmac
23164 @defmac AC_MINUS_C_MINUS_O
23165 @acindex{MINUS_C_MINUS_O}
23166 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23167 @end defmac
23169 @defmac AC_MMAP
23170 @acindex{MMAP}
23171 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23172 @end defmac
23174 @defmac AC_MODE_T
23175 @acindex{MODE_T}
23176 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23177 @end defmac
23179 @defmac AC_OBJEXT
23180 @acindex{OBJEXT}
23181 @ovindex OBJEXT
23182 Defined the output variable @code{OBJEXT} based on the output of the
23183 compiler, after .c files have been excluded.  Typically set to @samp{o}
23184 if Posix, @samp{obj} if a DOS variant.
23185 Now the compiler checking macros handle
23186 this automatically.
23187 @end defmac
23189 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23190 @acindex{OBSOLETE}
23191 Make M4 print a message to the standard error output warning that
23192 @var{this-macro-name} is obsolete, and giving the file and line number
23193 where it was called.  @var{this-macro-name} should be the name of the
23194 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23195 it is printed at the end of the warning message; for example, it can be
23196 a suggestion for what to use instead of @var{this-macro-name}.
23198 For instance
23200 @example
23201 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23202 @end example
23204 @noindent
23205 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23206 services to the user (@pxref{AU_DEFUN}).
23207 @end defmac
23209 @defmac AC_OFF_T
23210 @acindex{OFF_T}
23211 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23212 @end defmac
23214 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23215 @acindex{OUTPUT}
23216 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23217 interface is equivalent to:
23219 @example
23220 @group
23221 AC_CONFIG_FILES(@var{file}@dots{})
23222 AC_CONFIG_COMMANDS([default],
23223                    @var{extra-cmds}, @var{init-cmds})
23224 AC_OUTPUT
23225 @end group
23226 @end example
23228 @noindent
23229 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23230 @end defmac
23232 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23233 @acindex{OUTPUT_COMMANDS}
23234 Specify additional shell commands to run at the end of
23235 @file{config.status}, and shell commands to initialize any variables
23236 from @command{configure}.  This macro may be called multiple times.  It is
23237 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23239 Here is an unrealistic example:
23241 @example
23242 fubar=27
23243 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23244                    [fubar=$fubar])
23245 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23246                    [echo init bit])
23247 @end example
23249 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23250 additional key, an important difference is that
23251 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23252 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23253 can safely be given macro calls as arguments:
23255 @example
23256 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23257 @end example
23259 @noindent
23260 Conversely, where one level of quoting was enough for literal strings
23261 with @code{AC_OUTPUT_COMMANDS}, you need two with
23262 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23264 @example
23265 @group
23266 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23267 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23268 @end group
23269 @end example
23270 @end defmac
23272 @defmac AC_PID_T
23273 @acindex{PID_T}
23274 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23275 @end defmac
23277 @defmac AC_PREFIX
23278 @acindex{PREFIX}
23279 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23280 @end defmac
23282 @defmac AC_PROGRAMS_CHECK
23283 @acindex{PROGRAMS_CHECK}
23284 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23285 @end defmac
23287 @defmac AC_PROGRAMS_PATH
23288 @acindex{PROGRAMS_PATH}
23289 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23290 @end defmac
23292 @defmac AC_PROGRAM_CHECK
23293 @acindex{PROGRAM_CHECK}
23294 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23295 @end defmac
23297 @defmac AC_PROGRAM_EGREP
23298 @acindex{PROGRAM_EGREP}
23299 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23300 @end defmac
23302 @defmac AC_PROGRAM_PATH
23303 @acindex{PROGRAM_PATH}
23304 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23305 @end defmac
23307 @defmac AC_REMOTE_TAPE
23308 @acindex{REMOTE_TAPE}
23309 Removed because of limited usefulness.
23310 @end defmac
23312 @defmac AC_RESTARTABLE_SYSCALLS
23313 @acindex{RESTARTABLE_SYSCALLS}
23314 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23315 these days portable programs should use @code{sigaction} with
23316 @code{SA_RESTART} if they want restartable system calls.  They should
23317 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23318 system call is restartable is a dynamic issue, not a configuration-time
23319 issue.
23320 @end defmac
23322 @defmac AC_RETSIGTYPE
23323 @acindex{RETSIGTYPE}
23324 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23325 is obsolete when assuming C89 or better.
23326 @end defmac
23328 @defmac AC_RSH
23329 @acindex{RSH}
23330 Removed because of limited usefulness.
23331 @end defmac
23333 @defmac AC_SCO_INTL
23334 @acindex{SCO_INTL}
23335 @ovindex LIBS
23336 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23337 macro used to do this:
23339 @example
23340 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23341 @end example
23343 @noindent
23344 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23345 @end defmac
23347 @defmac AC_SETVBUF_REVERSED
23348 @acindex{SETVBUF_REVERSED}
23349 Replaced by
23350 @example
23351 AC_FUNC_SETVBUF_REVERSED
23352 @end example
23353 @noindent
23354 @xref{AC_FUNC_SETVBUF_REVERSED}.
23355 @end defmac
23357 @defmac AC_SET_MAKE
23358 @acindex{SET_MAKE}
23359 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23360 @end defmac
23362 @defmac AC_SIZEOF_TYPE
23363 @acindex{SIZEOF_TYPE}
23364 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23365 @end defmac
23367 @defmac AC_SIZE_T
23368 @acindex{SIZE_T}
23369 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23370 @end defmac
23372 @defmac AC_STAT_MACROS_BROKEN
23373 @acindex{STAT_MACROS_BROKEN}
23374 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23375 @end defmac
23377 @defmac AC_STDC_HEADERS
23378 @acindex{STDC_HEADERS}
23379 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
23380 @end defmac
23382 @defmac AC_STRCOLL
23383 @acindex{STRCOLL}
23384 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23385 @end defmac
23387 @defmac AC_STRUCT_ST_BLKSIZE
23388 @acindex{STRUCT_ST_BLKSIZE}
23389 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23390 @cvindex HAVE_ST_BLKSIZE
23391 If @code{struct stat} contains an @code{st_blksize} member, define
23392 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23393 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23394 the future.  This macro is obsoleted, and should be replaced by
23396 @example
23397 AC_CHECK_MEMBERS([struct stat.st_blksize])
23398 @end example
23399 @noindent
23400 @xref{AC_CHECK_MEMBERS}.
23401 @end defmac
23403 @defmac AC_STRUCT_ST_RDEV
23404 @acindex{STRUCT_ST_RDEV}
23405 @cvindex HAVE_ST_RDEV
23406 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23407 If @code{struct stat} contains an @code{st_rdev} member, define
23408 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23409 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23410 in the future.  Actually, even the new macro is obsolete and should be
23411 replaced by:
23412 @example
23413 AC_CHECK_MEMBERS([struct stat.st_rdev])
23414 @end example
23415 @noindent
23416 @xref{AC_CHECK_MEMBERS}.
23417 @end defmac
23419 @defmac AC_ST_BLKSIZE
23420 @acindex{ST_BLKSIZE}
23421 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23422 @end defmac
23424 @defmac AC_ST_BLOCKS
23425 @acindex{ST_BLOCKS}
23426 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
23427 @end defmac
23429 @defmac AC_ST_RDEV
23430 @acindex{ST_RDEV}
23431 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23432 @end defmac
23434 @defmac AC_SYS_RESTARTABLE_SYSCALLS
23435 @acindex{SYS_RESTARTABLE_SYSCALLS}
23436 @cvindex HAVE_RESTARTABLE_SYSCALLS
23437 If the system automatically restarts a system call that is interrupted
23438 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
23439 not check whether system calls are restarted in general---it checks whether a
23440 signal handler installed with @code{signal} (but not @code{sigaction})
23441 causes system calls to be restarted.  It does not check whether system calls
23442 can be restarted when interrupted by signals that have no handler.
23444 These days portable programs should use @code{sigaction} with
23445 @code{SA_RESTART} if they want restartable system calls.  They should
23446 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23447 system call is restartable is a dynamic issue, not a configuration-time
23448 issue.
23449 @end defmac
23451 @defmac AC_SYS_SIGLIST_DECLARED
23452 @acindex{SYS_SIGLIST_DECLARED}
23453 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
23454 name is obsolete, as the same functionality is now acheived via
23455 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
23456 @end defmac
23458 @defmac AC_TEST_CPP
23459 @acindex{TEST_CPP}
23460 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
23461 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
23462 @end defmac
23464 @defmac AC_TEST_PROGRAM
23465 @acindex{TEST_PROGRAM}
23466 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
23467 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
23468 @end defmac
23470 @defmac AC_TIMEZONE
23471 @acindex{TIMEZONE}
23472 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
23473 @end defmac
23475 @defmac AC_TIME_WITH_SYS_TIME
23476 @acindex{TIME_WITH_SYS_TIME}
23477 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
23478 @end defmac
23480 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
23481   @ovar{action-if-true}, @ovar{action-if-false})
23482 @acindex{TRY_COMPILE}
23483 Same as:
23485 @example
23486 AC_COMPILE_IFELSE(
23487   [AC_LANG_PROGRAM([[@var{includes}]],
23488      [[@var{function-body}]])],
23489   [@var{action-if-true}],
23490   [@var{action-if-false}])
23491 @end example
23493 @noindent
23494 @xref{Running the Compiler}.
23496 This macro double quotes both @var{includes} and @var{function-body}.
23498 For C and C++, @var{includes} is any @code{#include} statements needed
23499 by the code in @var{function-body} (@var{includes} is ignored if
23500 the currently selected language is Fortran or Fortran 77).  The compiler
23501 and compilation flags are determined by the current language
23502 (@pxref{Language Choice}).
23503 @end defmac
23505 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
23506 @acindex{TRY_CPP}
23507 Same as:
23509 @example
23510 AC_PREPROC_IFELSE(
23511   [AC_LANG_SOURCE([[@var{input}]])],
23512   [@var{action-if-true}],
23513   [@var{action-if-false}])
23514 @end example
23516 @noindent
23517 @xref{Running the Preprocessor}.
23519 This macro double quotes the @var{input}.
23520 @end defmac
23522 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
23523   @ovar{action-if-true}, @ovar{action-if-false})
23524 @acindex{TRY_LINK}
23525 Same as:
23527 @example
23528 AC_LINK_IFELSE(
23529   [AC_LANG_PROGRAM([[@var{includes}]],
23530      [[@var{function-body}]])],
23531   [@var{action-if-true}],
23532   [@var{action-if-false}])
23533 @end example
23535 @noindent
23536 @xref{Running the Compiler}.
23538 This macro double quotes both @var{includes} and @var{function-body}.
23540 Depending on the current language (@pxref{Language Choice}), create a
23541 test program to see whether a function whose body consists of
23542 @var{function-body} can be compiled and linked.  If the file compiles
23543 and links successfully, run shell commands @var{action-if-found},
23544 otherwise run @var{action-if-not-found}.
23546 This macro double quotes both @var{includes} and @var{function-body}.
23548 For C and C++, @var{includes} is any @code{#include} statements needed
23549 by the code in @var{function-body} (@var{includes} is ignored if
23550 the currently selected language is Fortran or Fortran 77).  The compiler
23551 and compilation flags are determined by the current language
23552 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
23553 @code{LIBS} are used for linking.
23554 @end defmac
23556 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
23557   @ovar{action-if-not-found})
23558 @acindex{TRY_LINK_FUNC}
23559 This macro is equivalent to
23560 @example
23561 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
23562   [@var{action-if-found}], [@var{action-if-not-found}])
23563 @end example
23564 @noindent
23565 @xref{AC_LINK_IFELSE}.
23566 @end defmac
23568 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
23569   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
23570 @acindex{TRY_RUN}
23571 Same as:
23573 @example
23574 AC_RUN_IFELSE(
23575   [AC_LANG_SOURCE([[@var{program}]])],
23576   [@var{action-if-true}],
23577   [@var{action-if-false}],
23578   [@var{action-if-cross-compiling}])
23579 @end example
23581 @noindent
23582 @xref{Runtime}.
23583 @end defmac
23585 @anchor{AC_TYPE_SIGNAL}
23586 @defmac AC_TYPE_SIGNAL
23587 @acindex{TYPE_SIGNAL}
23588 @cvindex RETSIGTYPE
23589 @hdrindex{signal.h}
23590 If @file{signal.h} declares @code{signal} as returning a pointer to a
23591 function returning @code{void}, define @code{RETSIGTYPE} to be
23592 @code{void}; otherwise, define it to be @code{int}.  These days, it is
23593 portable to assume C89, and that signal handlers return @code{void},
23594 without needing to use this macro or @code{RETSIGTYPE}.
23596 When targetting older K&R C, it is possible to define signal handlers as
23597 returning type @code{RETSIGTYPE}, and omit a return statement:
23599 @example
23600 @group
23601 RETSIGTYPE
23602 hup_handler ()
23604 @dots{}
23606 @end group
23607 @end example
23608 @end defmac
23610 @defmac AC_UID_T
23611 @acindex{UID_T}
23612 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
23613 @end defmac
23615 @defmac AC_UNISTD_H
23616 @acindex{UNISTD_H}
23617 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
23618 @end defmac
23620 @defmac AC_USG
23621 @acindex{USG}
23622 @cvindex USG
23623 Define @code{USG} if the BSD string functions are defined in
23624 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
23625 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
23626 @end defmac
23628 @defmac AC_UTIME_NULL
23629 @acindex{UTIME_NULL}
23630 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
23631 @end defmac
23633 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
23634 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
23635 If the cache file is inconsistent with the current host, target and
23636 build system types, it used to execute @var{cmd} or print a default
23637 error message.  This is now handled by default.
23638 @end defmac
23640 @defmac AC_VERBOSE (@var{result-description})
23641 @acindex{VERBOSE}
23642 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
23643 @end defmac
23645 @defmac AC_VFORK
23646 @acindex{VFORK}
23647 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
23648 @end defmac
23650 @defmac AC_VPRINTF
23651 @acindex{VPRINTF}
23652 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
23653 @end defmac
23655 @defmac AC_WAIT3
23656 @acindex{WAIT3}
23657 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
23658 portable programs should use @code{waitpid}, not @code{wait3}, as
23659 @code{wait3} has been removed from Posix.
23660 @end defmac
23662 @defmac AC_WARN
23663 @acindex{WARN}
23664 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
23665 @end defmac
23667 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
23668   @ovar{action-if-not-given})
23669 @acindex{WITH}
23670 This is an obsolete version of @code{AC_ARG_WITH} that does not
23671 support providing a help string (@pxref{AC_ARG_WITH}).
23672 @end defmac
23674 @defmac AC_WORDS_BIGENDIAN
23675 @acindex{WORDS_BIGENDIAN}
23676 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
23677 @end defmac
23679 @defmac AC_XENIX_DIR
23680 @acindex{XENIX_DIR}
23681 @ovindex LIBS
23682 This macro used to add @option{-lx} to output variable @code{LIBS} if on
23683 Xenix.  Also, if @file{dirent.h} is being checked for, added
23684 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
23685 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
23686 running XENIX on which you should not depend:
23688 @example
23689 AC_MSG_CHECKING([for Xenix])
23690 AC_EGREP_CPP([yes],
23691 [#if defined M_XENIX && !defined M_UNIX
23692   yes
23693 #endif],
23694              [AC_MSG_RESULT([yes]); XENIX=yes],
23695              [AC_MSG_RESULT([no]); XENIX=])
23696 @end example
23697 @noindent
23698 Don't use this macro, the dignified means to check the nature of the
23699 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23700 @end defmac
23702 @defmac AC_YYTEXT_POINTER
23703 @acindex{YYTEXT_POINTER}
23704 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
23705 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23706 @end defmac
23708 @node Autoconf 1
23709 @section Upgrading From Version 1
23710 @cindex Upgrading autoconf
23711 @cindex Autoconf upgrading
23713 Autoconf version 2 is mostly backward compatible with version 1.
23714 However, it introduces better ways to do some things, and doesn't
23715 support some of the ugly things in version 1.  So, depending on how
23716 sophisticated your @file{configure.ac} files are, you might have to do
23717 some manual work in order to upgrade to version 2.  This chapter points
23718 out some problems to watch for when upgrading.  Also, perhaps your
23719 @command{configure} scripts could benefit from some of the new features in
23720 version 2; the changes are summarized in the file @file{NEWS} in the
23721 Autoconf distribution.
23723 @menu
23724 * Changed File Names::          Files you might rename
23725 * Changed Makefiles::           New things to put in @file{Makefile.in}
23726 * Changed Macros::              Macro calls you might replace
23727 * Changed Results::             Changes in how to check test results
23728 * Changed Macro Writing::       Better ways to write your own macros
23729 @end menu
23731 @node Changed File Names
23732 @subsection Changed File Names
23734 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
23735 in a particular package's source directory), you must rename it to
23736 @file{acsite.m4}.  @xref{autoconf Invocation}.
23738 If you distribute @file{install.sh} with your package, rename it to
23739 @file{install-sh} so @command{make} builtin rules don't inadvertently
23740 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
23741 looks for the script under both names, but it is best to use the new name.
23743 If you were using @file{config.h.top}, @file{config.h.bot}, or
23744 @file{acconfig.h}, you still can, but you have less clutter if you
23745 use the @code{AH_} macros.  @xref{Autoheader Macros}.
23747 @node Changed Makefiles
23748 @subsection Changed Makefiles
23750 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
23751 your @file{Makefile.in} files, so they can take advantage of the values
23752 of those variables in the environment when @command{configure} is run.
23753 Doing this isn't necessary, but it's a convenience for users.
23755 Also add @samp{@@configure_input@@} in a comment to each input file for
23756 @code{AC_OUTPUT}, so that the output files contain a comment saying
23757 they were produced by @command{configure}.  Automatically selecting the
23758 right comment syntax for all the kinds of files that people call
23759 @code{AC_OUTPUT} on became too much work.
23761 Add @file{config.log} and @file{config.cache} to the list of files you
23762 remove in @code{distclean} targets.
23764 If you have the following in @file{Makefile.in}:
23766 @example
23767 prefix = /usr/local
23768 exec_prefix = $(prefix)
23769 @end example
23771 @noindent
23772 you must change it to:
23774 @example
23775 prefix = @@prefix@@
23776 exec_prefix = @@exec_prefix@@
23777 @end example
23779 @noindent
23780 The old behavior of replacing those variables without @samp{@@}
23781 characters around them has been removed.
23783 @node Changed Macros
23784 @subsection Changed Macros
23786 Many of the macros were renamed in Autoconf version 2.  You can still
23787 use the old names, but the new ones are clearer, and it's easier to find
23788 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
23789 new names for the old macros.  Use the @command{autoupdate} program to
23790 convert your @file{configure.ac} to using the new macro names.
23791 @xref{autoupdate Invocation}.
23793 Some macros have been superseded by similar ones that do the job better,
23794 but are not call-compatible.  If you get warnings about calling obsolete
23795 macros while running @command{autoconf}, you may safely ignore them, but
23796 your @command{configure} script generally works better if you follow
23797 the advice that is printed about what to replace the obsolete macros with.  In
23798 particular, the mechanism for reporting the results of tests has
23799 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
23800 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
23801 looks better if you switch to @code{AC_MSG_CHECKING} and
23802 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
23803 in conjunction with cache variables.  @xref{Caching Results}.
23807 @node Changed Results
23808 @subsection Changed Results
23810 If you were checking the results of previous tests by examining the
23811 shell variable @code{DEFS}, you need to switch to checking the values of
23812 the cache variables for those tests.  @code{DEFS} no longer exists while
23813 @command{configure} is running; it is only created when generating output
23814 files.  This difference from version 1 is because properly quoting the
23815 contents of that variable turned out to be too cumbersome and
23816 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
23817 Variable Names}.
23819 For example, here is a @file{configure.ac} fragment written for Autoconf
23820 version 1:
23822 @example
23823 AC_HAVE_FUNCS(syslog)
23824 case "$DEFS" in
23825 *-DHAVE_SYSLOG*) ;;
23826 *) # syslog is not in the default libraries.  See if it's in some other.
23827   saved_LIBS="$LIBS"
23828   for lib in bsd socket inet; do
23829     AC_CHECKING(for syslog in -l$lib)
23830     LIBS="-l$lib $saved_LIBS"
23831     AC_HAVE_FUNCS(syslog)
23832     case "$DEFS" in
23833     *-DHAVE_SYSLOG*) break ;;
23834     *) ;;
23835     esac
23836     LIBS="$saved_LIBS"
23837   done ;;
23838 esac
23839 @end example
23841 Here is a way to write it for version 2:
23843 @example
23844 AC_CHECK_FUNCS([syslog])
23845 if test "x$ac_cv_func_syslog" = xno; then
23846   # syslog is not in the default libraries.  See if it's in some other.
23847   for lib in bsd socket inet; do
23848     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
23849       LIBS="-l$lib $LIBS"; break])
23850   done
23852 @end example
23854 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
23855 backslashes before quotes, you need to remove them.  It now works
23856 predictably, and does not treat quotes (except back quotes) specially.
23857 @xref{Setting Output Variables}.
23859 All of the Boolean shell variables set by Autoconf macros now use
23860 @samp{yes} for the true value.  Most of them use @samp{no} for false,
23861 though for backward compatibility some use the empty string instead.  If
23862 you were relying on a shell variable being set to something like 1 or
23863 @samp{t} for true, you need to change your tests.
23865 @node Changed Macro Writing
23866 @subsection Changed Macro Writing
23868 When defining your own macros, you should now use @code{AC_DEFUN}
23869 instead of @code{define}.  @code{AC_DEFUN} automatically calls
23870 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
23871 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
23872 messages on the screen.  There's no actual harm in continuing to use the
23873 older way, but it's less convenient and attractive.  @xref{Macro
23874 Definitions}.
23876 You probably looked at the macros that came with Autoconf as a guide for
23877 how to do things.  It would be a good idea to take a look at the new
23878 versions of them, as the style is somewhat improved and they take
23879 advantage of some new features.
23881 If you were doing tricky things with undocumented Autoconf internals
23882 (macros, variables, diversions), check whether you need to change
23883 anything to account for changes that have been made.  Perhaps you can
23884 even use an officially supported technique in version 2 instead of
23885 kludging.  Or perhaps not.
23887 To speed up your locally written feature tests, add caching to them.
23888 See whether any of your tests are of general enough usefulness to
23889 encapsulate them into macros that you can share.
23892 @node Autoconf 2.13
23893 @section Upgrading From Version 2.13
23894 @cindex Upgrading autoconf
23895 @cindex Autoconf upgrading
23897 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
23898 suits this section@enddots{}
23900 @quotation
23901 Autoconf version 2.50 is mostly backward compatible with version 2.13.
23902 However, it introduces better ways to do some things, and doesn't
23903 support some of the ugly things in version 2.13.  So, depending on how
23904 sophisticated your @file{configure.ac} files are, you might have to do
23905 some manual work in order to upgrade to version 2.50.  This chapter
23906 points out some problems to watch for when upgrading.  Also, perhaps
23907 your @command{configure} scripts could benefit from some of the new
23908 features in version 2.50; the changes are summarized in the file
23909 @file{NEWS} in the Autoconf distribution.
23910 @end quotation
23912 @menu
23913 * Changed Quotation::           Broken code which used to work
23914 * New Macros::                  Interaction with foreign macros
23915 * Hosts and Cross-Compilation::  Bugward compatibility kludges
23916 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
23917 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
23918 @end menu
23920 @node Changed Quotation
23921 @subsection Changed Quotation
23923 The most important changes are invisible to you: the implementation of
23924 most macros have completely changed.  This allowed more factorization of
23925 the code, better error messages, a higher uniformity of the user's
23926 interface etc.  Unfortunately, as a side effect, some construct which
23927 used to (miraculously) work might break starting with Autoconf 2.50.
23928 The most common culprit is bad quotation.
23930 For instance, in the following example, the message is not properly
23931 quoted:
23933 @example
23934 AC_INIT
23935 AC_CHECK_HEADERS(foo.h, ,
23936   AC_MSG_ERROR(cannot find foo.h, bailing out))
23937 AC_OUTPUT
23938 @end example
23940 @noindent
23941 Autoconf 2.13 simply ignores it:
23943 @example
23944 $ @kbd{autoconf-2.13; ./configure --silent}
23945 creating cache ./config.cache
23946 configure: error: cannot find foo.h
23948 @end example
23950 @noindent
23951 while Autoconf 2.50 produces a broken @file{configure}:
23953 @example
23954 $ @kbd{autoconf-2.50; ./configure --silent}
23955 configure: error: cannot find foo.h
23956 ./configure: exit: bad non-numeric arg `bailing'
23957 ./configure: exit: bad non-numeric arg `bailing'
23959 @end example
23961 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
23962 too!
23964 @example
23965 AC_INIT([Example], [1.0], [bug-example@@example.org])
23966 AC_CHECK_HEADERS([foo.h], [],
23967   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
23968 AC_OUTPUT
23969 @end example
23971 Many many (and many more) Autoconf macros were lacking proper quotation,
23972 including no less than@dots{} @code{AC_DEFUN} itself!
23974 @example
23975 $ @kbd{cat configure.in}
23976 AC_DEFUN([AC_PROG_INSTALL],
23977 [# My own much better version
23979 AC_INIT
23980 AC_PROG_INSTALL
23981 AC_OUTPUT
23982 $ @kbd{autoconf-2.13}
23983 autoconf: Undefined macros:
23984 ***BUG in Autoconf--please report*** AC_FD_MSG
23985 ***BUG in Autoconf--please report*** AC_EPI
23986 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
23987 configure.in:5:AC_PROG_INSTALL
23988 $ @kbd{autoconf-2.50}
23990 @end example
23993 @node New Macros
23994 @subsection New Macros
23996 @cindex undefined macro
23997 @cindex @code{_m4_divert_diversion}
23999 While Autoconf was relatively dormant in the late 1990s, Automake
24000 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24001 in 2001, Autoconf provided
24002 versions of these macros, integrated in the @code{AC_} namespace,
24003 instead of @code{AM_}.  But in order to ease the upgrading via
24004 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24006 Unfortunately older versions of Automake (e.g., Automake 1.4)
24007 did not quote the names of these macros.
24008 Therefore, when @command{m4} finds something like
24009 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24010 @code{AM_TYPE_PTRDIFF_T} is
24011 expanded, replaced with its Autoconf definition.
24013 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24014 complains, in its own words:
24016 @example
24017 $ @kbd{cat configure.ac}
24018 AC_INIT([Example], [1.0], [bug-example@@example.org])
24019 AM_TYPE_PTRDIFF_T
24020 $ @kbd{aclocal-1.4}
24021 $ @kbd{autoconf}
24022 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24023 aclocal.m4:17: the top level
24024 autom4te: m4 failed with exit status: 1
24026 @end example
24028 Modern versions of Automake no longer define most of these
24029 macros, and properly quote the names of the remaining macros.
24030 If you must use an old Automake, do not depend upon macros from Automake
24031 as it is simply not its job
24032 to provide macros (but the one it requires itself):
24034 @example
24035 $ @kbd{cat configure.ac}
24036 AC_INIT([Example], [1.0], [bug-example@@example.org])
24037 AM_TYPE_PTRDIFF_T
24038 $ @kbd{rm aclocal.m4}
24039 $ @kbd{autoupdate}
24040 autoupdate: `configure.ac' is updated
24041 $ @kbd{cat configure.ac}
24042 AC_INIT([Example], [1.0], [bug-example@@example.org])
24043 AC_CHECK_TYPES([ptrdiff_t])
24044 $ @kbd{aclocal-1.4}
24045 $ @kbd{autoconf}
24047 @end example
24050 @node Hosts and Cross-Compilation
24051 @subsection Hosts and Cross-Compilation
24052 @cindex Cross compilation
24054 Based on the experience of compiler writers, and after long public
24055 debates, many aspects of the cross-compilation chain have changed:
24057 @itemize @minus
24058 @item
24059 the relationship between the build, host, and target architecture types,
24061 @item
24062 the command line interface for specifying them to @command{configure},
24064 @item
24065 the variables defined in @command{configure},
24067 @item
24068 the enabling of cross-compilation mode.
24069 @end itemize
24071 @sp 1
24073 The relationship between build, host, and target have been cleaned up:
24074 the chain of default is now simply: target defaults to host, host to
24075 build, and build to the result of @command{config.guess}.  Nevertheless,
24076 in order to ease the transition from 2.13 to 2.50, the following
24077 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24078 be completely disabled in a couple of releases (we cannot keep it, as it
24079 proves to cause more problems than it cures).
24081 They all default to the result of running @command{config.guess}, unless
24082 you specify either @option{--build} or @option{--host}.  In this case,
24083 the default becomes the system type you specified.  If you specify both,
24084 and they're different, @command{configure} enters cross compilation
24085 mode, so it doesn't run any tests that require execution.
24087 Hint: if you mean to override the result of @command{config.guess},
24088 prefer @option{--build} over @option{--host}.  In the future,
24089 @option{--host} will not override the name of the build system type.
24090 Whenever you specify @option{--host}, be sure to specify @option{--build}
24091 too.
24093 @sp 1
24095 For backward compatibility, @command{configure} accepts a system
24096 type as an option by itself.  Such an option overrides the
24097 defaults for build, host, and target system types.  The following
24098 configure statement configures a cross toolchain that runs on
24099 NetBSD/alpha but generates code for GNU Hurd/sparc,
24100 which is also the build platform.
24102 @example
24103 ./configure --host=alpha-netbsd sparc-gnu
24104 @end example
24106 @sp 1
24108 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24109 and @code{target} had a different semantics before and after the
24110 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24111 @option{--build} is strictly copied into @code{build_alias}, and is left
24112 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24113 set to the canonicalized build type.  To ease the transition, before,
24114 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24115 rely on this broken feature.
24117 For consistency with the backward compatibility scheme exposed above,
24118 when @option{--host} is specified but @option{--build} isn't, the build
24119 system is assumed to be the same as @option{--host}, and
24120 @samp{build_alias} is set to that value.  Eventually, this
24121 historically incorrect behavior will go away.
24123 @sp 1
24125 The former scheme to enable cross-compilation proved to cause more harm
24126 than good, in particular, it used to be triggered too easily, leaving
24127 regular end users puzzled in front of cryptic error messages.
24128 @command{configure} could even enter cross-compilation mode only
24129 because the compiler was not functional.  This is mainly because
24130 @command{configure} used to try to detect cross-compilation, instead of
24131 waiting for an explicit flag from the user.
24133 Now, @command{configure} enters cross-compilation mode if and only if
24134 @option{--host} is passed.
24136 That's the short documentation.  To ease the transition between 2.13 and
24137 its successors, a more complicated scheme is implemented.  @emph{Do not
24138 rely on the following}, as it will be removed in the near future.
24140 If you specify @option{--host}, but not @option{--build}, when
24141 @command{configure} performs the first compiler test it tries to run
24142 an executable produced by the compiler.  If the execution fails, it
24143 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24144 the compiler test is performed, it may be too late to modify the
24145 build-system type: other tests may have already been performed.
24146 Therefore, whenever you specify @option{--host}, be sure to specify
24147 @option{--build} too.
24149 @example
24150 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24151 @end example
24153 @noindent
24154 enters cross-compilation mode.  The former interface, which
24155 consisted in setting the compiler to a cross-compiler without informing
24156 @command{configure} is obsolete.  For instance, @command{configure}
24157 fails if it can't run the code generated by the specified compiler if you
24158 configure as follows:
24160 @example
24161 ./configure CC=m68k-coff-gcc
24162 @end example
24165 @node AC_LIBOBJ vs LIBOBJS
24166 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24168 Up to Autoconf 2.13, the replacement of functions was triggered via the
24169 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24170 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24171 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24173 This change is mandated by the unification of the GNU Build System
24174 components.  In particular, the various fragile techniques used to parse
24175 a @file{configure.ac} are all replaced with the use of traces.  As a
24176 consequence, any action must be traceable, which obsoletes critical
24177 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24178 and it can even be handled gracefully (read, ``without your having to
24179 change something'').
24181 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24182 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24184 @sp 1
24186 As for function replacement, the fix is immediate: use
24187 @code{AC_LIBOBJ}.  For instance:
24189 @example
24190 LIBOBJS="$LIBOBJS fnmatch.o"
24191 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24192 @end example
24194 @noindent
24195 should be replaced with:
24197 @example
24198 AC_LIBOBJ([fnmatch])
24199 AC_LIBOBJ([malloc])
24200 @end example
24202 @sp 1
24204 @ovindex LIBOBJDIR
24205 When used with Automake 1.10 or newer, a suitable value for
24206 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24207 can be referenced from any @file{Makefile.am}.  Even without Automake,
24208 arranging for @code{LIBOBJDIR} to be set correctly enables
24209 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24210 The @code{LIBOBJDIR} feature is experimental.
24213 @node AC_ACT_IFELSE vs AC_TRY_ACT
24214 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24215 @c the anchor keeps the old node name, to try to avoid breaking links
24216 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24218 @acindex{@var{ACT}_IFELSE}
24219 @acindex{TRY_@var{ACT}}
24220 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24221 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24222 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24223 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24224 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24225 @code{AC_TRY_RUN}.  The motivations where:
24226 @itemize @minus
24227 @item
24228 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24229 quoting their arguments;
24231 @item
24232 the combinatoric explosion is solved by decomposing on the one hand the
24233 generation of sources, and on the other hand executing the program;
24235 @item
24236 this scheme helps supporting more languages than plain C and C++.
24237 @end itemize
24239 In addition to the change of syntax, the philosophy has changed too:
24240 while emphasis was put on speed at the expense of accuracy, today's
24241 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24242 expense of speed.
24245 As a perfect example of what is @emph{not} to be done, here is how to
24246 find out whether a header file contains a particular declaration, such
24247 as a typedef, a structure, a structure member, or a function.  Use
24248 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24249 header file; on some systems the symbol might be defined in another
24250 header file that the file you are checking includes.
24252 As a (bad) example, here is how you should not check for C preprocessor
24253 symbols, either defined by header files or predefined by the C
24254 preprocessor: using @code{AC_EGREP_CPP}:
24256 @example
24257 @group
24258 AC_EGREP_CPP(yes,
24259 [#ifdef _AIX
24260   yes
24261 #endif
24262 ], is_aix=yes, is_aix=no)
24263 @end group
24264 @end example
24266 The above example, properly written would (i) use
24267 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24269 @example
24270 @group
24271 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24272 [[#ifndef _AIX
24273  error: This isn't AIX!
24274 #endif
24275 ]])],
24276                    [is_aix=yes],
24277                    [is_aix=no])
24278 @end group
24279 @end example
24282 @c ============================= Generating Test Suites with Autotest
24284 @node Using Autotest
24285 @chapter Generating Test Suites with Autotest
24287 @cindex Autotest
24289 @display
24290 @strong{N.B.: This section describes a feature which is still
24291 stabilizing.  Although we believe that Autotest is useful as-is, this
24292 documentation describes an interface which might change in the future:
24293 do not depend upon Autotest without subscribing to the Autoconf mailing
24294 lists.}
24295 @end display
24297 It is paradoxical that portable projects depend on nonportable tools
24298 to run their test suite.  Autoconf by itself is the paragon of this
24299 problem: although it aims at perfectly portability, up to 2.13 its
24300 test suite was using DejaGNU, a rich and complex testing
24301 framework, but which is far from being standard on Posix systems.
24302 Worse yet, it was likely to be missing on the most fragile platforms,
24303 the very platforms that are most likely to torture Autoconf and
24304 exhibit deficiencies.
24306 To circumvent this problem, many package maintainers have developed their
24307 own testing framework, based on simple shell scripts whose sole outputs
24308 are exit status values describing whether the test succeeded.  Most of
24309 these tests share common patterns, and this can result in lots of
24310 duplicated code and tedious maintenance.
24312 Following exactly the same reasoning that yielded to the inception of
24313 Autoconf, Autotest provides a test suite generation framework, based on
24314 M4 macros building a portable shell script.  The suite itself is
24315 equipped with automatic logging and tracing facilities which greatly
24316 diminish the interaction with bug reporters, and simple timing reports.
24318 Autoconf itself has been using Autotest for years, and we do attest that
24319 it has considerably improved the strength of the test suite and the
24320 quality of bug reports.  Other projects are known to use some generation
24321 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
24322 them with different needs, and this usage has validated Autotest as a general
24323 testing framework.
24325 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24326 interactive tool testing, which is probably its main limitation.
24328 @menu
24329 * Using an Autotest Test Suite::  Autotest and the user
24330 * Writing Testsuites::          Autotest macros
24331 * testsuite Invocation::        Running @command{testsuite} scripts
24332 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24333 @end menu
24335 @node Using an Autotest Test Suite
24336 @section Using an Autotest Test Suite
24338 @menu
24339 * testsuite Scripts::           The concepts of Autotest
24340 * Autotest Logs::               Their contents
24341 @end menu
24343 @node testsuite Scripts
24344 @subsection @command{testsuite} Scripts
24346 @cindex @command{testsuite}
24348 Generating testing or validation suites using Autotest is rather easy.
24349 The whole validation suite is held in a file to be processed through
24350 @command{autom4te}, itself using GNU M4 under the hood, to
24351 produce a stand-alone Bourne shell script which then gets distributed.
24352 Neither @command{autom4te} nor GNU M4 are needed at
24353 the installer's end.
24355 @cindex test group
24356 Each test of the validation suite should be part of some test group.  A
24357 @dfn{test group} is a sequence of interwoven tests that ought to be
24358 executed together, usually because one test in the group creates data
24359 files that a later test in the same group needs to read.  Complex test
24360 groups make later debugging more tedious.  It is much better to
24361 keep only a few tests per test group.  Ideally there is only one test
24362 per test group.
24364 For all but the simplest packages, some file such as @file{testsuite.at}
24365 does not fully hold all test sources, as these are often easier to
24366 maintain in separate files.  Each of these separate files holds a single
24367 test group, or a sequence of test groups all addressing some common
24368 functionality in the package.  In such cases, @file{testsuite.at}
24369 merely initializes the validation suite, and sometimes does elementary
24370 health checking, before listing include statements for all other test
24371 files.  The special file @file{package.m4}, containing the
24372 identification of the package, is automatically included if found.
24374 A convenient alternative consists in moving all the global issues
24375 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24376 invocation) into the file @code{local.at}, and making
24377 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24378 suites.  In such case, generating the whole test suite or pieces of it
24379 is only a matter of choosing the @command{autom4te} command line
24380 arguments.
24382 The validation scripts that Autotest produces are by convention called
24383 @command{testsuite}.  When run, @command{testsuite} executes each test
24384 group in turn, producing only one summary line per test to say if that
24385 particular test succeeded or failed.  At end of all tests, summarizing
24386 counters get printed.  One debugging directory is left for each test
24387 group which failed, if any: such directories are named
24388 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24389 the test group, and they include:
24391 @itemize @bullet
24392 @item a debugging script named @file{run} which reruns the test in
24393 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24394 of debugging scripts has the purpose of easing the chase for bugs.
24396 @item all the files created with @code{AT_DATA}
24398 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24400 @item a log of the run, named @file{testsuite.log}
24401 @end itemize
24403 In the ideal situation, none of the tests fail, and consequently no
24404 debugging directory is left behind for validation.
24406 It often happens in practice that individual tests in the validation
24407 suite need to get information coming out of the configuration process.
24408 Some of this information, common for all validation suites, is provided
24409 through the file @file{atconfig}, automatically created by
24410 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
24411 testing environment specifically needs, you might prepare an optional
24412 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24413 The configuration process produces @file{atconfig} and @file{atlocal}
24414 out of these two input files, and these two produced files are
24415 automatically read by the @file{testsuite} script.
24417 Here is a diagram showing the relationship between files.
24419 @noindent
24420 Files used in preparing a software package for distribution:
24422 @example
24423                 [package.m4] -->.
24424                                  \
24425 subfile-1.at ->.  [local.at] ---->+
24426     ...         \                  \
24427 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
24428     ...         /
24429 subfile-n.at ->'
24430 @end example
24432 @noindent
24433 Files used in configuring a software package:
24435 @example
24436                                      .--> atconfig
24437                                     /
24438 [atlocal.in] -->  config.status* --<
24439                                     \
24440                                      `--> [atlocal]
24441 @end example
24443 @noindent
24444 Files created during test suite execution:
24446 @example
24447 atconfig -->.                    .--> testsuite.log
24448              \                  /
24449               >-- testsuite* --<
24450              /                  \
24451 [atlocal] ->'                    `--> [testsuite.dir]
24452 @end example
24455 @node Autotest Logs
24456 @subsection Autotest Logs
24458 When run, the test suite creates a log file named after itself, e.g., a
24459 test suite named @command{testsuite} creates @file{testsuite.log}.  It
24460 contains a lot of information, usually more than maintainers actually
24461 need, but therefore most of the time it contains all that is needed:
24463 @table @asis
24464 @item command line arguments
24465 A bad but unfortunately widespread habit consists of
24466 setting environment variables before the command, such as in
24467 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
24468 know this change, hence (i) it cannot report it to you, and (ii)
24469 it cannot preserve the value of @code{CC} for subsequent runs.
24470 Autoconf faced exactly the same problem, and solved it by asking
24471 users to pass the variable definitions as command line arguments.
24472 Autotest requires this rule, too, but has no means to enforce it; the log
24473 then contains a trace of the variables that were changed by the user.
24475 @item @file{ChangeLog} excerpts
24476 The topmost lines of all the @file{ChangeLog} files found in the source
24477 hierarchy.  This is especially useful when bugs are reported against
24478 development versions of the package, since the version string does not
24479 provide sufficient information to know the exact state of the sources
24480 the user compiled.  Of course, this relies on the use of a
24481 @file{ChangeLog}.
24483 @item build machine
24484 Running a test suite in a cross-compile environment is not an easy task,
24485 since it would mean having the test suite run on a machine @var{build},
24486 while running programs on a machine @var{host}.  It is much simpler to
24487 run both the test suite and the programs on @var{host}, but then, from
24488 the point of view of the test suite, there remains a single environment,
24489 @var{host} = @var{build}.  The log contains relevant information on the
24490 state of the @var{build} machine, including some important environment
24491 variables.
24492 @c FIXME: How about having an M4sh macro to say `hey, log the value
24493 @c of `@dots{}'?  This would help both Autoconf and Autotest.
24495 @item tested programs
24496 The absolute file name and answers to @option{--version} of the tested
24497 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
24499 @item configuration log
24500 The contents of @file{config.log}, as created by @command{configure},
24501 are appended.  It contains the configuration flags and a detailed report
24502 on the configuration itself.
24503 @end table
24506 @node Writing Testsuites
24507 @section Writing @file{testsuite.at}
24509 The @file{testsuite.at} is a Bourne shell script making use of special
24510 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
24511 its beginning followed by one call to @code{m4_include} per source file
24512 for tests.  Each such included file, or the remainder of
24513 @file{testsuite.at} if include files are not used, contain a sequence of
24514 test groups.  Each test group begins with a call to @code{AT_SETUP},
24515 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
24516 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
24517 groups can be categorized by a call to @code{AT_BANNER}.
24519 All of the public Autotest macros have all-uppercase names in the
24520 namespace @samp{^AT_} to prevent them from accidentally conflicting with
24521 other text; Autoconf also reserves the namespace @samp{^_AT_} for
24522 internal macros.  All shell variables used in the testsuite for internal
24523 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
24524 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
24525 makes use of the file system namespace @samp{^at-}.
24527 Since Autoconf is built on top of M4sugar (@pxref{Programming in
24528 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
24529 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
24530 @emph{should not use} the namespace of a package that does not own the
24531 macro or shell code you are writing.
24533 @defmac AT_INIT (@ovar{name})
24534 @atindex{INIT}
24535 @c FIXME: Not clear, plus duplication of the information.
24536 Initialize Autotest.  Giving a @var{name} to the test suite is
24537 encouraged if your package includes several test suites.  Before this
24538 macro is called, @code{AT_PACKAGE_STRING} and
24539 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
24540 information about the testsuite to the user.  Typically, these macros
24541 are provided by a file @file{package.m4} built by @command{make}
24542 (@pxref{Making testsuite Scripts}), in order to inherit the package
24543 name, version, and bug reporting address from @file{configure.ac}.
24544 @end defmac
24546 @defmac AT_COPYRIGHT (@var{copyright-notice})
24547 @atindex{COPYRIGHT}
24548 @cindex Copyright Notice
24549 State that, in addition to the Free Software Foundation's copyright on
24550 the Autotest macros, parts of your test suite are covered by
24551 @var{copyright-notice}.
24553 The @var{copyright-notice} shows up in both the head of
24554 @command{testsuite} and in @samp{testsuite --version}.
24555 @end defmac
24557 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
24558   @ovar{action-if-given}, @ovar{action-if-not-given})
24559 @atindex{ARG_OPTION}
24560 @vrindex at_arg_@var{option}
24561 Accept options from the space-separated list @var{options}, a list that
24562 has leading dashes removed from the options.  Long options will be
24563 prefixed with @samp{--}, single-character options with @samp{-}.  The
24564 first word in this list is the primary @var{option}, any others are
24565 assumed to be short-hand aliases.  The variable associated with it
24566 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
24567 with underscores.
24569 If the user passes @option{--@var{option}} to the @command{testsuite},
24570 the variable will be set to @samp{:}.  If the user does not pass the
24571 option, or passes @option{--no-@var{option}}, then the variable will be
24572 set to @samp{false}.
24574 @vrindex at_optarg
24575 @vrindex at_optarg_@var{option}
24576 @var{action-if-given} is run each time the option is encountered; here,
24577 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
24578 appropriate.  @code{at_optarg} is actually just a copy of
24579 @code{at_arg_@var{option}}.
24581 @var{action-if-not-given} will be run once after option parsing is
24582 complete and if no option from @var{options} was used.
24584 @var{help-text} is added to the end of the list of options shown in
24585 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24587 It it recommended that you use a package-specific prefix to @var{options}
24588 names in order to avoid clashes with future Autotest built-in options.
24589 @end defmac
24591 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
24592   @ovar{action-if-given}, @ovar{action-if-not-given})
24593 @atindex{ARG_OPTION_ARG}
24594 @vrindex at_arg_@var{option}
24595 Accept options with arguments from the space-separated list
24596 @var{options}, a list that has leading dashes removed from the options.
24597 Long options will be prefixed with @samp{--}, single-character options
24598 with @samp{-}.  The first word in this list is the primary @var{option},
24599 any others are assumed to be short-hand aliases.  The variable associated
24600 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
24601 replaced with underscores.
24603 If the user passes @option{--@var{option}=@var{arg}} or
24604 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
24605 variable will be set to @samp{@var{arg}}.
24607 @vrindex at_optarg
24608 @var{action-if-given} is run each time the option is encountered; here,
24609 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
24610 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
24612 @var{action-if-not-given} will be run once after option parsing is
24613 complete and if no option from @var{options} was used.
24615 @var{help-text} is added to the end of the list of options shown in
24616 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
24618 It it recommended that you use a package-specific prefix to @var{options}
24619 names in order to avoid clashes with future Autotest built-in options.
24620 @end defmac
24622 @defmac AT_COLOR_TESTS
24623 @atindex{COLOR_TESTS}
24624 Enable colored test results by default when the output is connected to
24625 a terminal.
24626 @end defmac
24628 @defmac AT_TESTED (@var{executables})
24629 @atindex{TESTED}
24630 Log the file name and answer to @option{--version} of each program in
24631 space-separated list @var{executables}.  Several invocations register
24632 new executables, in other words, don't fear registering one program
24633 several times.
24635 Autotest test suites rely on @env{PATH} to find the tested program.
24636 This avoids the need to generate absolute names of the various tools, and
24637 makes it possible to test installed programs.  Therefore, knowing which
24638 programs are being exercised is crucial to understanding problems in
24639 the test suite itself, or its occasional misuses.  It is a good idea to
24640 also subscribe foreign programs you depend upon, to avoid incompatible
24641 diagnostics.
24642 @end defmac
24644 @sp 1
24646 @defmac AT_BANNER (@var{test-category-name})
24647 @atindex{BANNER}
24648 This macro identifies the start of a category of related test groups.
24649 When the resulting @file{testsuite} is invoked with more than one test
24650 group to run, its output will include a banner containing
24651 @var{test-category-name} prior to any tests run from that category.  The
24652 banner should be no more than about 40 or 50 characters.  A blank banner
24653 indicates uncategorized tests; an empty line will be inserted after
24654 tests from an earlier category, effectively ending that category.
24655 @end defmac
24657 @defmac AT_SETUP (@var{test-group-name})
24658 @atindex{SETUP}
24659 This macro starts a group of related tests, all to be executed in the
24660 same subshell.  It accepts a single argument, which holds a few words
24661 (no more than about 30 or 40 characters) quickly describing the purpose
24662 of the test group being started.  @var{test-group-name} must not expand
24663 to unbalanced quotes, although quadrigraphs can be used.
24664 @end defmac
24666 @defmac AT_KEYWORDS (@var{keywords})
24667 @atindex{KEYWORDS}
24668 Associate the space-separated list of @var{keywords} to the enclosing
24669 test group.  This makes it possible to run ``slices'' of the test suite.
24670 For instance, if some of your test groups exercise some @samp{foo}
24671 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
24672 @samp{./testsuite -k foo} to run exclusively these test groups.  The
24673 @var{test-group-name} of the test group is automatically recorded to
24674 @code{AT_KEYWORDS}.
24676 Several invocations within a test group accumulate new keywords.  In
24677 other words, don't fear registering the same keyword several times in a
24678 test group.
24679 @end defmac
24681 @defmac AT_CAPTURE_FILE (@var{file})
24682 @atindex{CAPTURE_FILE}
24683 If the current test group fails, log the contents of @var{file}.
24684 Several identical calls within one test group have no additional effect.
24685 @end defmac
24687 @defmac AT_FAIL_IF (@var{shell-condition})
24688 @atindex{FAIL_IF}
24689 Make the test group fail and skip the rest of its execution, if
24690 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
24691 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
24692 will be executed and may still cause the test group to be skipped.
24693 You can instantiate this macro many times from within the same test group.
24695 You should use this macro only for very simple failure conditions.  If the
24696 @var{shell-condition} could emit any kind of output you should instead
24697 use @command{AT_CHECK} like
24698 @example
24699 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
24700 @end example
24701 @noindent
24702 so that such output is properly recorded in the @file{testsuite.log}
24703 file.
24704 @end defmac
24706 @defmac AT_SKIP_IF (@var{shell-condition})
24707 @atindex{SKIP_IF}
24708 Determine whether the test should be skipped because it requires
24709 features that are unsupported on the machine under test.
24710 @var{shell-condition} is a shell expression such as a @code{test}
24711 command.  Tests before @command{AT_SKIP_IF} will be executed
24712 and may still cause the test group to fail.  You can instantiate this
24713 macro many times from within the same test group.
24715 You should use this macro only for very simple skip conditions.  If the
24716 @var{shell-condition} could emit any kind of output you should instead
24717 use @command{AT_CHECK} like
24718 @example
24719 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
24720 @end example
24721 @noindent
24722 so that such output is properly recorded in the @file{testsuite.log}
24723 file.
24724 @end defmac
24726 @defmac AT_XFAIL_IF (@var{shell-condition})
24727 @atindex{XFAIL_IF}
24728 Determine whether the test is expected to fail because it is a known
24729 bug (for unsupported features, you should skip the test).
24730 @var{shell-condition} is a shell expression such as a @code{test}
24731 command; you can instantiate this macro many times from within the
24732 same test group, and one of the conditions is enough to turn
24733 the test into an expected failure.
24734 @end defmac
24736 @defmac AT_CLEANUP
24737 @atindex{CLEANUP}
24738 End the current test group.
24739 @end defmac
24741 @sp 1
24743 @defmac AT_DATA (@var{file}, @var{contents})
24744 @atindex{DATA}
24745 Initialize an input data @var{file} with given @var{contents}.  Of
24746 course, the @var{contents} have to be properly quoted between square
24747 brackets to protect against included commas or spurious M4
24748 expansion.  @var{contents} must be empty or end with a newline.
24749 @var{file} must
24750 be a single shell word that expands into a single file name.
24751 @end defmac
24753 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24754   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24755 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
24756   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
24757 @atindex{CHECK}
24758 @atindex{CHECK_UNQUOTED}
24759 @vrindex at_status
24760 Execute a test by performing given shell @var{commands} in a subshell.
24761 @var{commands} is output as-is, so shell expansions are honored.  These
24762 commands should normally exit with @var{status}, while producing expected
24763 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
24764 unexpected status 77, then the rest of the test group is skipped.  If
24765 @var{commands} exit with unexpected status 99, then the test group is
24766 immediately failed.  Otherwise, if this test fails, run shell commands
24767 @var{run-if-fail} or, if this test passes, run shell commands
24768 @var{run-if-pass}, both inside the current shell execution environment.
24769 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
24770 @var{commands} is available in the @code{at_status} shell variable.
24772 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24774 If @var{status} is the literal @samp{ignore}, then the corresponding
24775 exit status is not checked, except for the special cases of 77 (skip)
24776 and 99 (hard failure).  The existence of hard failures allows one to
24777 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
24778 feature has not yet been implemented, but to still distinguish between
24779 gracefully handling the missing feature and dumping core.  A hard
24780 failure also inhibits post-test actions in @var{run-if-fail}.
24782 If the value of the @var{stdout} or @var{stderr} parameter is one of the
24783 literals in the following table, then the test treats the output
24784 according to the rules of that literal.  Otherwise, the value of the
24785 parameter is treated as text that must exactly match the output given by
24786 @var{commands} on standard output and standard error (including an empty
24787 parameter for no output); any differences are captured in the testsuite
24788 log and the test is failed (unless an unexpected exit status of 77
24789 skipped the test instead).  The difference between @code{AT_CHECK} and
24790 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
24791 expansion (@samp{$}), command substitution (@samp{`}), and backslash
24792 escaping (@samp{\}) on comparison text given in the @var{stdout} and
24793 @var{stderr} arguments; if the text includes a trailing newline, this
24794 would be the same as if it were specified via an unquoted
24795 here-document.  (However, there is no difference in the interpretation
24796 of @var{commands}).
24798 @table @samp
24799 @item ignore
24800 The content of the output is ignored, but still captured in the test
24801 group log (if the testsuite is run with option @option{-v}, the test
24802 group log is displayed as the test is run; if the test group later
24803 fails, the test group log is also copied into the overall testsuite
24804 log).  This action is valid for both @var{stdout} and @var{stderr}.
24806 @item ignore-nolog
24807 The content of the output is ignored, and nothing is captured in the log
24808 files.  If @var{commands} are likely to produce binary output (including
24809 long lines) or large amounts of output, then logging the output can make
24810 it harder to locate details related to subsequent tests within the
24811 group, and could potentially corrupt terminal display of a user running
24812 @command{testsuite -v}.
24814 @item stdout
24815 For the @var{stdout} parameter, capture the content of standard output
24816 to both the file @file{stdout} and the test group log.  Subsequent
24817 commands in the test group can then post-process the file.  This action
24818 is often used when it is desired to use @command{grep} to look for a
24819 substring in the output, or when the output must be post-processed to
24820 normalize error messages into a common form.
24822 @item stderr
24823 Like @samp{stdout}, except that it only works for the @var{stderr}
24824 parameter, and the standard error capture file will be named
24825 @file{stderr}.
24827 @item stdout-nolog
24828 @itemx stderr-nolog
24829 Like @samp{stdout} or @samp{stderr}, except that the captured output is
24830 not duplicated into the test group log.  This action is particularly
24831 useful for an intermediate check that produces large amounts of data,
24832 which will be followed by another check that filters down to the
24833 relevant data, as it makes it easier to locate details in the log.
24835 @item expout
24836 For the @var{stdout} parameter, compare standard output contents with
24837 the previously created file @file{expout}, and list any differences in
24838 the testsuite log.
24840 @item experr
24841 Like @samp{expout}, except that it only works for the @var{stderr}
24842 parameter, and the standard error contents are compared with
24843 @file{experr}.
24844 @end table
24845 @end defmac
24847 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
24848   @ovar{run-if-fail}, @ovar{run-if-pass})
24849 @atindex{CHECK_EUNIT}
24850 Initialize and execute an Erlang module named @var{module} that performs
24851 tests following the @var{test-spec} EUnit test specification.
24852 @var{test-spec} must be a valid EUnit test specification, as defined in
24853 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
24854 Reference Manual}.  @var{erlflags} are optional command-line options
24855 passed to the Erlang interpreter to execute the test Erlang module.
24856 Typically, @var{erlflags} defines at least the paths to directories
24857 containing the compiled Erlang modules under test, as @samp{-pa path1
24858 path2 ...}.
24860 For example, the unit tests associated with Erlang module @samp{testme},
24861 which compiled code is in subdirectory @file{src}, can be performed
24862 with:
24864 @example
24865 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
24866                [-pa "$@{abs_top_builddir@}/src"])
24867 @end example
24869 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
24871 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
24872 must be defined as the path of the Erlang interpreter, the path of the
24873 Erlang compiler, and the command-line flags to pass to the compiler,
24874 respectively.  Those variables should be configured in
24875 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
24876 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
24877 variables are automatically defined in the testsuite.  If @code{ERL} or
24878 @code{ERLC} is not defined, the test group is skipped.
24880 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
24881 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
24882 an invalid EUnit test specification, the test group fails.  Otherwise,
24883 if the EUnit test passes, shell commands @var{run-if-pass} are executed
24884 or, if the EUnit test fails, shell commands @var{run-if-fail} are
24885 executed and the test group fails.
24887 Only the generated test Erlang module is automatically compiled and
24888 executed.  If @var{test-spec} involves testing other Erlang modules,
24889 e.g. module @samp{testme} in the example above, those modules must be
24890 already compiled.
24892 If the testsuite is run in verbose mode, with option @option{--verbose},
24893 EUnit is also run in verbose mode to output more details about
24894 individual unit tests.
24895 @end defmac
24898 @node testsuite Invocation
24899 @section Running @command{testsuite} Scripts
24900 @cindex @command{testsuite}
24902 Autotest test suites support the following options:
24904 @table @option
24905 @item --help
24906 @itemx -h
24907 Display the list of options and exit successfully.
24909 @item --version
24910 @itemx -V
24911 Display the version of the test suite and exit successfully.
24913 @item --directory=@var{dir}
24914 @itemx -C @var{dir}
24915 Change the current directory to @var{dir} before creating any files.
24916 Useful for running the testsuite in a subdirectory from a top-level
24917 Makefile.
24919 @item --jobs@r{[}=@var{n}@r{]}
24920 @itemx -j@ovar{n}
24921 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
24922 run all given tests in parallel.  Note that there should be no space
24923 before the argument to @option{-j}, as @option{-j @var{number}} denotes
24924 the separate arguments @option{-j} and @option{@var{number}}, see below.
24926 In parallel mode, the standard input device of the testsuite script is
24927 not available to commands inside a test group.  Furthermore, banner
24928 lines are not printed, and the summary line for each test group is
24929 output after the test group completes.  Summary lines may appear
24930 unordered.  If verbose and trace output are enabled (see below), they
24931 may appear intermixed from concurrently running tests.
24933 Parallel mode requires the @command{mkfifo} command to work, and will be
24934 silently disabled otherwise.
24936 @item --clean
24937 @itemx -c
24938 Remove all the files the test suite might have created and exit.  Meant
24939 for @code{clean} Make targets.
24941 @item --list
24942 @itemx -l
24943 List all the tests (or only the selection), including their possible
24944 keywords.
24945 @end table
24947 @sp 1
24949 By default all tests are performed (or described with @option{--list})
24950 silently in the default environment, but the environment, set of tests,
24951 and verbosity level can be tuned:
24953 @table @samp
24954 @item @var{variable}=@var{value}
24955 Set the environment @var{variable} to @var{value}.  Use this rather
24956 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
24957 different environment.
24959 @cindex @code{AUTOTEST_PATH}
24960 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
24961 to @env{PATH}.  Relative directory names (not starting with
24962 @samp{/}) are considered to be relative to the top level of the
24963 package being built.  All directories are made absolute, first
24964 starting from the top level @emph{build} tree, then from the
24965 @emph{source} tree.  For instance @samp{./testsuite
24966 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
24967 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
24968 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
24969 @env{PATH}.
24971 @item @var{number}
24972 @itemx @var{number}-@var{number}
24973 @itemx @var{number}-
24974 @itemx -@var{number}
24975 Add the corresponding test groups, with obvious semantics, to the
24976 selection.
24978 @item --keywords=@var{keywords}
24979 @itemx -k @var{keywords}
24980 Add to the selection the test groups with title or keywords (arguments
24981 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
24982 of the comma separated list @var{keywords}, case-insensitively.  Use
24983 @samp{!} immediately before the keyword to invert the selection for this
24984 keyword.  By default, the keywords match whole words; enclose them in
24985 @samp{.*} to also match parts of words.
24987 For example, running
24989 @example
24990 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
24991 @end example
24993 @noindent
24994 selects all tests tagged @samp{autoupdate} @emph{and} with tags
24995 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
24996 etc.), while
24998 @example
24999 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25000 @end example
25002 @noindent
25003 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25004 containing @samp{FUNC}.
25006 @item --errexit
25007 @itemx -e
25008 If any test fails, immediately abort testing.  This implies
25009 @option{--debug}: post test group clean up, and top-level logging
25010 are inhibited.  This option is meant for the full test
25011 suite, it is not really useful for generated debugging scripts.
25012 If the testsuite is run in parallel mode using @option{--jobs},
25013 then concurrently running tests will finish before exiting.
25015 @item --verbose
25016 @itemx -v
25017 Force more verbosity in the detailed output of what is being done.  This
25018 is the default for debugging scripts.
25020 @item --color
25021 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25022 Enable colored test results.  Without an argument, or with @samp{always},
25023 test results will be colored.  With @samp{never}, color mode is turned
25024 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25025 the testsuite author, or the argument @samp{auto} is given, then test
25026 results are colored if standard output is connected to a terminal.
25028 @item --debug
25029 @itemx -d
25030 Do not remove the files after a test group was performed---but they are
25031 still removed @emph{before}, therefore using this option is sane when
25032 running several test groups.  Create debugging scripts.  Do not
25033 overwrite the top-level
25034 log (in order to preserve a supposedly existing full log file).  This is
25035 the default for debugging scripts, but it can also be useful to debug
25036 the testsuite itself.
25038 @item --recheck
25039 Add to the selection all test groups that failed or passed unexpectedly
25040 during the last non-debugging test run.
25042 @item --trace
25043 @itemx -x
25044 Trigger shell tracing of the test groups.
25045 @end table
25047 Besides these options accepted by every Autotest testsuite, the
25048 testsuite author might have added package-specific options
25049 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25050 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25051 the package documentation for details.
25054 @node Making testsuite Scripts
25055 @section Making @command{testsuite} Scripts
25057 For putting Autotest into movement, you need some configuration and
25058 makefile machinery.  We recommend, at least if your package uses deep or
25059 shallow hierarchies, that you use @file{tests/} as the name of the
25060 directory holding all your tests and their makefile.  Here is a
25061 check list of things to do.
25063 @itemize @minus
25065 @item
25066 @cindex @file{package.m4}
25067 @atindex{PACKAGE_STRING}
25068 @atindex{PACKAGE_BUGREPORT}
25069 @atindex{PACKAGE_NAME}
25070 @atindex{PACKAGE_TARNAME}
25071 @atindex{PACKAGE_VERSION}
25072 @atindex{PACKAGE_URL}
25073 Make sure to create the file @file{package.m4}, which defines the
25074 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25075 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25076 address to which bug reports should be sent.  For sake of completeness,
25077 we suggest that you also define @code{AT_PACKAGE_NAME},
25078 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25079 @code{AT_PACKAGE_URL}.
25080 @xref{Initializing configure}, for a description of these variables.
25081 Be sure to distribute @file{package.m4} and to put it into the source
25082 hierarchy: the test suite ought to be shipped!  See below for an example
25083 @file{Makefile} excerpt.
25085 @item
25086 Invoke @code{AC_CONFIG_TESTDIR}.
25088 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
25089 @acindex{CONFIG_TESTDIR}
25090 An Autotest test suite is to be configured in @var{directory}.  This
25091 macro causes @file{@var{directory}/atconfig} to be created by
25092 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25093 @var{test-path} (@pxref{testsuite Invocation}).
25094 @end defmac
25096 @item
25097 Still within @file{configure.ac}, as appropriate, ensure that some
25098 @code{AC_CONFIG_FILES} command includes substitution for
25099 @file{tests/atlocal}.
25101 @item
25102 The appropriate @file{Makefile} should be modified so the validation in
25103 your package is triggered by @samp{make check}.  An example is provided
25104 below.
25105 @end itemize
25107 With Automake, here is a minimal example for inclusion in
25108 @file{tests/Makefile.am}, in order to link @samp{make check} with a
25109 validation suite.
25111 @example
25112 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
25113 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25114         :;@{ \
25115           echo '# Signature of the current package.' && \
25116           echo 'm4_define([AT_PACKAGE_NAME],' && \
25117           echo '  [$(PACKAGE_NAME)])' && \
25118           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25119           echo '  [$(PACKAGE_TARNAME)])' && \
25120           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25121           echo '  [$(PACKAGE_VERSION)])' && \
25122           echo 'm4_define([AT_PACKAGE_STRING],' && \
25123           echo '  [$(PACKAGE_STRING)])' && \
25124           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25125           echo '  [$(PACKAGE_BUGREPORT)])'; \
25126           echo 'm4_define([AT_PACKAGE_URL],' && \
25127           echo '  [$(PACKAGE_URL)])'; \
25128         @} >'$(srcdir)/package.m4'
25130 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25131 TESTSUITE = $(srcdir)/testsuite
25133 check-local: atconfig atlocal $(TESTSUITE)
25134         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25136 installcheck-local: atconfig atlocal $(TESTSUITE)
25137         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25138           $(TESTSUITEFLAGS)
25140 clean-local:
25141         test ! -f '$(TESTSUITE)' || \
25142          $(SHELL) '$(TESTSUITE)' --clean
25144 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
25145 AUTOTEST = $(AUTOM4TE) --language=autotest
25146 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25147         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25148         mv $@@.tmp $@@
25149 @end example
25151 Note that the built testsuite is distributed; this is necessary because
25152 users might not have Autoconf installed, and thus would not be able to
25153 rebuild it.  Likewise, the use of @file{missing} provides the user with
25154 a nicer error message if they modify a source file to the testsuite, and
25155 accidentally trigger the rebuild rules.
25157 You might want to list explicitly the dependencies, i.e., the list of
25158 the files @file{testsuite.at} includes.
25160 If you don't use Automake, you should include the above example in
25161 @file{tests/@/Makefile.in}, along with additional lines inspired from
25162 the following:
25164 @example
25165 subdir = tests
25166 PACKAGE_NAME = @@PACKAGE_NAME@@
25167 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25168 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25169 PACKAGE_STRING = @@PACKAGE_STRING@@
25170 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25171 PACKAGE_URL = @@PACKAGE_URL@@
25173 atconfig: $(top_builddir)/config.status
25174         cd $(top_builddir) && \
25175            $(SHELL) ./config.status $(subdir)/$@@
25177 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25178         cd $(top_builddir) && \
25179            $(SHELL) ./config.status $(subdir)/$@@
25180 @end example
25182 @noindent
25183 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
25184 to distribute the file @file{build-aux/@/missing} from the Automake
25185 project; a copy of this file resides in the Autoconf source tree.
25187 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
25188 within your makefile, you can fine-tune test suite execution with this
25189 variable, for example:
25191 @example
25192 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25193 @end example
25197 @c =============================== Frequent Autoconf Questions, with answers
25199 @node FAQ
25200 @chapter Frequent Autoconf Questions, with answers
25202 Several questions about Autoconf come up occasionally.  Here some of them
25203 are addressed.
25205 @menu
25206 * Distributing::                Distributing @command{configure} scripts
25207 * Why GNU M4::                  Why not use the standard M4?
25208 * Bootstrapping::               Autoconf and GNU M4 require each other?
25209 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25210 * Defining Directories::        Passing @code{datadir} to program
25211 * Autom4te Cache::              What is it?  Can I remove it?
25212 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25213 * Expanded Before Required::    Expanded Before Required
25214 * Debugging::                   Debugging @command{configure} scripts
25215 @end menu
25217 @node Distributing
25218 @section Distributing @command{configure} Scripts
25219 @cindex License
25221 @display
25222 What are the restrictions on distributing @command{configure}
25223 scripts that Autoconf generates?  How does that affect my
25224 programs that use them?
25225 @end display
25227 There are no restrictions on how the configuration scripts that Autoconf
25228 produces may be distributed or used.  In Autoconf version 1, they were
25229 covered by the GNU General Public License.  We still encourage
25230 software authors to distribute their work under terms like those of the
25231 GPL, but doing so is not required to use Autoconf.
25233 Of the other files that might be used with @command{configure},
25234 @file{config.h.in} is under whatever copyright you use for your
25235 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25236 exception to the GPL when they are used with an Autoconf-generated
25237 @command{configure} script, which permits you to distribute them under the
25238 same terms as the rest of your package.  @file{install-sh} is from the X
25239 Consortium and is not copyrighted.
25241 @node Why GNU M4
25242 @section Why Require GNU M4?
25244 @display
25245 Why does Autoconf require GNU M4?
25246 @end display
25248 Many M4 implementations have hard-coded limitations on the size and
25249 number of macros that Autoconf exceeds.  They also lack several
25250 builtin macros that it would be difficult to get along without in a
25251 sophisticated application like Autoconf, including:
25253 @example
25254 m4_builtin
25255 m4_indir
25256 m4_bpatsubst
25257 __file__
25258 __line__
25259 @end example
25261 Autoconf requires version 1.4.6 or later of GNU M4.
25263 Since only software maintainers need to use Autoconf, and since GNU
25264 M4 is simple to configure and install, it seems reasonable to require
25265 GNU M4 to be installed also.  Many maintainers of GNU and
25266 other free software already have most of the GNU utilities
25267 installed, since they prefer them.
25269 @node Bootstrapping
25270 @section How Can I Bootstrap?
25271 @cindex Bootstrap
25273 @display
25274 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25275 @command{configure} script, how do I bootstrap?  It seems like a chicken
25276 and egg problem!
25277 @end display
25279 This is a misunderstanding.  Although GNU M4 does come with a
25280 @command{configure} script produced by Autoconf, Autoconf is not required
25281 in order to run the script and install GNU M4.  Autoconf is only
25282 required if you want to change the M4 @command{configure} script, which few
25283 people have to do (mainly its maintainer).
25285 @node Why Not Imake
25286 @section Why Not Imake?
25287 @cindex Imake
25289 @display
25290 Why not use Imake instead of @command{configure} scripts?
25291 @end display
25293 Several people have written addressing this question, so
25294 adaptations of their explanations are included here.
25296 The following answer is based on one written by Richard Pixley:
25298 @quotation
25299 Autoconf generated scripts frequently work on machines that it has
25300 never been set up to handle before.  That is, it does a good job of
25301 inferring a configuration for a new system.  Imake cannot do this.
25303 Imake uses a common database of host specific data.  For X11, this makes
25304 sense because the distribution is made as a collection of tools, by one
25305 central authority who has control over the database.
25307 GNU tools are not released this way.  Each GNU tool has a
25308 maintainer; these maintainers are scattered across the world.  Using a
25309 common database would be a maintenance nightmare.  Autoconf may appear
25310 to be this kind of database, but in fact it is not.  Instead of listing
25311 host dependencies, it lists program requirements.
25313 If you view the GNU suite as a collection of native tools, then the
25314 problems are similar.  But the GNU development tools can be
25315 configured as cross tools in almost any host+target permutation.  All of
25316 these configurations can be installed concurrently.  They can even be
25317 configured to share host independent files across hosts.  Imake doesn't
25318 address these issues.
25320 Imake templates are a form of standardization.  The GNU coding
25321 standards address the same issues without necessarily imposing the same
25322 restrictions.
25323 @end quotation
25326 Here is some further explanation, written by Per Bothner:
25328 @quotation
25329 One of the advantages of Imake is that it is easy to generate large
25330 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25331 However, @code{cpp} is not programmable: it has limited conditional
25332 facilities, and no looping.  And @code{cpp} cannot inspect its
25333 environment.
25335 All of these problems are solved by using @code{sh} instead of
25336 @code{cpp}.  The shell is fully programmable, has macro substitution,
25337 can execute (or source) other shell scripts, and can inspect its
25338 environment.
25339 @end quotation
25342 Paul Eggert elaborates more:
25344 @quotation
25345 With Autoconf, installers need not assume that Imake itself is already
25346 installed and working well.  This may not seem like much of an advantage
25347 to people who are accustomed to Imake.  But on many hosts Imake is not
25348 installed or the default installation is not working well, and requiring
25349 Imake to install a package hinders the acceptance of that package on
25350 those hosts.  For example, the Imake template and configuration files
25351 might not be installed properly on a host, or the Imake build procedure
25352 might wrongly assume that all source files are in one big directory
25353 tree, or the Imake configuration might assume one compiler whereas the
25354 package or the installer needs to use another, or there might be a
25355 version mismatch between the Imake expected by the package and the Imake
25356 supported by the host.  These problems are much rarer with Autoconf,
25357 where each package comes with its own independent configuration
25358 processor.
25360 Also, Imake often suffers from unexpected interactions between
25361 @command{make} and the installer's C preprocessor.  The fundamental problem
25362 here is that the C preprocessor was designed to preprocess C programs,
25363 not makefiles.  This is much less of a problem with Autoconf,
25364 which uses the general-purpose preprocessor M4, and where the
25365 package's author (rather than the installer) does the preprocessing in a
25366 standard way.
25367 @end quotation
25370 Finally, Mark Eichin notes:
25372 @quotation
25373 Imake isn't all that extensible, either.  In order to add new features to
25374 Imake, you need to provide your own project template, and duplicate most
25375 of the features of the existing one.  This means that for a sophisticated
25376 project, using the vendor-provided Imake templates fails to provide any
25377 leverage---since they don't cover anything that your own project needs
25378 (unless it is an X11 program).
25380 On the other side, though:
25382 The one advantage that Imake has over @command{configure}:
25383 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
25384 than @file{Makefile.in} files.  There is a fix to this, however---at least
25385 for the Kerberos V5 tree, we've modified things to call in common
25386 @file{post.in} and @file{pre.in} makefile fragments for the
25387 entire tree.  This means that a lot of common things don't have to be
25388 duplicated, even though they normally are in @command{configure} setups.
25389 @end quotation
25392 @node Defining Directories
25393 @section How Do I @code{#define} Installation Directories?
25395 @display
25396 My program needs library files, installed in @code{datadir} and
25397 similar.  If I use
25399 @example
25400 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
25401   [Define to the read-only architecture-independent
25402    data directory.])
25403 @end example
25405 @noindent
25406 I get
25408 @example
25409 #define DATADIR "$@{prefix@}/share"
25410 @end example
25411 @end display
25413 As already explained, this behavior is on purpose, mandated by the
25414 GNU Coding Standards, see @ref{Installation Directory
25415 Variables}.  There are several means to achieve a similar goal:
25417 @itemize @minus
25418 @item
25419 Do not use @code{AC_DEFINE} but use your makefile to pass the
25420 actual value of @code{datadir} via compilation flags.
25421 @xref{Installation Directory Variables}, for the details.
25423 @item
25424 This solution can be simplified when compiling a program: you may either
25425 extend the @code{CPPFLAGS}:
25427 @example
25428 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
25429 @end example
25431 @noindent
25432 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
25434 @example
25435 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
25436 @end example
25438 @noindent
25439 Alternatively, create a dedicated header file:
25441 @example
25442 DISTCLEANFILES = myprog-paths.h
25443 myprog-paths.h: Makefile
25444         echo '#define DATADIR "$(datadir)"' >$@@
25445 @end example
25447 @noindent
25448 The gnulib module @samp{configmake} provides such a header with all the
25449 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
25450 Gnulib}.
25452 @item
25453 Use @code{AC_DEFINE} but have @command{configure} compute the literal
25454 value of @code{datadir} and others.  Many people have wrapped macros to
25455 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
25456 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
25457 Archive}.
25459 This solution does not conform to the GNU Coding Standards.
25461 @item
25462 Note that all the previous solutions hard wire the absolute name of
25463 these directories in the executables, which is not a good property.  You
25464 may try to compute the names relative to @code{prefix}, and try to
25465 find @code{prefix} at runtime, this way your package is relocatable.
25466 @end itemize
25469 @node Autom4te Cache
25470 @section What is @file{autom4te.cache}?
25472 @display
25473 What is this directory @file{autom4te.cache}?  Can I safely remove it?
25474 @end display
25476 In the GNU Build System, @file{configure.ac} plays a central
25477 role and is read by many tools: @command{autoconf} to create
25478 @file{configure}, @command{autoheader} to create @file{config.h.in},
25479 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
25480 check the completeness of @file{configure.ac}, @command{autoreconf} to
25481 check the GNU Build System components that are used.  To
25482 ``read @file{configure.ac}'' actually means to compile it with M4,
25483 which can be a long process for complex @file{configure.ac}.
25485 This is why all these tools, instead of running directly M4, invoke
25486 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
25487 a specific demand, stores additional information in
25488 @file{autom4te.cache} for future runs.  For instance, if you run
25489 @command{autoconf}, behind the scenes, @command{autom4te} also
25490 stores information for the other tools, so that when you invoke
25491 @command{autoheader} or @command{automake} etc., reprocessing
25492 @file{configure.ac} is not needed.  The speed up is frequently 30%,
25493 and is increasing with the size of @file{configure.ac}.
25495 But it is and remains being simply a cache: you can safely remove it.
25497 @sp 1
25499 @display
25500 Can I permanently get rid of it?
25501 @end display
25503 The creation of this cache can be disabled from
25504 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
25505 details.  You should be aware that disabling the cache slows down the
25506 Autoconf test suite by 40%.  The more GNU Build System
25507 components are used, the more the cache is useful; for instance
25508 running @samp{autoreconf -f} on the Core Utilities is twice slower without
25509 the cache @emph{although @option{--force} implies that the cache is
25510 not fully exploited}, and eight times slower than without
25511 @option{--force}.
25514 @node Present But Cannot Be Compiled
25515 @section Header Present But Cannot Be Compiled
25517 The most important guideline to bear in mind when checking for
25518 features is to mimic as much as possible the intended use.
25519 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
25520 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
25521 the preprocessor, instead of the compiler, to check for headers.  As a
25522 result, incompatibilities between headers went unnoticed during
25523 configuration, and maintainers finally had to deal with this issue
25524 elsewhere.
25526 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
25527 checks are performed, and @command{configure} complains loudly if the
25528 compiler and the preprocessor do not agree.  However, only the compiler
25529 result is considered.
25531 Consider the following example:
25533 @smallexample
25534 $ @kbd{cat number.h}
25535 typedef int number;
25536 $ @kbd{cat pi.h}
25537 const number pi = 3;
25538 $ @kbd{cat configure.ac}
25539 AC_INIT([Example], [1.0], [bug-example@@example.org])
25540 AC_CHECK_HEADERS([pi.h])
25541 $ @kbd{autoconf -Wall}
25542 $ @kbd{./configure}
25543 checking for gcc... gcc
25544 checking for C compiler default output file name... a.out
25545 checking whether the C compiler works... yes
25546 checking whether we are cross compiling... no
25547 checking for suffix of executables...
25548 checking for suffix of object files... o
25549 checking whether we are using the GNU C compiler... yes
25550 checking whether gcc accepts -g... yes
25551 checking for gcc option to accept ISO C89... none needed
25552 checking how to run the C preprocessor... gcc -E
25553 checking for grep that handles long lines and -e... grep
25554 checking for egrep... grep -E
25555 checking for ANSI C header files... yes
25556 checking for sys/types.h... yes
25557 checking for sys/stat.h... yes
25558 checking for stdlib.h... yes
25559 checking for string.h... yes
25560 checking for memory.h... yes
25561 checking for strings.h... yes
25562 checking for inttypes.h... yes
25563 checking for stdint.h... yes
25564 checking for unistd.h... yes
25565 checking pi.h usability... no
25566 checking pi.h presence... yes
25567 configure: WARNING: pi.h: present but cannot be compiled
25568 configure: WARNING: pi.h:     check for missing prerequisite headers?
25569 configure: WARNING: pi.h: see the Autoconf documentation
25570 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
25571 configure: WARNING: pi.h: proceeding with the compiler's result
25572 configure: WARNING:     ## -------------------------------------- ##
25573 configure: WARNING:     ## Report this to bug-example@@example.org ##
25574 configure: WARNING:     ## -------------------------------------- ##
25575 checking for pi.h... yes
25576 @end smallexample
25578 @noindent
25579 The proper way the handle this case is using the fourth argument
25580 (@pxref{Generic Headers}):
25582 @example
25583 $ @kbd{cat configure.ac}
25584 AC_INIT([Example], [1.0], [bug-example@@example.org])
25585 AC_CHECK_HEADERS([number.h pi.h], [], [],
25586 [[#ifdef HAVE_NUMBER_H
25587 # include <number.h>
25588 #endif
25590 $ @kbd{autoconf -Wall}
25591 $ @kbd{./configure}
25592 checking for gcc... gcc
25593 checking for C compiler default output... a.out
25594 checking whether the C compiler works... yes
25595 checking whether we are cross compiling... no
25596 checking for suffix of executables...
25597 checking for suffix of object files... o
25598 checking whether we are using the GNU C compiler... yes
25599 checking whether gcc accepts -g... yes
25600 checking for gcc option to accept ANSI C... none needed
25601 checking for number.h... yes
25602 checking for pi.h... yes
25603 @end example
25605 See @ref{Particular Headers}, for a list of headers with their
25606 prerequisites.
25608 @node Expanded Before Required
25609 @section Expanded Before Required
25611 @cindex expanded before required
25612 Older versions of Autoconf silently built files with incorrect ordering
25613 between dependent macros if an outer macro first expanded, then later
25614 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
25615 situation no longer generates out-of-order code, but results in
25616 duplicate output and a syntax warning:
25618 @example
25619 $ @kbd{cat configure.ac}
25620 @result{}AC_DEFUN([TESTA], [[echo in A
25621 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
25622 @result{}SEEN_A=:]])
25623 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
25624 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
25625 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
25626 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
25627 @result{}TESTA
25628 @result{}TESTC])
25629 @result{}AC_INIT
25630 @result{}OUTER
25631 @result{}AC_OUTPUT
25632 $ @kbd{autoconf}
25633 @result{}configure.ac:11: warning: AC_REQUIRE:
25634 @result{} `TESTA' was expanded before it was required
25635 @result{}configure.ac:4: TESTB is expanded from...
25636 @result{}configure.ac:6: TESTC is expanded from...
25637 @result{}configure.ac:7: OUTER is expanded from...
25638 @result{}configure.ac:11: the top level
25639 @end example
25641 @noindent
25642 To avoid this warning, decide what purpose the macro in question serves.
25643 If it only needs to be expanded once (for example, if it provides
25644 initialization text used by later macros), then the simplest fix is to
25645 change the macro to be declared with @code{AC_DEFUN_ONCE}
25646 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
25647 newer.  A more portable fix is to change all
25648 instances of direct calls to instead go through @code{AC_REQUIRE}
25649 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
25650 by arguments or by the current definition of other macros in the m4
25651 environment, then the macro should always be directly expanded instead
25652 of required.
25654 For another case study, consider this example trimmed down from an
25655 actual package.  Originally, the package contained shell code and
25656 multiple macro invocations at the top level of @file{configure.ac}:
25658 @example
25659 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25660 foobar=
25661 AC_PROG_CC
25663 @end example
25665 @noindent
25666 but that was getting complex, so the author wanted to offload some of
25667 the text into a new macro in another file included via
25668 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
25669 macro:
25671 @example
25672 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25673 AC_DEFUN([BAR], [
25674 foobar=
25675 AC_PROG_CC
25679 @end example
25681 @noindent
25682 With older versions of Autoconf, the setting of @samp{foobar=} occurs
25683 before the single compiler check, as the author intended.  But with
25684 Autoconf 2.64, this issues the ``expanded before it was required''
25685 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
25686 check, one before @samp{foobar=}, and one after.  To understand why this
25687 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
25688 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
25689 the documented semantics of @code{AC_REQUIRE}, this means that
25690 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
25691 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceeding the
25692 use of @samp{foobar=}.  The older versions of Autoconf were broken with
25693 regards to the rules of @code{AC_REQUIRE}, which explains why the code
25694 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
25695 autoconf.  In other words, the author was unknowingly relying on a bug
25696 exploit to get the desired results, and that exploit broke once the bug
25697 was fixed.
25699 So, what recourse does the author have, to restore their intended
25700 semantics of setting @samp{foobar=} prior to a single compiler check,
25701 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
25702 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
25703 there is always the possibility of using the lower-level
25704 @code{m4_define}:
25706 @example
25707 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25708 m4_define([BAR], [
25709 foobar=
25710 AC_PROG_CC
25714 @end example
25716 @noindent
25717 This works great if everything is in the same file.  However, it does
25718 not help in the case where the author wants to have @command{aclocal}
25719 find the definition of @code{BAR} from its own file, since
25720 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
25721 better fix is to recognize that if @code{BAR} also uses
25722 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
25723 to a subsequent require.  Then, by creating yet another helper macro,
25724 the author can once again guarantee a single invocation of
25725 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
25726 author can also use @code{AC_BEFORE} to make sure no other macro
25727 appearing before @code{BAR} has triggered an unwanted expansion of
25728 @code{AC_PROG_CC}.
25730 @example
25731 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
25732 AC_DEFUN([BEFORE_CC], [
25733 foobar=
25735 AC_DEFUN([BAR], [
25736 AC_BEFORE([$0], [AC_PROG_CC])dnl
25737 AC_REQUIRE([BEFORE_CC])dnl
25738 AC_REQUIRE([AC_PROG_CC])dnl
25742 @end example
25745 @node Debugging
25746 @section Debugging @command{configure} scripts
25748 While in general, @command{configure} scripts generated by Autoconf
25749 strive to be fairly portable to various systems, compilers, shells, and
25750 other tools, it may still be necessary to debug a failing test, broken
25751 script or makefile, or fix or override an incomplete, faulty, or erroneous
25752 test, especially during macro development.  Failures can occur at all levels,
25753 in M4 syntax or semantics, shell script issues, or due to bugs in the
25754 test or the tools invoked by @command{configure}.  Together with the
25755 rather arcane error message that @command{m4} and @command{make} may
25756 produce when their input contains syntax errors, this can make debugging
25757 rather painful.
25759 Nevertheless, here is a list of hints and strategies that may help:
25761 @itemize
25762 @item
25763 When @command{autoconf} fails, common causes for error include:
25765 @itemize
25766 @item
25767 mismatched or unbalanced parentheses or braces (@pxref{Balancing
25768 Parentheses}),
25770 @item under- or overquoted macro arguments (@pxref{Autoconf
25771 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
25772 Macros}),
25774 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
25775 Language}).
25776 @end itemize
25778 Typically, it helps to go back to the last working version of the input
25779 and compare the differences for each of these errors.  Another
25780 possibility is to sprinkle pairs of @code{m4_traceon} and
25781 @code{m4_traceoff} judiciously in the code, either without a parameter
25782 or listing some macro names and watch @command{m4} expand its input
25783 verbosely (@pxref{Debugging via autom4te}).
25785 @item
25786 Sometimes @command{autoconf} succeeds but the generated
25787 @command{configure} script has invalid shell syntax.  You can detect this
25788 case by running @samp{bash -n configure} or @samp{sh -n configure}.
25789 If this command fails, the same tips apply, as if @command{autoconf} had
25790 failed.
25792 @item
25793 Debugging @command{configure} script execution may be done by sprinkling
25794 pairs of @code{set -x} and @code{set +x} into the shell script before
25795 and after the region that contains a bug.  Running the whole script with
25796 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
25797 @var{shell} may work, but produces lots of output.  Here, it can help to
25798 search for markers like @samp{checking for} a particular test in the
25799 @var{log-file}.
25801 @item
25802 Alternatively, you might use a shell with debugging capabilities like
25803 @uref{http://bashdb.sourceforge.net/, bashdb}.
25805 @item
25806 When @command{configure} tests produce invalid results for your system,
25807 it may be necessary to override them:
25809 @itemize
25810 @item
25811 For programs, tools or libraries variables, preprocessor, compiler, or
25812 linker flags, it is often sufficient to override them at @command{make}
25813 run time with some care (@pxref{Macros and Submakes}).  Since this
25814 normally won't cause @command{configure} to be run again with these
25815 changed settings, it may fail if the changed variable would have caused
25816 different test results from @command{configure}, so this may work only
25817 for simple differences.
25819 @item
25820 Most tests which produce their result in a substituted variable allow to
25821 override the test by setting the variable on the @command{configure}
25822 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
25823 @pxref{Particular Systems}).
25825 @item
25826 Many tests store their result in a cache variable (@pxref{Caching
25827 Results}).  This lets you override them either on the
25828 @command{configure} command line as above, or through a primed cache or
25829 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
25830 cache variable is documented with a test macro or may be inferred from
25831 @ref{Cache Variable Names}; the precise semantics of undocumented
25832 variables are often internal details, subject to change.
25833 @end itemize
25835 @item
25836 Alternatively, @command{configure} may produce invalid results because
25837 of uncaught programming errors, in your package or in an upstream
25838 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
25839 library with a specified function, always check @file{config.log}.  This
25840 will reveal the exact error that produced the failing result: the
25841 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
25842 @end itemize
25844 Conversely, as macro author, you can make it easier for users of your
25845 macro:
25847 @itemize
25848 @item
25849 by minimizing dependencies between tests and between test results as far
25850 as possible,
25852 @item
25853 by using @command{make} variables to factorize and allow
25854 override of settings at @command{make} run time,
25856 @item
25857 by honoring the GNU Coding Standards and not overriding flags
25858 reserved for the user except temporarily during @command{configure}
25859 tests,
25861 @item
25862 by not requiring users of your macro to use the cache variables.
25863 Instead, expose the result of the test via @var{run-if-true} and
25864 @var{run-if-false} parameters.  If the result is not a boolean,
25865 then provide it through documented shell variables.
25866 @end itemize
25869 @c ===================================================== History of Autoconf.
25871 @node History
25872 @chapter History of Autoconf
25873 @cindex History of autoconf
25875 @emph{This chapter was written by the original author, David MacKenzie.}
25877 You may be wondering, Why was Autoconf originally written?  How did it
25878 get into its present form?  (Why does it look like gorilla spit?)  If
25879 you're not wondering, then this chapter contains no information useful
25880 to you, and you might as well skip it.  If you @emph{are} wondering,
25881 then let there be light@enddots{}
25883 @menu
25884 * Genesis::                     Prehistory and naming of @command{configure}
25885 * Exodus::                      The plagues of M4 and Perl
25886 * Leviticus::                   The priestly code of portability arrives
25887 * Numbers::                     Growth and contributors
25888 * Deuteronomy::                 Approaching the promises of easy configuration
25889 @end menu
25891 @node Genesis
25892 @section Genesis
25894 In June 1991 I was maintaining many of the GNU utilities for the
25895 Free Software Foundation.  As they were ported to more platforms and
25896 more programs were added, the number of @option{-D} options that users
25897 had to select in the makefile (around 20) became burdensome.
25898 Especially for me---I had to test each new release on a bunch of
25899 different systems.  So I wrote a little shell script to guess some of
25900 the correct settings for the fileutils package, and released it as part
25901 of fileutils 2.0.  That @command{configure} script worked well enough that
25902 the next month I adapted it (by hand) to create similar @command{configure}
25903 scripts for several other GNU utilities packages.  Brian Berliner
25904 also adapted one of my scripts for his CVS revision control system.
25906 Later that summer, I learned that Richard Stallman and Richard Pixley
25907 were developing similar scripts to use in the GNU compiler tools;
25908 so I adapted my @command{configure} scripts to support their evolving
25909 interface: using the file name @file{Makefile.in} as the templates;
25910 adding @samp{+srcdir}, the first option (of many); and creating
25911 @file{config.status} files.
25913 @node Exodus
25914 @section Exodus
25916 As I got feedback from users, I incorporated many improvements, using
25917 Emacs to search and replace, cut and paste, similar changes in each of
25918 the scripts.  As I adapted more GNU utilities packages to use
25919 @command{configure} scripts, updating them all by hand became impractical.
25920 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
25921 mail saying that the @command{configure} scripts were great, and asking if
25922 I had a tool for generating them that I could send him.  No, I thought,
25923 but I should!  So I started to work out how to generate them.  And the
25924 journey from the slavery of hand-written @command{configure} scripts to the
25925 abundance and ease of Autoconf began.
25927 Cygnus @command{configure}, which was being developed at around that time,
25928 is table driven; it is meant to deal mainly with a discrete number of
25929 system types with a small number of mainly unguessable features (such as
25930 details of the object file format).  The automatic configuration system
25931 that Brian Fox had developed for Bash takes a similar approach.  For
25932 general use, it seems to me a hopeless cause to try to maintain an
25933 up-to-date database of which features each variant of each operating
25934 system has.  It's easier and more reliable to check for most features on
25935 the fly---especially on hybrid systems that people have hacked on
25936 locally or that have patches from vendors installed.
25938 I considered using an architecture similar to that of Cygnus
25939 @command{configure}, where there is a single @command{configure} script that
25940 reads pieces of @file{configure.in} when run.  But I didn't want to have
25941 to distribute all of the feature tests with every package, so I settled
25942 on having a different @command{configure} made from each
25943 @file{configure.in} by a preprocessor.  That approach also offered more
25944 control and flexibility.
25946 I looked briefly into using the Metaconfig package, by Larry Wall,
25947 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
25948 reasons.  The @command{Configure} scripts it produces are interactive,
25949 which I find quite inconvenient; I didn't like the ways it checked for
25950 some features (such as library functions); I didn't know that it was
25951 still being maintained, and the @command{Configure} scripts I had
25952 seen didn't work on many modern systems (such as System V R4 and NeXT);
25953 it wasn't flexible in what it could do in response to a feature's
25954 presence or absence; I found it confusing to learn; and it was too big
25955 and complex for my needs (I didn't realize then how much Autoconf would
25956 eventually have to grow).
25958 I considered using Perl to generate my style of @command{configure}
25959 scripts, but decided that M4 was better suited to the job of simple
25960 textual substitutions: it gets in the way less, because output is
25961 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
25962 the GNU extensions to M4.)  Also, some of my friends at the
25963 University of Maryland had recently been putting M4 front ends on
25964 several programs, including @code{tvtwm}, and I was interested in trying
25965 out a new language.
25967 @node Leviticus
25968 @section Leviticus
25970 Since my @command{configure} scripts determine the system's capabilities
25971 automatically, with no interactive user intervention, I decided to call
25972 the program that generates them Autoconfig.  But with a version number
25973 tacked on, that name would be too long for old Unix file systems,
25974 so I shortened it to Autoconf.
25976 In the fall of 1991 I called together a group of fellow questers after
25977 the Holy Grail of portability (er, that is, alpha testers) to give me
25978 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
25979 and continued to add features and improve the techniques used in the
25980 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
25981 with the idea of making an Autoconf shell script to run M4
25982 and check for unresolved macro calls; Richard Pixley, who suggested
25983 running the compiler instead of searching the file system to find
25984 include files and symbols, for more accurate results; Karl Berry, who
25985 got Autoconf to configure @TeX{} and added the macro index to the
25986 documentation; and Ian Lance Taylor, who added support for creating a C
25987 header file as an alternative to putting @option{-D} options in a
25988 makefile, so he could use Autoconf for his UUCP package.
25989 The alpha testers cheerfully adjusted their files again and again as the
25990 names and calling conventions of the Autoconf macros changed from
25991 release to release.  They all contributed many specific checks, great
25992 ideas, and bug fixes.
25994 @node Numbers
25995 @section Numbers
25997 In July 1992, after months of alpha testing, I released Autoconf 1.0,
25998 and converted many GNU packages to use it.  I was surprised by how
25999 positive the reaction to it was.  More people started using it than I
26000 could keep track of, including people working on software that wasn't
26001 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26002 Autoconf continued to improve rapidly, as many people using the
26003 @command{configure} scripts reported problems they encountered.
26005 Autoconf turned out to be a good torture test for M4 implementations.
26006 Unix M4 started to dump core because of the length of the
26007 macros that Autoconf defined, and several bugs showed up in GNU
26008 M4 as well.  Eventually, we realized that we needed to use some
26009 features that only GNU M4 has.  4.3BSD M4, in
26010 particular, has an impoverished set of builtin macros; the System V
26011 version is better, but still doesn't provide everything we need.
26013 More development occurred as people put Autoconf under more stresses
26014 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26015 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26016 invalid arguments.  Jim Blandy bravely coerced it into configuring
26017 GNU Emacs, laying the groundwork for several later improvements.
26018 Roland McGrath got it to configure the GNU C Library, wrote the
26019 @command{autoheader} script to automate the creation of C header file
26020 templates, and added a @option{--verbose} option to @command{configure}.
26021 Noah Friedman added the @option{--autoconf-dir} option and
26022 @code{AC_MACRODIR} environment variable.  (He also coined the term
26023 @dfn{autoconfiscate} to mean ``adapt a software package to use
26024 Autoconf''.)  Roland and Noah improved the quoting protection in
26025 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26026 dealing with portability problems from February through June, 1993.
26028 @node Deuteronomy
26029 @section Deuteronomy
26031 A long wish list for major features had accumulated, and the effect of
26032 several years of patching by various people had left some residual
26033 cruft.  In April 1994, while working for Cygnus Support, I began a major
26034 revision of Autoconf.  I added most of the features of the Cygnus
26035 @command{configure} that Autoconf had lacked, largely by adapting the
26036 relevant parts of Cygnus @command{configure} with the help of david zuhn
26037 and Ken Raeburn.  These features include support for using
26038 @file{config.sub}, @file{config.guess}, @option{--host}, and
26039 @option{--target}; making links to files; and running @command{configure}
26040 scripts in subdirectories.  Adding these features enabled Ken to convert
26041 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26042 Autoconf.
26044 I added more features in response to other peoples' requests.  Many
26045 people had asked for @command{configure} scripts to share the results of
26046 the checks between runs, because (particularly when configuring a large
26047 source tree, like Cygnus does) they were frustratingly slow.  Mike
26048 Haertel suggested adding site-specific initialization scripts.  People
26049 distributing software that had to unpack on MS-DOS asked for a way to
26050 override the @file{.in} extension on the file names, which produced file
26051 names like @file{config.h.in} containing two dots.  Jim Avera did an
26052 extensive examination of the problems with quoting in @code{AC_DEFINE}
26053 and @code{AC_SUBST}; his insights led to significant improvements.
26054 Richard Stallman asked that compiler output be sent to @file{config.log}
26055 instead of @file{/dev/null}, to help people debug the Emacs
26056 @command{configure} script.
26058 I made some other changes because of my dissatisfaction with the quality
26059 of the program.  I made the messages showing results of the checks less
26060 ambiguous, always printing a result.  I regularized the names of the
26061 macros and cleaned up coding style inconsistencies.  I added some
26062 auxiliary utilities that I had developed to help convert source code
26063 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26064 the macros not interrupt each others' messages.  (That feature revealed
26065 some performance bottlenecks in GNU M4, which he hastily
26066 corrected!)  I reorganized the documentation around problems people want
26067 to solve.  And I began a test suite, because experience had shown that
26068 Autoconf has a pronounced tendency to regress when we change it.
26070 Again, several alpha testers gave invaluable feedback, especially
26071 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26072 and Mark Eichin.
26074 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26075 have free time again.  I think.  Yeah, right.)
26078 @c ========================================================== Appendices
26081 @node GNU Free Documentation License
26082 @appendix GNU Free Documentation License
26084 @include fdl.texi
26086 @node Indices
26087 @appendix Indices
26089 @menu
26090 * Environment Variable Index::  Index of environment variables used
26091 * Output Variable Index::       Index of variables set in output files
26092 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26093 * Cache Variable Index::        Index of documented cache variables
26094 * Autoconf Macro Index::        Index of Autoconf macros
26095 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26096 * Autotest Macro Index::        Index of Autotest macros
26097 * Program & Function Index::    Index of those with portability problems
26098 * Concept Index::               General index
26099 @end menu
26101 @node Environment Variable Index
26102 @appendixsec Environment Variable Index
26104 This is an alphabetical list of the environment variables that might
26105 influence Autoconf checks.
26107 @printindex ev
26109 @node Output Variable Index
26110 @appendixsec Output Variable Index
26112 This is an alphabetical list of the variables that Autoconf can
26113 substitute into files that it creates, typically one or more
26114 makefiles.  @xref{Setting Output Variables}, for more information
26115 on how this is done.
26117 @printindex ov
26119 @node Preprocessor Symbol Index
26120 @appendixsec Preprocessor Symbol Index
26122 This is an alphabetical list of the C preprocessor symbols that the
26123 Autoconf macros define.  To work with Autoconf, C source code needs to
26124 use these names in @code{#if} or @code{#ifdef} directives.
26126 @printindex cv
26128 @node Cache Variable Index
26129 @appendixsec Cache Variable Index
26131 This is an alphabetical list of documented cache variables used
26132 by macros defined in Autoconf.  Autoconf macros may use additional cache
26133 variables internally.
26134 @ifset shortindexflag
26135 To make the list easier to use, the variables are listed without their
26136 preceding @samp{ac_cv_}.
26137 @end ifset
26139 @printindex CA
26141 @node Autoconf Macro Index
26142 @appendixsec Autoconf Macro Index
26144 This is an alphabetical list of the Autoconf macros.
26145 @ifset shortindexflag
26146 To make the list easier to use, the macros are listed without their
26147 preceding @samp{AC_}.
26148 @end ifset
26150 @printindex AC
26152 @node M4 Macro Index
26153 @appendixsec M4 Macro Index
26155 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26156 @ifset shortindexflag
26157 To make the list easier to use, the macros are listed without their
26158 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26159 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26160 names.
26161 @end ifset
26163 @printindex MS
26165 @node Autotest Macro Index
26166 @appendixsec Autotest Macro Index
26168 This is an alphabetical list of the Autotest macros.
26169 @ifset shortindexflag
26170 To make the list easier to use, the macros are listed without their
26171 preceding @samp{AT_}.
26172 @end ifset
26174 @printindex AT
26176 @node Program & Function Index
26177 @appendixsec Program and Function Index
26179 This is an alphabetical list of the programs and functions whose
26180 portability is discussed in this document.
26182 @printindex pr
26184 @node Concept Index
26185 @appendixsec Concept Index
26187 This is an alphabetical list of the files, tools, and concepts
26188 introduced in this document.
26190 @printindex cp
26192 @bye
26194 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26195 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26196 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26197 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26198 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26199 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26200 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26201 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26202 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26203 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26204 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26205 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26206 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26207 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26208 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26209 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26210 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26211 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26212 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26213 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26214 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26215 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26216 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26217 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26218 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26219 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26220 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26221 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26222 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26223 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26224 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26225 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26226 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26227 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26228 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26229 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26230 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26231 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26232 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26233 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26234 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26235 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26236 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26237 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26238 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26239 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
26240 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26241 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26242 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26243 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26244 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26245 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26246 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26247 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26248 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26249 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26250 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26251 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26252 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26253 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26254 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26255 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26256 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26257 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26258 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26259 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26260 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26261 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26262 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26263 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26264 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26265 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26266 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26267 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26268 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26269 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26270 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26271 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26272 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26273 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26274 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26275 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26276 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26277 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26278 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26279 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26280 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26281 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26282 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26283 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26284 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
26285 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26287 @c Local Variables:
26288 @c fill-column: 72
26289 @c ispell-local-dictionary: "american"
26290 @c indent-tabs-mode: nil
26291 @c whitespace-check-buffer-indent: nil
26292 @c End: