doc: emphasize that config.h must be first
[autoconf.git] / doc / autoconf.texi
blobe51032324c6c4e070254708e15fead4c95f81e37
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @documentencoding UTF-8
8 @setchapternewpage odd
9 @finalout
11 @c @ovar(ARG)
12 @c ----------
13 @c The ARG is an optional argument.  To be used for macro arguments in
14 @c their documentation (@defmac).
15 @macro ovar{varname}
16 @r{[}@var{\varname\}@r{]}
17 @end macro
19 @c @dvar(ARG, DEFAULT)
20 @c -------------------
21 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
22 @c for macro arguments in their documentation (@defmac).
23 @macro dvar{varname, default}
24 @r{[}@var{\varname\} = @samp{\default\}@r{]}
25 @end macro
27 @c @dvarv(ARG, DEFAULT-VAR)
28 @c ------------------------
29 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
30 @c around DEFAULT-VAR.
31 @macro dvarv{varname, default}
32 @r{[}@var{\varname\} = @var{\default\}@r{]}@c
33 @end macro
35 @c Handling the indexes with Texinfo yields several different problems.
37 @c Because we want to drop out the AC_ part of the macro names in the
38 @c printed manual, but not in the other outputs, we need a layer above
39 @c the usual @acindex{} etc.  That's why we first define indexes such as
40 @c acx meant to become the macro @acindex.  First of all, using 'ac_'
41 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
42 @c So use something more regular 'acx'.  Then you finish with a printed
43 @c index saying 'index is not existent'.  Of course: you ought to use
44 @c two letters :(  So you use capitals.
46 @c Second, when defining a macro in the TeX world, following spaces are
47 @c eaten.  But then, since we embed @acxindex commands that use the end
48 @c of line as an end marker, the whole things wrecks itself.  So make
49 @c sure you do *force* an additional end of line, add a '@c'.
51 @c Finally, you might want to get rid of TeX expansion, using --expand
52 @c with texi2dvi.  But then you wake up an old problem: we use macros
53 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
55 @c Define an environment variable index, for variables users may set
56 @c in their environment or on the configure command line.
57 @defcodeindex ev
58 @c Define an output variable index, for commonly AC_SUBST'ed variables.
59 @defcodeindex ov
60 @c Define a cache variable index, for variables matching *_cv_*.
61 @defcodeindex CA
62 @c Other shell variables not fitting the above categories should be
63 @c listed in the predefined vrindex, which we merge in the concept index.
64 @syncodeindex vr cp
65 @c Define a CPP preprocessor macro index, for #define'd strings.
66 @defcodeindex cv
67 @c Define an Autoconf macro index that @defmac doesn't write to.
68 @defcodeindex AC
69 @c Define an Autotest macro index that @defmac doesn't write to.
70 @defcodeindex AT
71 @c Define an M4sugar macro index that @defmac doesn't write to.
72 @defcodeindex MS
73 @c Define an index for *foreign* programs: 'mv' etc.  Used for the
74 @c portability sections and so on.
75 @defindex pr
77 @c shortindexflag
78 @c --------------
79 @c Shall we factor AC_ out of the Autoconf macro index etc.?
80 @iftex
81 @set shortindexflag
82 @end iftex
84 @c @acindex{MACRO}
85 @c ---------------
86 @c Registering an AC_\MACRO\.
87 @ifset shortindexflag
88 @macro acindex{macro}
89 @ACindex \macro\
91 @end macro
92 @end ifset
93 @ifclear shortindexflag
94 @macro acindex{macro}
95 @ACindex AC_\macro\
96 @end macro
97 @end ifclear
99 @c @ahindex{MACRO}
100 @c ---------------
101 @c Registering an AH_\MACRO\.
102 @macro ahindex{macro}
103 @ACindex AH_\macro\
105 @end macro
107 @c @asindex{MACRO}
108 @c ---------------
109 @c Registering an AS_\MACRO\.
110 @ifset shortindexflag
111 @macro asindex{macro}
112 @MSindex \macro\
114 @end macro
115 @end ifset
116 @ifclear shortindexflag
117 @macro asindex{macro}
118 @MSindex AS_\macro\
119 @end macro
120 @end ifclear
122 @c @atindex{MACRO}
123 @c ---------------
124 @c Registering an AT_\MACRO\.
125 @ifset shortindexflag
126 @macro atindex{macro}
127 @ATindex \macro\
129 @end macro
130 @end ifset
131 @ifclear shortindexflag
132 @macro atindex{macro}
133 @ATindex AT_\macro\
134 @end macro
135 @end ifclear
137 @c @auindex{MACRO}
138 @c ---------------
139 @c Registering an AU_\MACRO\.
140 @macro auindex{macro}
141 @ACindex AU_\macro\
143 @end macro
145 @c @hdrindex{MACRO}
146 @c ----------------
147 @c Indexing a header.
148 @macro hdrindex{macro}
149 @prindex @file{\macro\}
151 @end macro
153 @c @msindex{MACRO}
154 @c ---------------
155 @c Registering an m4_\MACRO\.
156 @ifset shortindexflag
157 @macro msindex{macro}
158 @MSindex \macro\
160 @end macro
161 @end ifset
162 @ifclear shortindexflag
163 @macro msindex{macro}
164 @MSindex m4_\macro\
165 @end macro
166 @end ifclear
169 @c @caindex{VARIABLE}
170 @c ------------------
171 @c Registering an ac_cv_\VARIABLE\ cache variable.
172 @ifset shortindexflag
173 @macro caindex{macro}
174 @CAindex \macro\
175 @end macro
176 @end ifset
177 @ifclear shortindexflag
178 @macro caindex{macro}
179 @CAindex ac_cv_\macro\
180 @end macro
181 @end ifclear
183 @c Define an index for functions: `alloca' etc.  Used for the
184 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
185 @c since `@defmac' goes into it => we'd get all the macros too.
187 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
189 @c   ! No room for a new @write .
190 @c   l.112 @defcodeindex fu
192 @c   so don't define yet another one :(  Just put some tags before each
193 @c   @prindex which is actually a @funindex.
195 @c   @defcodeindex fu
198 @c   @c Put the programs and functions into their own index.
199 @c   @syncodeindex fu pr
201 @comment %**end of header
202 @comment ========================================================
204 @copying
206 This manual (@value{UPDATED}) is for GNU Autoconf
207 (version @value{VERSION}),
208 a package for creating scripts to configure source code packages using
209 templates and an M4 macro package.
211 Copyright @copyright{} 1992--1996, 1998--2017 Free Software Foundation,
212 Inc.
214 @quotation
215 Permission is granted to copy, distribute and/or modify this document
216 under the terms of the GNU Free Documentation License,
217 Version 1.3 or any later version published by the Free Software
218 Foundation; with no Invariant Sections, no Front-Cover texts, and
219 no Back-Cover Texts.  A copy of the license is included in the section
220 entitled ``GNU Free Documentation License.''
221 @end quotation
222 @end copying
226 @dircategory Software development
227 @direntry
228 * Autoconf: (autoconf).         Create source code configuration scripts.
229 @end direntry
231 @dircategory Individual utilities
232 @direntry
233 * autoscan: (autoconf)autoscan Invocation.
234                                 Semi-automatic @file{configure.ac} writing
235 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
236 * autoconf-invocation: (autoconf)autoconf Invocation.
237                                 How to create configuration scripts
238 * autoreconf: (autoconf)autoreconf Invocation.
239                                 Remaking multiple @command{configure} scripts
240 * autoheader: (autoconf)autoheader Invocation.
241                                 How to create configuration templates
242 * autom4te: (autoconf)autom4te Invocation.
243                                 The Autoconf executables backbone
244 * configure: (autoconf)configure Invocation.    Configuring a package.
245 * autoupdate: (autoconf)autoupdate Invocation.
246                                 Automatic update of @file{configure.ac}
247 * config.status: (autoconf)config.status Invocation. Recreating configurations.
248 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
249 @end direntry
251 @titlepage
252 @title Autoconf
253 @subtitle Creating Automatic Configuration Scripts
254 @subtitle for version @value{VERSION}, @value{UPDATED}
255 @author David MacKenzie
256 @author Ben Elliston
257 @author Akim Demaille
258 @page
259 @vskip 0pt plus 1filll
260 @insertcopying
261 @end titlepage
263 @contents
266 @ifnottex
267 @node Top
268 @top Autoconf
269 @insertcopying
270 @end ifnottex
272 @c The master menu, created with texinfo-master-menu, goes here.
274 @menu
275 * Introduction::                Autoconf's purpose, strengths, and weaknesses
276 * The GNU Build System::        A set of tools for portable software packages
277 * Making configure Scripts::    How to organize and produce Autoconf scripts
278 * Setup::                       Initialization and output
279 * Existing Tests::              Macros that check for particular features
280 * Writing Tests::               How to write new feature checks
281 * Results::                     What to do with results from feature checks
282 * Programming in M4::           Layers on top of which Autoconf is written
283 * Programming in M4sh::         Shell portability layer
284 * Writing Autoconf Macros::     Adding new macros to Autoconf
285 * Portable Shell::              Shell script portability pitfalls
286 * Portable Make::               Makefile portability pitfalls
287 * Portable C and C++::          C and C++ portability pitfalls
288 * Manual Configuration::        Selecting features that can't be guessed
289 * Site Configuration::          Local defaults for @command{configure}
290 * Running configure Scripts::   How to use the Autoconf output
291 * config.status Invocation::    Recreating a configuration
292 * Obsolete Constructs::         Kept for backward compatibility
293 * Using Autotest::              Creating portable test suites
294 * FAQ::                         Frequent Autoconf Questions, with answers
295 * History::                     History of Autoconf
296 * GNU Free Documentation License::  License for copying this manual
297 * Indices::                     Indices of symbols, concepts, etc.
299 @detailmenu
300  --- The Detailed Node Listing ---
302 The GNU Build System
304 * Automake::                    Escaping makefile hell
305 * Gnulib::                      The GNU portability library
306 * Libtool::                     Building libraries portably
307 * Pointers::                    More info on the GNU build system
309 Making @command{configure} Scripts
311 * Writing Autoconf Input::      What to put in an Autoconf input file
312 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
313 * ifnames Invocation::          Listing the conditionals in source code
314 * autoconf Invocation::         How to create configuration scripts
315 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
317 Writing @file{configure.ac}
319 * Shell Script Compiler::       Autoconf as solution of a problem
320 * Autoconf Language::           Programming in Autoconf
321 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
323 Initialization and Output Files
325 * Initializing configure::      Option processing etc.
326 * Versioning::                  Dealing with Autoconf versions
327 * Notices::                     Copyright, version numbers in @command{configure}
328 * Input::                       Where Autoconf should find files
329 * Output::                      Outputting results from the configuration
330 * Configuration Actions::       Preparing the output based on results
331 * Configuration Files::         Creating output files
332 * Makefile Substitutions::      Using output variables in makefiles
333 * Configuration Headers::       Creating a configuration header file
334 * Configuration Commands::      Running arbitrary instantiation commands
335 * Configuration Links::         Links depending on the configuration
336 * Subdirectories::              Configuring independent packages together
337 * Default Prefix::              Changing the default installation prefix
339 Substitutions in Makefiles
341 * Preset Output Variables::     Output variables that are always set
342 * Installation Directory Variables::  Other preset output variables
343 * Changed Directory Variables::  Warnings about @file{datarootdir}
344 * Build Directories::           Supporting multiple concurrent compiles
345 * Automatic Remaking::          Makefile rules for configuring
347 Configuration Header Files
349 * Header Templates::            Input for the configuration headers
350 * autoheader Invocation::       How to create configuration templates
351 * Autoheader Macros::           How to specify CPP templates
353 Existing Tests
355 * Common Behavior::             Macros' standard schemes
356 * Alternative Programs::        Selecting between alternative programs
357 * Files::                       Checking for the existence of files
358 * Libraries::                   Library archives that might be missing
359 * Library Functions::           C library functions that might be missing
360 * Header Files::                Header files that might be missing
361 * Declarations::                Declarations that may be missing
362 * Structures::                  Structures or members that might be missing
363 * Types::                       Types that might be missing
364 * Compilers and Preprocessors::  Checking for compiling programs
365 * System Services::             Operating system services
366 * C and Posix Variants::        Kludges for C and Posix variants
367 * Erlang Libraries::            Checking for the existence of Erlang libraries
369 Common Behavior
371 * Standard Symbols::            Symbols defined by the macros
372 * Default Includes::            Includes used by the generic macros
374 Alternative Programs
376 * Particular Programs::         Special handling to find certain programs
377 * Generic Programs::            How to find other programs
379 Library Functions
381 * Function Portability::        Pitfalls with usual functions
382 * Particular Functions::        Special handling to find certain functions
383 * Generic Functions::           How to find other functions
385 Header Files
387 * Header Portability::          Collected knowledge on common headers
388 * Particular Headers::          Special handling to find certain headers
389 * Generic Headers::             How to find other headers
391 Declarations
393 * Particular Declarations::     Macros to check for certain declarations
394 * Generic Declarations::        How to find other declarations
396 Structures
398 * Particular Structures::       Macros to check for certain structure members
399 * Generic Structures::          How to find other structure members
401 Types
403 * Particular Types::            Special handling to find certain types
404 * Generic Types::               How to find other types
406 Compilers and Preprocessors
408 * Specific Compiler Characteristics::  Some portability issues
409 * Generic Compiler Characteristics::  Language independent tests and features
410 * C Compiler::                  Checking its characteristics
411 * C++ Compiler::                Likewise
412 * Objective C Compiler::        Likewise
413 * Objective C++ Compiler::      Likewise
414 * Erlang Compiler and Interpreter::  Likewise
415 * Fortran Compiler::            Likewise
416 * Go Compiler::                 Likewise
418 Writing Tests
420 * Language Choice::             Selecting which language to use for testing
421 * Writing Test Programs::       Forging source files for compilers
422 * Running the Preprocessor::    Detecting preprocessor symbols
423 * Running the Compiler::        Detecting language or header features
424 * Running the Linker::          Detecting library features
425 * Runtime::                     Testing for runtime features
426 * Systemology::                 A zoology of operating systems
427 * Multiple Cases::              Tests for several possible values
429 Writing Test Programs
431 * Guidelines::                  General rules for writing test programs
432 * Test Functions::              Avoiding pitfalls in test programs
433 * Generating Sources::          Source program boilerplate
435 Results of Tests
437 * Defining Symbols::            Defining C preprocessor symbols
438 * Setting Output Variables::    Replacing variables in output files
439 * Special Chars in Variables::  Characters to beware of in variables
440 * Caching Results::             Speeding up subsequent @command{configure} runs
441 * Printing Messages::           Notifying @command{configure} users
443 Caching Results
445 * Cache Variable Names::        Shell variables used in caches
446 * Cache Files::                 Files @command{configure} uses for caching
447 * Cache Checkpointing::         Loading and saving the cache file
449 Programming in M4
451 * M4 Quotation::                Protecting macros from unwanted expansion
452 * Using autom4te::              The Autoconf executables backbone
453 * Programming in M4sugar::      Convenient pure M4 macros
454 * Debugging via autom4te::      Figuring out what M4 was doing
456 M4 Quotation
458 * Active Characters::           Characters that change the behavior of M4
459 * One Macro Call::              Quotation and one macro call
460 * Quoting and Parameters::      M4 vs. shell parameters
461 * Quotation and Nested Macros::  Macros calling macros
462 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
463 * Quadrigraphs::                Another way to escape special characters
464 * Balancing Parentheses::       Dealing with unbalanced parentheses
465 * Quotation Rule Of Thumb::     One parenthesis, one quote
467 Using @command{autom4te}
469 * autom4te Invocation::         A GNU M4 wrapper
470 * Customizing autom4te::        Customizing the Autoconf package
472 Programming in M4sugar
474 * Redefined M4 Macros::         M4 builtins changed in M4sugar
475 * Diagnostic Macros::           Diagnostic messages from M4sugar
476 * Diversion support::           Diversions in M4sugar
477 * Conditional constructs::      Conditions in M4
478 * Looping constructs::          Iteration in M4
479 * Evaluation Macros::           More quotation and evaluation control
480 * Text processing Macros::      String manipulation in M4
481 * Number processing Macros::    Arithmetic computation in M4
482 * Set manipulation Macros::     Set manipulation in M4
483 * Forbidden Patterns::          Catching unexpanded macros
485 Programming in M4sh
487 * Common Shell Constructs::     Portability layer for common shell constructs
488 * Polymorphic Variables::       Support for indirect variable names
489 * Initialization Macros::       Macros to establish a sane shell environment
490 * File Descriptor Macros::      File descriptor macros for input and output
492 Writing Autoconf Macros
494 * Macro Definitions::           Basic format of an Autoconf macro
495 * Macro Names::                 What to call your new macros
496 * Reporting Messages::          Notifying @command{autoconf} users
497 * Dependencies Between Macros::  What to do when macros depend on other macros
498 * Obsoleting Macros::           Warning about old ways of doing things
499 * Coding Style::                Writing Autoconf macros @`a la Autoconf
501 Dependencies Between Macros
503 * Prerequisite Macros::         Ensuring required information
504 * Suggested Ordering::          Warning about possible ordering problems
505 * One-Shot Macros::             Ensuring a macro is called only once
507 Portable Shell Programming
509 * Shellology::                  A zoology of shells
510 * Invoking the Shell::          Invoking the shell as a command
511 * Here-Documents::              Quirks and tricks
512 * File Descriptors::            FDs and redirections
513 * Signal Handling::             Shells, signals, and headaches
514 * File System Conventions::     File names
515 * Shell Pattern Matching::      Pattern matching
516 * Shell Substitutions::         Variable and command expansions
517 * Assignments::                 Varying side effects of assignments
518 * Parentheses::                 Parentheses in shell scripts
519 * Slashes::                     Slashes in shell scripts
520 * Special Shell Variables::     Variables you should not change
521 * Shell Functions::             What to look out for if you use them
522 * Limitations of Builtins::     Portable use of not so portable /bin/sh
523 * Limitations of Usual Tools::  Portable use of portable tools
525 Portable Make Programming
527 * $< in Ordinary Make Rules::   $< in ordinary rules
528 * Failure in Make Rules::       Failing portably in rules
529 * Special Chars in Names::      Special Characters in Macro Names
530 * Backslash-Newline-Empty::     Empty lines after backslash-newline
531 * Backslash-Newline Comments::  Spanning comments across line boundaries
532 * Long Lines in Makefiles::     Line length limitations
533 * Macros and Submakes::         @code{make macro=value} and submakes
534 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
535 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
536 * Parallel Make::               Parallel @command{make} quirks
537 * Comments in Make Rules::      Other problems with Make comments
538 * Newlines in Make Rules::      Using literal newlines in rules
539 * Comments in Make Macros::     Other problems with Make comments in macros
540 * Trailing whitespace in Make Macros::  Macro substitution problems
541 * Command-line Macros and whitespace::  Whitespace trimming of values
542 * obj/ and Make::               Don't name a subdirectory @file{obj}
543 * make -k Status::              Exit status of @samp{make -k}
544 * VPATH and Make::              @code{VPATH} woes
545 * Single Suffix Rules::         Single suffix rules and separated dependencies
546 * Timestamps and Make::         Subsecond timestamp resolution
548 @code{VPATH} and Make
550 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
551 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
552 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
553 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
554 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
555 * Make Target Lookup::          More details about @code{VPATH} lookup
557 Portable C and C++ Programming
559 * Varieties of Unportability::  How to make your programs unportable
560 * Integer Overflow::            When integers get too large
561 * Preprocessor Arithmetic::     @code{#if} expression problems
562 * Null Pointers::               Properties of null pointers
563 * Buffer Overruns::             Subscript errors and the like
564 * Volatile Objects::            @code{volatile} and signals
565 * Floating Point Portability::  Portable floating-point arithmetic
566 * Exiting Portably::            Exiting and the exit status
568 Integer Overflow
570 * Integer Overflow Basics::     Why integer overflow is a problem
571 * Signed Overflow Examples::    Examples of code assuming wraparound
572 * Optimization and Wraparound::  Optimizations that break uses of wraparound
573 * Signed Overflow Advice::      Practical advice for signed overflow issues
574 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
576 Manual Configuration
578 * Specifying Target Triplets::  Specifying target triplets
579 * Canonicalizing::              Getting the canonical system type
580 * Using System Type::           What to do with the system type
582 Site Configuration
584 * Help Formatting::             Customizing @samp{configure --help}
585 * External Software::           Working with other optional software
586 * Package Options::             Selecting optional features
587 * Pretty Help Strings::         Formatting help string
588 * Option Checking::             Controlling checking of @command{configure} options
589 * Site Details::                Configuring site details
590 * Transforming Names::          Changing program names when installing
591 * Site Defaults::               Giving @command{configure} local defaults
593 Transforming Program Names When Installing
595 * Transformation Options::      @command{configure} options to transform names
596 * Transformation Examples::     Sample uses of transforming names
597 * Transformation Rules::        Makefile uses of transforming names
599 Running @command{configure} Scripts
601 * Basic Installation::          Instructions for typical cases
602 * Compilers and Options::       Selecting compilers and optimization
603 * Multiple Architectures::      Compiling for multiple architectures at once
604 * Installation Names::          Installing in different directories
605 * Optional Features::           Selecting optional features
606 * Particular Systems::          Particular systems
607 * System Type::                 Specifying the system type
608 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
609 * Defining Variables::          Specifying the compiler etc.
610 * configure Invocation::        Changing how @command{configure} runs
612 Obsolete Constructs
614 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
615 * acconfig Header::             Additional entries in @file{config.h.in}
616 * autoupdate Invocation::       Automatic update of @file{configure.ac}
617 * Obsolete Macros::             Backward compatibility macros
618 * Autoconf 1::                  Tips for upgrading your files
619 * Autoconf 2.13::               Some fresher tips
621 Upgrading From Version 1
623 * Changed File Names::          Files you might rename
624 * Changed Makefiles::           New things to put in @file{Makefile.in}
625 * Changed Macros::              Macro calls you might replace
626 * Changed Results::             Changes in how to check test results
627 * Changed Macro Writing::       Better ways to write your own macros
629 Upgrading From Version 2.13
631 * Changed Quotation::           Broken code which used to work
632 * New Macros::                  Interaction with foreign macros
633 * Hosts and Cross-Compilation::  Bugward compatibility kludges
634 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
635 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
637 Generating Test Suites with Autotest
639 * Using an Autotest Test Suite::  Autotest and the user
640 * Writing Testsuites::          Autotest macros
641 * testsuite Invocation::        Running @command{testsuite} scripts
642 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
644 Using an Autotest Test Suite
646 * testsuite Scripts::           The concepts of Autotest
647 * Autotest Logs::               Their contents
649 Frequent Autoconf Questions, with answers
651 * Distributing::                Distributing @command{configure} scripts
652 * Why GNU M4::                  Why not use the standard M4?
653 * Bootstrapping::               Autoconf and GNU M4 require each other?
654 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
655 * Defining Directories::        Passing @code{datadir} to program
656 * Autom4te Cache::              What is it?  Can I remove it?
657 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
658 * Expanded Before Required::    Expanded Before Required
659 * Debugging::                   Debugging @command{configure} scripts
661 History of Autoconf
663 * Genesis::                     Prehistory and naming of @command{configure}
664 * Exodus::                      The plagues of M4 and Perl
665 * Leviticus::                   The priestly code of portability arrives
666 * Numbers::                     Growth and contributors
667 * Deuteronomy::                 Approaching the promises of easy configuration
669 Indices
671 * Environment Variable Index::  Index of environment variables used
672 * Output Variable Index::       Index of variables set in output files
673 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
674 * Cache Variable Index::        Index of documented cache variables
675 * Autoconf Macro Index::        Index of Autoconf macros
676 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
677 * Autotest Macro Index::        Index of Autotest macros
678 * Program & Function Index::    Index of those with portability problems
679 * Concept Index::               General index
681 @end detailmenu
682 @end menu
684 @c ============================================================= Introduction.
686 @node Introduction
687 @chapter Introduction
688 @cindex Introduction
690 @flushright
691 A physicist, an engineer, and a computer scientist were discussing the
692 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
693 early in the Creation, God made Light; and you know, Maxwell's
694 equations, the dual nature of electromagnetic waves, the relativistic
695 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
696 before making Light, God split the Chaos into Land and Water; it takes
697 a hell of an engineer to handle that big amount of mud, and orderly
698 separation of solids from liquids@enddots{}'' The computer scientist
699 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
701 ---Anonymous
702 @end flushright
703 @c (via Franc,ois Pinard)
705 Autoconf is a tool for producing shell scripts that automatically
706 configure software source code packages to adapt to many kinds of
707 Posix-like systems.  The configuration scripts produced by Autoconf
708 are independent of Autoconf when they are run, so their users do not
709 need to have Autoconf.
711 The configuration scripts produced by Autoconf require no manual user
712 intervention when run; they do not normally even need an argument
713 specifying the system type.  Instead, they individually test for the
714 presence of each feature that the software package they are for might need.
715 (Before each check, they print a one-line message stating what they are
716 checking for, so the user doesn't get too bored while waiting for the
717 script to finish.)  As a result, they deal well with systems that are
718 hybrids or customized from the more common Posix variants.  There is
719 no need to maintain files that list the features supported by each
720 release of each variant of Posix.
722 For each software package that Autoconf is used with, it creates a
723 configuration script from a template file that lists the system features
724 that the package needs or can use.  After the shell code to recognize
725 and respond to a system feature has been written, Autoconf allows it to
726 be shared by many software packages that can use (or need) that feature.
727 If it later turns out that the shell code needs adjustment for some
728 reason, it needs to be changed in only one place; all of the
729 configuration scripts can be regenerated automatically to take advantage
730 of the updated code.
732 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
733 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
734 Those who do not understand Autoconf are condemned to reinvent it, poorly.
735 The primary goal of Autoconf is making the @emph{user's} life easier;
736 making the @emph{maintainer's} life easier is only a secondary goal.
737 Put another way, the primary goal is not to make the generation of
738 @file{configure} automatic for package maintainers (although patches
739 along that front are welcome, since package maintainers form the user
740 base of Autoconf); rather, the goal is to make @file{configure}
741 painless, portable, and predictable for the end user of each
742 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
743 successful at its goal---most complaints to the Autoconf list are
744 about difficulties in writing Autoconf input, and not in the behavior of
745 the resulting @file{configure}.  Even packages that don't use Autoconf
746 will generally provide a @file{configure} script, and the most common
747 complaint about these alternative home-grown scripts is that they fail
748 to meet one or more of the GNU Coding Standards (@pxref{Configuration, , ,
749 standards, The GNU Coding Standards}) that users
750 have come to expect from Autoconf-generated @file{configure} scripts.
752 The Metaconfig package is similar in purpose to Autoconf, but the
753 scripts it produces require manual user intervention, which is quite
754 inconvenient when configuring large source trees.  Unlike Metaconfig
755 scripts, Autoconf scripts can support cross-compiling, if some care is
756 taken in writing them.
758 Autoconf does not solve all problems related to making portable
759 software packages---for a more complete solution, it should be used in
760 concert with other GNU build tools like Automake and
761 Libtool.  These other tools take on jobs like the creation of a
762 portable, recursive makefile with all of the standard targets,
763 linking of shared libraries, and so on.  @xref{The GNU Build System},
764 for more information.
766 Autoconf imposes some restrictions on the names of macros used with
767 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
769 Autoconf requires GNU M4 version 1.4.6 or later in order to
770 generate the scripts.  It uses features that some versions of M4,
771 including GNU M4 1.3, do not have.  Autoconf works better
772 with GNU M4 version 1.4.14 or later, though this is not
773 required.
775 @xref{Autoconf 1}, for information about upgrading from version 1.
776 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
777 for answers to some common questions about Autoconf.
779 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
780 Autoconf web page} for up-to-date information, details on the mailing
781 lists, pointers to a list of known bugs, etc.
783 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
784 list}.  Past suggestions are
785 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
787 Mail bug reports to @email{bug-autoconf@@gnu.org, the
788 Autoconf Bugs mailing list}.  Past bug reports are
789 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
791 If possible, first check that your bug is
792 not already solved in current development versions, and that it has not
793 been reported yet.  Be sure to include all the needed information and a
794 short @file{configure.ac} that demonstrates the problem.
796 Autoconf's development tree is accessible via @command{git}; see the
797 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
798 Summary} for details, or view
799 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
800 repository}.  Anonymous CVS access is also available, see
801 @file{README} for more details.  Patches relative to the
802 current @command{git} version can be sent for review to the
803 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
804 discussion on prior patches
805 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
806 archived}; and all commits are posted in the read-only
807 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
808 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
809 archived}.
811 Because of its mission, the Autoconf package itself
812 includes only a set of often-used
813 macros that have already demonstrated their usefulness.  Nevertheless,
814 if you wish to share your macros, or find existing ones, see the
815 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
816 Archive}, which is kindly run by @email{simons@@cryp.to,
817 Peter Simons}.
820 @c ================================================= The GNU Build System
822 @node The GNU Build System
823 @chapter The GNU Build System
824 @cindex GNU build system
826 Autoconf solves an important problem---reliable discovery of
827 system-specific build and runtime information---but this is only one
828 piece of the puzzle for the development of portable software.  To this
829 end, the GNU project has developed a suite of integrated
830 utilities to finish the job Autoconf started: the GNU build
831 system, whose most important components are Autoconf, Automake, and
832 Libtool.  In this chapter, we introduce you to those tools, point you
833 to sources of more information, and try to convince you to use the
834 entire GNU build system for your software.
836 @menu
837 * Automake::                    Escaping makefile hell
838 * Gnulib::                      The GNU portability library
839 * Libtool::                     Building libraries portably
840 * Pointers::                    More info on the GNU build system
841 @end menu
843 @node Automake
844 @section Automake
846 The ubiquity of @command{make} means that a makefile is almost the
847 only viable way to distribute automatic build rules for software, but
848 one quickly runs into its numerous limitations.  Its lack of
849 support for automatic dependency tracking, recursive builds in
850 subdirectories, reliable timestamps (e.g., for network file systems), and
851 so on, mean that developers must painfully (and often incorrectly)
852 reinvent the wheel for each project.  Portability is non-trivial, thanks
853 to the quirks of @command{make} on many systems.  On top of all this is the
854 manual labor required to implement the many standard targets that users
855 have come to expect (@code{make install}, @code{make distclean},
856 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
857 you also have to insert repetitive code in your @file{Makefile.in} to
858 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
859 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
860 @cindex Automake
862 Automake allows you to specify your build needs in a @file{Makefile.am}
863 file with a vastly simpler and more powerful syntax than that of a plain
864 makefile, and then generates a portable @file{Makefile.in} for
865 use with Autoconf.  For example, the @file{Makefile.am} to build and
866 install a simple ``Hello world'' program might look like:
868 @example
869 bin_PROGRAMS = hello
870 hello_SOURCES = hello.c
871 @end example
873 @noindent
874 The resulting @file{Makefile.in} (~400 lines) automatically supports all
875 the standard targets, the substitutions provided by Autoconf, automatic
876 dependency tracking, @code{VPATH} building, and so on.  @command{make}
877 builds the @code{hello} program, and @code{make install} installs it
878 in @file{/usr/local/bin} (or whatever prefix was given to
879 @command{configure}, if not @file{/usr/local}).
881 The benefits of Automake increase for larger packages (especially ones
882 with subdirectories), but even for small programs the added convenience
883 and portability can be substantial.  And that's not all@enddots{}
885 @node Gnulib
886 @section Gnulib
888 GNU software has a well-deserved reputation for running on
889 many different types of systems.  While our primary goal is to write
890 software for the GNU system, many users and developers have
891 been introduced to us through the systems that they were already using.
893 @cindex Gnulib
894 Gnulib is a central location for common GNU code, intended to
895 be shared among free software packages.  Its components are typically
896 shared at the source level, rather than being a library that gets built,
897 installed, and linked against.  The idea is to copy files from Gnulib
898 into your own source tree.  There is no distribution tarball; developers
899 should just grab source modules from the repository.  The source files
900 are available online, under various licenses, mostly GNU
901 GPL or GNU LGPL.
903 Gnulib modules typically contain C source code along with Autoconf
904 macros used to configure the source code.  For example, the Gnulib
905 @code{stdalign} module implements a @file{stdalign.h} header that nearly
906 conforms to C11, even on old-fashioned hosts that lack @file{stdalign.h}.
907 This module contains a source file for the replacement header, along
908 with an Autoconf macro that arranges to use the replacement header on
909 old-fashioned systems.
911 @node Libtool
912 @section Libtool
914 Often, one wants to build not only programs, but libraries, so that
915 other programs can benefit from the fruits of your labor.  Ideally, one
916 would like to produce @emph{shared} (dynamically linked) libraries,
917 which can be used by multiple programs without duplication on disk or in
918 memory and can be updated independently of the linked programs.
919 Producing shared libraries portably, however, is the stuff of
920 nightmares---each system has its own incompatible tools, compiler flags,
921 and magic incantations.  Fortunately, GNU provides a solution:
922 @dfn{Libtool}.
923 @cindex Libtool
925 Libtool handles all the requirements of building shared libraries for
926 you, and at this time seems to be the @emph{only} way to do so with any
927 portability.  It also handles many other headaches, such as: the
928 interaction of Make rules with the variable suffixes of
929 shared libraries, linking reliably with shared libraries before they are
930 installed by the superuser, and supplying a consistent versioning system
931 (so that different versions of a library can be installed or upgraded
932 without breaking binary compatibility).  Although Libtool, like
933 Autoconf, can be used without Automake, it is most simply utilized in
934 conjunction with Automake---there, Libtool is used automatically
935 whenever shared libraries are needed, and you need not know its syntax.
937 @node Pointers
938 @section Pointers
940 Developers who are used to the simplicity of @command{make} for small
941 projects on a single system might be daunted at the prospect of
942 learning to use Automake and Autoconf.  As your software is
943 distributed to more and more users, however, you otherwise
944 quickly find yourself putting lots of effort into reinventing the
945 services that the GNU build tools provide, and making the
946 same mistakes that they once made and overcame.  (Besides, since
947 you're already learning Autoconf, Automake is a piece of cake.)
949 There are a number of places that you can go to for more information on
950 the GNU build tools.
952 @itemize @minus
954 @item Web
956 The project home pages for
957 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
958 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
959 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
960 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
962 @item Automake Manual
964 @xref{Top, , Automake, automake, GNU Automake}, for more
965 information on Automake.
967 @item Books
969 The book @cite{GNU Autoconf, Automake and
970 Libtool}@footnote{@cite{GNU Autoconf, Automake and Libtool},
971 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
972 New Riders), 2000, ISBN 1578701902.} describes the complete GNU
973 build environment.  You can also find
974 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
976 @end itemize
978 @c ================================================= Making configure Scripts.
980 @node Making configure Scripts
981 @chapter Making @command{configure} Scripts
982 @cindex @file{aclocal.m4}
983 @cindex @command{configure}
985 The configuration scripts that Autoconf produces are by convention
986 called @command{configure}.  When run, @command{configure} creates several
987 files, replacing configuration parameters in them with appropriate
988 values.  The files that @command{configure} creates are:
990 @itemize @minus
991 @item
992 one or more @file{Makefile} files, usually one in each subdirectory of the
993 package (@pxref{Makefile Substitutions});
995 @item
996 optionally, a C header file, the name of which is configurable,
997 containing @code{#define} directives (@pxref{Configuration Headers});
999 @item
1000 a shell script called @file{config.status} that, when run, recreates
1001 the files listed above (@pxref{config.status Invocation});
1003 @item
1004 an optional shell script normally called @file{config.cache}
1005 (created when using @samp{configure --config-cache}) that
1006 saves the results of running many of the tests (@pxref{Cache Files});
1008 @item
1009 a file called @file{config.log} containing any messages produced by
1010 compilers, to help debugging if @command{configure} makes a mistake.
1011 @end itemize
1013 @cindex @file{configure.ac}
1014 To create a @command{configure} script with Autoconf, you need
1015 to write an Autoconf input file @file{configure.ac} and run
1016 @command{autoconf} on it.  If you write your own feature tests to
1017 supplement those that come with Autoconf, you might also write files
1018 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
1019 file to contain @code{#define} directives, you might also run
1020 @command{autoheader}, and you can distribute the generated file
1021 @file{config.h.in} with the package.
1023 Here is a diagram showing how the files that can be used in
1024 configuration are produced.  Programs that are executed are suffixed by
1025 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
1026 @command{autoconf} and @command{autoheader} also read the installed Autoconf
1027 macro files (by reading @file{autoconf.m4}).
1029 @noindent
1030 Files used in preparing a software package for distribution, when using
1031 just Autoconf:
1032 @example
1033 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
1035 @group
1036 configure.ac --.
1037                |   .------> autoconf* -----> configure
1038 [aclocal.m4] --+---+
1039                |   `-----> [autoheader*] --> [config.h.in]
1040 [acsite.m4] ---'
1041 @end group
1043 Makefile.in
1044 @end example
1046 @noindent
1047 Additionally, if you use Automake, the following additional productions
1048 come into play:
1050 @example
1051 @group
1052 [acinclude.m4] --.
1053                  |
1054 [local macros] --+--> aclocal* --> aclocal.m4
1055                  |
1056 configure.ac ----'
1057 @end group
1059 @group
1060 configure.ac --.
1061                +--> automake* --> Makefile.in
1062 Makefile.am ---'
1063 @end group
1064 @end example
1066 @noindent
1067 Files used in configuring a software package:
1068 @example
1069 @group
1070                        .-------------> [config.cache]
1071 configure* ------------+-------------> config.log
1072                        |
1073 [config.h.in] -.       v            .-> [config.h] -.
1074                +--> config.status* -+               +--> make*
1075 Makefile.in ---'                    `-> Makefile ---'
1076 @end group
1077 @end example
1079 @menu
1080 * Writing Autoconf Input::      What to put in an Autoconf input file
1081 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1082 * ifnames Invocation::          Listing the conditionals in source code
1083 * autoconf Invocation::         How to create configuration scripts
1084 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1085 @end menu
1087 @node Writing Autoconf Input
1088 @section Writing @file{configure.ac}
1090 To produce a @command{configure} script for a software package, create a
1091 file called @file{configure.ac} that contains invocations of the
1092 Autoconf macros that test the system features your package needs or can
1093 use.  Autoconf macros already exist to check for many features; see
1094 @ref{Existing Tests}, for their descriptions.  For most other features,
1095 you can use Autoconf template macros to produce custom checks; see
1096 @ref{Writing Tests}, for information about them.  For especially tricky
1097 or specialized features, @file{configure.ac} might need to contain some
1098 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1099 Programming}.  The @command{autoscan} program can give you a good start
1100 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1101 information).
1103 @cindex @file{configure.in}
1104 Previous versions of Autoconf promoted the name @file{configure.in},
1105 which is somewhat ambiguous (the tool needed to process this file is not
1106 described by its extension), and introduces a slight confusion with
1107 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1108 processed by @command{configure}'').  Using @file{configure.ac} is now
1109 preferred, while the use of @file{configure.in} will cause warnings
1110 from @command{autoconf}.
1112 @menu
1113 * Shell Script Compiler::       Autoconf as solution of a problem
1114 * Autoconf Language::           Programming in Autoconf
1115 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1116 @end menu
1118 @node Shell Script Compiler
1119 @subsection A Shell Script Compiler
1121 Just as for any other computer language, in order to properly program
1122 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1123 the language tries to address and @emph{how} it does so.
1125 The problem Autoconf addresses is that the world is a mess.  After all,
1126 you are using Autoconf in order to have your package compile easily on
1127 all sorts of different systems, some of them being extremely hostile.
1128 Autoconf itself bears the price for these differences: @command{configure}
1129 must run on all those systems, and thus @command{configure} must limit itself
1130 to their lowest common denominator of features.
1132 Naturally, you might then think of shell scripts; who needs
1133 @command{autoconf}?  A set of properly written shell functions is enough to
1134 make it easy to write @command{configure} scripts by hand.  Sigh!
1135 Unfortunately, even in 2008, where shells without any function support are
1136 far and few between, there are pitfalls to avoid when making use of them.
1137 Also, finding a Bourne shell that accepts shell functions is not trivial,
1138 even though there is almost always one on interesting porting targets.
1140 So, what is really needed is some kind of compiler, @command{autoconf},
1141 that takes an Autoconf program, @file{configure.ac}, and transforms it
1142 into a portable shell script, @command{configure}.
1144 How does @command{autoconf} perform this task?
1146 There are two obvious possibilities: creating a brand new language or
1147 extending an existing one.  The former option is attractive: all
1148 sorts of optimizations could easily be implemented in the compiler and
1149 many rigorous checks could be performed on the Autoconf program
1150 (e.g., rejecting any non-portable construct).  Alternatively, you can
1151 extend an existing language, such as the @code{sh} (Bourne shell)
1152 language.
1154 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1155 therefore most convenient to implement @command{autoconf} as a macro
1156 expander: a program that repeatedly performs @dfn{macro expansions} on
1157 text input, replacing macro calls with macro bodies and producing a pure
1158 @code{sh} script in the end.  Instead of implementing a dedicated
1159 Autoconf macro expander, it is natural to use an existing
1160 general-purpose macro language, such as M4, and implement the extensions
1161 as a set of M4 macros.
1164 @node Autoconf Language
1165 @subsection The Autoconf Language
1166 @cindex quotation
1168 The Autoconf language differs from many other computer
1169 languages because it treats actual code the same as plain text.  Whereas
1170 in C, for instance, data and instructions have different syntactic
1171 status, in Autoconf their status is rigorously the same.  Therefore, we
1172 need a means to distinguish literal strings from text to be expanded:
1173 quotation.
1175 When calling macros that take arguments, there must not be any white
1176 space between the macro name and the open parenthesis.
1178 @example
1179 AC_INIT ([oops], [1.0]) # incorrect
1180 AC_INIT([hello], [1.0]) # good
1181 @end example
1183 Arguments should
1184 be enclosed within the quote characters @samp{[} and @samp{]}, and be
1185 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1186 unless they are quoted.  You should always quote an argument that
1187 might contain a macro name, comma, parenthesis, or a leading blank or
1188 newline.  This rule applies recursively for every macro
1189 call, including macros called from other macros.  For more details on
1190 quoting rules, see @ref{Programming in M4}.
1192 For instance:
1194 @example
1195 AC_CHECK_HEADER([stdio.h],
1196                 [AC_DEFINE([HAVE_STDIO_H], [1],
1197                    [Define to 1 if you have <stdio.h>.])],
1198                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1199 @end example
1201 @noindent
1202 is quoted properly.  You may safely simplify its quotation to:
1204 @example
1205 AC_CHECK_HEADER([stdio.h],
1206                 [AC_DEFINE([HAVE_STDIO_H], 1,
1207                    [Define to 1 if you have <stdio.h>.])],
1208                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1209 @end example
1211 @noindent
1212 because @samp{1} cannot contain a macro call.  Here, the argument of
1213 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1214 interpreted as an argument separator.  Also, the second and third arguments
1215 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1216 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1217 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1218 if you unwisely defined a macro with a name like @samp{Define} or
1219 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1220 would keep the quotes, but many Autoconf users find such precautions
1221 annoying, and would rewrite the example as follows:
1223 @example
1224 AC_CHECK_HEADER(stdio.h,
1225                 [AC_DEFINE(HAVE_STDIO_H, 1,
1226                    [Define to 1 if you have <stdio.h>.])],
1227                 [AC_MSG_ERROR([sorry, can't do anything for you])])
1228 @end example
1230 @noindent
1231 This is safe, so long as you adopt good naming conventions and do not
1232 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1233 @samp{h}.  Though it is also safe here to omit the quotes around
1234 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1235 message strings are more likely to inadvertently contain commas.
1237 The following example is wrong and dangerous, as it is underquoted:
1239 @example
1240 AC_CHECK_HEADER(stdio.h,
1241                 AC_DEFINE(HAVE_STDIO_H, 1,
1242                    Define to 1 if you have <stdio.h>.),
1243                 AC_MSG_ERROR([sorry, can't do anything for you]))
1244 @end example
1246 In other cases, you may want to use text that also resembles a macro
1247 call.  You must quote that text (whether just the potential problem, or
1248 the entire line) even when it is not passed as a macro argument; and you
1249 may also have to use @code{m4_pattern_allow} (@pxref{Forbidden
1250 Patterns}), to declare your intention that the resulting configure file
1251 will have a literal that resembles what would otherwise be reserved for
1252 a macro name.  For example:
1254 @example
1255 dnl Simulate a possible future autoconf macro
1256 m4_define([AC_DC], [oops])
1257 dnl Underquoted:
1258 echo "Hard rock was here!  --AC_DC"
1259 dnl Correctly quoted:
1260 m4_pattern_allow([AC_DC])
1261 echo "Hard rock was here!  --[AC_DC]"
1262 [echo "Hard rock was here!  --AC_DC"]
1263 @end example
1265 @noindent
1266 which results in this text in @file{configure}:
1268 @example
1269 echo "Hard rock was here!  --oops"
1270 echo "Hard rock was here!  --AC_DC"
1271 echo "Hard rock was here!  --AC_DC"
1272 @end example
1274 @noindent
1275 When you use the same text in a macro argument, you must therefore have
1276 an extra quotation level (since one is stripped away by the macro
1277 substitution).  In general, then, it is a good idea to @emph{use double
1278 quoting for all literal string arguments}, either around just the
1279 problematic portions, or over the entire argument:
1281 @example
1282 m4_pattern_allow([AC_DC])
1283 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1284 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1285 @end example
1287 It is also possible to avoid the problematic patterns in the first
1288 place, by the use of additional escaping (either a quadrigraph, or
1289 creative shell constructs), in which case it is no longer necessary to
1290 use @code{m4_pattern_allow}:
1292 @example
1293 echo "Hard rock was here!  --AC""_DC"
1294 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1295 @end example
1297 You are now able to understand one of the constructs of Autoconf that
1298 has been continually misunderstood@enddots{}  The rule of thumb is that
1299 @emph{whenever you expect macro expansion, expect quote expansion};
1300 i.e., expect one level of quotes to be lost.  For instance:
1302 @example
1303 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1304  [AC_MSG_ERROR([you lose])])
1305 @end example
1307 @noindent
1308 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1309 @samp{char b[10];} and is expanded once, which results in
1310 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1311 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1312 in Autoconf's past to
1313 address this issue via the M4 @code{changequote} primitive, but do not
1314 use it!)  Let's take a closer look: the author meant the first argument
1315 to be understood as a literal, and therefore it must be quoted twice;
1316 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1317 once so that it is only expanded after the rest of the body of
1318 @code{AC_COMPILE_IFELSE} is in place:
1320 @example
1321 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1322   [AC_MSG_ERROR([you lose])])
1323 @end example
1325 @noindent
1326 Voil@`a, you actually produce @samp{char b[10];} this time!
1328 On the other hand, descriptions (e.g., the last parameter of
1329 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1330 are subject to line breaking, for example---and should not be double quoted.
1331 Even if these descriptions are short and are not actually broken, double
1332 quoting them yields weird results.
1334 Some macros take optional arguments, which this documentation represents
1335 as @ovar{arg} (not to be confused with the quote characters).  You may
1336 just leave them empty, or use @samp{[]} to make the emptiness of the
1337 argument explicit, or you may simply omit the trailing commas.  The
1338 three lines below are equivalent:
1340 @example
1341 AC_CHECK_HEADERS([stdio.h], [], [], [])
1342 AC_CHECK_HEADERS([stdio.h],,,)
1343 AC_CHECK_HEADERS([stdio.h])
1344 @end example
1346 It is best to put each macro call on its own line in
1347 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1348 rely on the newline after the macro call to terminate the commands.
1349 This approach makes the generated @command{configure} script a little
1350 easier to read by not inserting lots of blank lines.  It is generally
1351 safe to set shell variables on the same line as a macro call, because
1352 the shell allows assignments without intervening newlines.
1354 You can include comments in @file{configure.ac} files by starting them
1355 with the @samp{#}.  For example, it is helpful to begin
1356 @file{configure.ac} files with a line like this:
1358 @example
1359 # Process this file with autoconf to produce a configure script.
1360 @end example
1362 @node Autoconf Input Layout
1363 @subsection Standard @file{configure.ac} Layout
1365 The order in which @file{configure.ac} calls the Autoconf macros is not
1366 important, with a few exceptions.  Every @file{configure.ac} must
1367 contain a call to @code{AC_INIT} before the checks, and a call to
1368 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1369 rely on other macros having been called first, because they check
1370 previously set values of some variables to decide what to do.  These
1371 macros are noted in the individual descriptions (@pxref{Existing
1372 Tests}), and they also warn you when @command{configure} is created if they
1373 are called out of order.
1375 To encourage consistency, here is a suggested order for calling the
1376 Autoconf macros.  Generally speaking, the things near the end of this
1377 list are those that could depend on things earlier in it.  For example,
1378 library functions could be affected by types and libraries.
1380 @display
1381 @group
1382 Autoconf requirements
1383 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1384 information on the package
1385 checks for programs
1386 checks for libraries
1387 checks for header files
1388 checks for types
1389 checks for structures
1390 checks for compiler characteristics
1391 checks for library functions
1392 checks for system services
1393 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1394 @code{AC_OUTPUT}
1395 @end group
1396 @end display
1399 @node autoscan Invocation
1400 @section Using @command{autoscan} to Create @file{configure.ac}
1401 @cindex @command{autoscan}
1403 The @command{autoscan} program can help you create and/or maintain a
1404 @file{configure.ac} file for a software package.  @command{autoscan}
1405 examines source files in the directory tree rooted at a directory given
1406 as a command line argument, or the current directory if none is given.
1407 It searches the source files for common portability problems and creates
1408 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1409 for that package, and checks a possibly existing @file{configure.ac} for
1410 completeness.
1412 When using @command{autoscan} to create a @file{configure.ac}, you
1413 should manually examine @file{configure.scan} before renaming it to
1414 @file{configure.ac}; it probably needs some adjustments.
1415 Occasionally, @command{autoscan} outputs a macro in the wrong order
1416 relative to another macro, so that @command{autoconf} produces a warning;
1417 you need to move such macros manually.  Also, if you want the package to
1418 use a configuration header file, you must add a call to
1419 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1420 also have to change or add some @code{#if} directives to your program in
1421 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1422 information about a program that can help with that job).
1424 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1425 consider adding its suggestions.  The file @file{autoscan.log}
1426 contains detailed information on why a macro is requested.
1428 @command{autoscan} uses several data files (installed along with Autoconf)
1429 to determine which macros to output when it finds particular symbols in
1430 a package's source files.  These data files all have the same format:
1431 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1432 output if that symbol is encountered.  Lines starting with @samp{#} are
1433 comments.
1435 @command{autoscan} accepts the following options:
1437 @table @option
1438 @item --help
1439 @itemx -h
1440 Print a summary of the command line options and exit.
1442 @item --version
1443 @itemx -V
1444 Print the version number of Autoconf and exit.
1446 @item --verbose
1447 @itemx -v
1448 Print the names of the files it examines and the potentially interesting
1449 symbols it finds in them.  This output can be voluminous.
1451 @item --debug
1452 @itemx -d
1453 Don't remove temporary files.
1455 @item --include=@var{dir}
1456 @itemx -I @var{dir}
1457 Append @var{dir} to the include path.  Multiple invocations accumulate.
1459 @item --prepend-include=@var{dir}
1460 @itemx -B @var{dir}
1461 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1462 @end table
1464 @node ifnames Invocation
1465 @section Using @command{ifnames} to List Conditionals
1466 @cindex @command{ifnames}
1468 @command{ifnames} can help you write @file{configure.ac} for a software
1469 package.  It prints the identifiers that the package already uses in C
1470 preprocessor conditionals.  If a package has already been set up to have
1471 some portability, @command{ifnames} can thus help you figure out what its
1472 @command{configure} needs to check for.  It may help fill in some gaps in a
1473 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1474 Invocation}).
1476 @command{ifnames} scans all of the C source files named on the command line
1477 (or the standard input, if none are given) and writes to the standard
1478 output a sorted list of all the identifiers that appear in those files
1479 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1480 directives.  It prints each identifier on a line, followed by a
1481 space-separated list of the files in which that identifier occurs.
1483 @noindent
1484 @command{ifnames} accepts the following options:
1486 @table @option
1487 @item --help
1488 @itemx -h
1489 Print a summary of the command line options and exit.
1491 @item --version
1492 @itemx -V
1493 Print the version number of Autoconf and exit.
1494 @end table
1496 @node autoconf Invocation
1497 @section Using @command{autoconf} to Create @command{configure}
1498 @cindex @command{autoconf}
1500 To create @command{configure} from @file{configure.ac}, run the
1501 @command{autoconf} program with no arguments.  @command{autoconf} processes
1502 @file{configure.ac} with the M4 macro processor, using the
1503 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1504 file instead of @file{configure.ac} and writes the configuration script
1505 to the standard output instead of to @command{configure}.  If you give
1506 @command{autoconf} the argument @option{-}, it reads from the standard
1507 input instead of @file{configure.ac} and writes the configuration script
1508 to the standard output.
1510 The Autoconf macros are defined in several files.  Some of the files are
1511 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1512 looks for the optional file @file{acsite.m4} in the directory that
1513 contains the distributed Autoconf macro files, and for the optional file
1514 @file{aclocal.m4} in the current directory.  Those files can contain
1515 your site's or the package's own Autoconf macro definitions
1516 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1517 defined in more than one of the files that @command{autoconf} reads, the
1518 last definition it reads overrides the earlier ones.
1520 @command{autoconf} accepts the following options:
1522 @table @option
1523 @item --help
1524 @itemx -h
1525 Print a summary of the command line options and exit.
1527 @item --version
1528 @itemx -V
1529 Print the version number of Autoconf and exit.
1531 @item --verbose
1532 @itemx -v
1533 Report processing steps.
1535 @item --debug
1536 @itemx -d
1537 Don't remove the temporary files.
1539 @item --force
1540 @itemx -f
1541 Remake @file{configure} even if newer than its input files.
1543 @item --include=@var{dir}
1544 @itemx -I @var{dir}
1545 Append @var{dir} to the include path.  Multiple invocations accumulate.
1547 @item --prepend-include=@var{dir}
1548 @itemx -B @var{dir}
1549 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1551 @item --output=@var{file}
1552 @itemx -o @var{file}
1553 Save output (script or trace) to @var{file}.  The file @option{-} stands
1554 for the standard output.
1556 @item --warnings=@var{category}
1557 @itemx -W @var{category}
1558 @evindex WARNINGS
1559 Report the warnings related to @var{category} (which can actually be a
1560 comma separated list).  @xref{Reporting Messages}, macro
1561 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1562 values include:
1564 @table @samp
1565 @item all
1566 report all the warnings
1568 @item none
1569 report none
1571 @item error
1572 treats warnings as errors
1574 @item no-@var{category}
1575 disable warnings falling into @var{category}
1576 @end table
1578 Warnings about @samp{syntax} are enabled by default, and the environment
1579 variable @env{WARNINGS}, a comma separated list of categories, is
1580 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1581 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1582 disable the defaults and @env{WARNINGS}, and then
1583 enable warnings about obsolete constructs, use @option{-W
1584 none,obsolete}.
1586 @cindex Back trace
1587 @cindex Macro invocation stack
1588 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1589 displays a back trace for errors, but not for warnings; if you want
1590 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1591 examples.
1593 @item --trace=@var{macro}[:@var{format}]
1594 @itemx -t @var{macro}[:@var{format}]
1595 Do not create the @command{configure} script, but list the calls to
1596 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1597 arguments can be used to list several macros.  Multiple @option{--trace}
1598 arguments for a single macro are not cumulative; instead, you should
1599 just make @var{format} as long as needed.
1601 The @var{format} is a regular string, with newlines if desired, and
1602 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1603 @ref{autom4te Invocation}, for details on the @var{format}.
1605 @item --initialization
1606 @itemx -i
1607 By default, @option{--trace} does not trace the initialization of the
1608 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1609 results in a noticeable speedup, but can be disabled by this option.
1610 @end table
1613 It is often necessary to check the content of a @file{configure.ac}
1614 file, but parsing it yourself is extremely fragile and error-prone.  It
1615 is suggested that you rely upon @option{--trace} to scan
1616 @file{configure.ac}.  For instance, to find the list of variables that
1617 are substituted, use:
1619 @example
1620 @group
1621 $ @kbd{autoconf -t AC_SUBST}
1622 configure.ac:2:AC_SUBST:ECHO_C
1623 configure.ac:2:AC_SUBST:ECHO_N
1624 configure.ac:2:AC_SUBST:ECHO_T
1625 @i{More traces deleted}
1626 @end group
1627 @end example
1629 @noindent
1630 The example below highlights the difference between @samp{$@@},
1631 @samp{$*}, and @samp{$%}.
1633 @example
1634 @group
1635 $ @kbd{cat configure.ac}
1636 AC_DEFINE(This, is, [an
1637 [example]])
1638 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1639 *: $*
1640 %: $%'
1641 @@: [This],[is],[an
1642 [example]]
1643 *: This,is,an
1644 [example]
1645 %: This:is:an [example]
1646 @end group
1647 @end example
1649 @noindent
1650 The @var{format} gives you a lot of freedom:
1652 @example
1653 @group
1654 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1655 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1656 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1657 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1658 @i{More traces deleted}
1659 @end group
1660 @end example
1662 @noindent
1663 A long @var{separator} can be used to improve the readability of complex
1664 structures, and to ease their parsing (for instance when no single
1665 character is suitable as a separator):
1667 @example
1668 @group
1669 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1670 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1671 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1672 AUTOMAKE|:::::|automake|:::::|$missing_dir
1673 @i{More traces deleted}
1674 @end group
1675 @end example
1677 @node autoreconf Invocation
1678 @section Using @command{autoreconf} to Update @command{configure} Scripts
1679 @cindex @command{autoreconf}
1681 Installing the various components of the GNU Build System can be
1682 tedious: running @command{autopoint} for Gettext, @command{automake} for
1683 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1684 because some tools such as @command{automake} have been updated on your
1685 system, or because some of the sources such as @file{configure.ac} have
1686 been updated, or finally, simply in order to install the GNU Build
1687 System in a fresh tree.
1689 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1690 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1691 @command{autopoint} (when appropriate) repeatedly to update the
1692 GNU Build System in the specified directories and their
1693 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1694 those files that are older than their sources.  The environment variables
1695 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1696 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1697 may be used to override the invocation of the respective tools.
1699 If you install a new version of some tool, you can make
1700 @command{autoreconf} remake @emph{all} of the files by giving it the
1701 @option{--force} option.
1703 @xref{Automatic Remaking}, for Make rules to automatically
1704 rebuild @command{configure} scripts when their source files change.  That
1705 method handles the timestamps of configuration header templates
1706 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1707 @option{--localdir=@var{dir}}.
1709 @cindex Gettext
1710 @cindex @command{autopoint}
1711 Gettext supplies the @command{autopoint} command to add translation
1712 infrastructure to a source package.  If you use @command{autopoint},
1713 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1714 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1715 Invocation, , Invoking the @code{autopoint} Program, gettext,
1716 GNU @code{gettext} utilities}, for further details.
1718 @noindent
1719 @command{autoreconf} accepts the following options:
1721 @table @option
1722 @item --help
1723 @itemx -h
1724 Print a summary of the command line options and exit.
1726 @item --version
1727 @itemx -V
1728 Print the version number of Autoconf and exit.
1730 @item --verbose
1731 @itemx -v
1732 Print the name of each directory @command{autoreconf} examines and the
1733 commands it runs.  If given two or more times, pass @option{--verbose}
1734 to subordinate tools that support it.
1736 @item --debug
1737 @itemx -d
1738 Don't remove the temporary files.
1740 @item --force
1741 @itemx -f
1742 Consider all generated and standard auxiliary files to be obsolete.
1743 This remakes even @file{configure} scripts and configuration headers
1744 that are newer than their input files (@file{configure.ac} and, if
1745 present, @file{aclocal.m4}).
1747 If deemed appropriate, this option triggers calls to @samp{automake
1748 --force-missing}.  Passing both @option{--force} and @option{--install}
1749 to @command{autoreconf} will in turn undo any customizations to standard
1750 files.  Note that the macro @code{AM_INIT_AUTOMAKE} has some options
1751 which change the set of files considered to be standard.
1753 @item --install
1754 @itemx -i
1755 Install any missing standard auxiliary files in the package.  By
1756 default, files are copied; this can be changed with @option{--symlink}.
1758 If deemed appropriate, this option triggers calls to
1759 @samp{automake --add-missing},
1760 @samp{libtoolize}, @samp{autopoint}, etc.
1762 @item --no-recursive
1763 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1764 macro @code{AC_CONFIG_SUBDIRS}).
1766 @item --symlink
1767 @itemx -s
1768 When used with @option{--install}, install symbolic links to the missing
1769 auxiliary files instead of copying them.
1771 @item --make
1772 @itemx -m
1773 When the directories were configured, update the configuration by
1774 running @samp{./config.status --recheck && ./config.status}, and then
1775 run @samp{make}.
1777 @item --include=@var{dir}
1778 @itemx -I @var{dir}
1779 Append @var{dir} to the include path.  Multiple invocations accumulate.
1780 Passed on to @command{aclocal}, @command{autoconf} and
1781 @command{autoheader} internally.
1783 @item --prepend-include=@var{dir}
1784 @itemx -B @var{dir}
1785 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1786 Passed on to @command{autoconf} and @command{autoheader} internally.
1788 @item --warnings=@var{category}
1789 @itemx -W @var{category}
1790 @evindex WARNINGS
1791 Report the warnings related to @var{category} (which can actually be a
1792 comma separated list).
1794 @table @samp
1795 @item cross
1796 related to cross compilation issues.
1798 @item obsolete
1799 report the uses of obsolete constructs.
1801 @item portability
1802 portability issues
1804 @item syntax
1805 dubious syntactic constructs.
1807 @item all
1808 report all the warnings
1810 @item none
1811 report none
1813 @item error
1814 treats warnings as errors
1816 @item no-@var{category}
1817 disable warnings falling into @var{category}
1818 @end table
1820 Warnings about @samp{syntax} are enabled by default, and the environment
1821 variable @env{WARNINGS}, a comma separated list of categories, is
1822 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1823 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1824 disable the defaults and @env{WARNINGS}, and then
1825 enable warnings about obsolete constructs, use @option{-W
1826 none,obsolete}.
1827 @end table
1829 If you want @command{autoreconf} to pass flags that are not listed here
1830 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1831 Due to a limitation in the Autoconf implementation these flags currently
1832 must be set on a single line in @file{Makefile.am}, without any
1833 backslash-newlines.  Also, be aware that future Automake releases might
1834 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1835 support for it.
1837 @c ========================================= Initialization and Output Files.
1839 @node Setup
1840 @chapter Initialization and Output Files
1842 Autoconf-generated @command{configure} scripts need some information about
1843 how to initialize, such as how to find the package's source files and
1844 about the output files to produce.  The following sections describe the
1845 initialization and the creation of output files.
1847 @menu
1848 * Initializing configure::      Option processing etc.
1849 * Versioning::                  Dealing with Autoconf versions
1850 * Notices::                     Copyright, version numbers in @command{configure}
1851 * Input::                       Where Autoconf should find files
1852 * Output::                      Outputting results from the configuration
1853 * Configuration Actions::       Preparing the output based on results
1854 * Configuration Files::         Creating output files
1855 * Makefile Substitutions::      Using output variables in makefiles
1856 * Configuration Headers::       Creating a configuration header file
1857 * Configuration Commands::      Running arbitrary instantiation commands
1858 * Configuration Links::         Links depending on the configuration
1859 * Subdirectories::              Configuring independent packages together
1860 * Default Prefix::              Changing the default installation prefix
1861 @end menu
1863 @node Initializing configure
1864 @section Initializing @command{configure}
1866 Every @command{configure} script must call @code{AC_INIT} before doing
1867 anything else that produces output.  Calls to silent macros, such as
1868 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1869 are generally used via @file{aclocal.m4}, since that is implicitly
1870 included before the start of @file{configure.ac}.  The only other
1871 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1873 @anchor{AC_INIT}
1874 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1875   @ovar{tarname}, @ovar{url})
1876 @acindex{INIT}
1877 Process any command-line arguments and perform initialization
1878 and verification.
1880 Set the name of the @var{package} and its @var{version}.  These are
1881 typically used in @option{--version} support, including that of
1882 @command{configure}.  The optional argument @var{bug-report} should be
1883 the email to which users should send bug reports.  The package
1884 @var{tarname} differs from @var{package}: the latter designates the full
1885 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1886 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1887 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1888 other than alphanumerics and underscores are changed to @samp{-}.  If
1889 provided, @var{url} should be the home page for the package.
1891 The arguments of @code{AC_INIT} must be static, i.e., there should not
1892 be any shell computation, quotes, or newlines, but they can be computed
1893 by M4.  This is because the package information strings are expanded at
1894 M4 time into several contexts, and must give the same text at shell time
1895 whether used in single-quoted strings, double-quoted strings, quoted
1896 here-documents, or unquoted here-documents.  It is permissible to use
1897 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1898 that changes with every commit to a version control system (in fact,
1899 Autoconf does just that, for all builds of the development tree made
1900 between releases).
1902 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1903 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1904 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1906 @table @asis
1907 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1908 @acindex{PACKAGE_NAME}
1909 @ovindex PACKAGE_NAME
1910 @cvindex PACKAGE_NAME
1911 Exactly @var{package}.
1913 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1914 @acindex{PACKAGE_TARNAME}
1915 @ovindex PACKAGE_TARNAME
1916 @cvindex PACKAGE_TARNAME
1917 Exactly @var{tarname}, possibly generated from @var{package}.
1919 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1920 @acindex{PACKAGE_VERSION}
1921 @ovindex PACKAGE_VERSION
1922 @cvindex PACKAGE_VERSION
1923 Exactly @var{version}.
1925 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1926 @acindex{PACKAGE_STRING}
1927 @ovindex PACKAGE_STRING
1928 @cvindex PACKAGE_STRING
1929 Exactly @samp{@var{package} @var{version}}.
1931 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1932 @acindex{PACKAGE_BUGREPORT}
1933 @ovindex PACKAGE_BUGREPORT
1934 @cvindex PACKAGE_BUGREPORT
1935 Exactly @var{bug-report}, if one was provided.  Typically an email
1936 address, or URL to a bug management web page.
1938 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1939 @acindex{PACKAGE_URL}
1940 @ovindex PACKAGE_URL
1941 @cvindex PACKAGE_URL
1942 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1943 @var{package} begins with @samp{GNU }, then this defaults to
1944 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1945 assumed.
1946 @end table
1947 @end defmac
1949 If your @command{configure} script does its own option processing, it
1950 should inspect @samp{$@@} or @samp{$*} immediately after calling
1951 @code{AC_INIT}, because other Autoconf macros liberally use the
1952 @command{set} command to process strings, and this has the side effect
1953 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1954 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1955 implement your own option processing.  @xref{Site Configuration}.
1957 @node Versioning
1958 @section Dealing with Autoconf versions
1959 @cindex Autoconf version
1960 @cindex version, Autoconf
1962 The following optional macros can be used to help choose the minimum
1963 version of Autoconf that can successfully compile a given
1964 @file{configure.ac}.
1966 @defmac AC_PREREQ (@var{version})
1967 @acindex{PREREQ}
1968 @cindex Version
1969 Ensure that a recent enough version of Autoconf is being used.  If the
1970 version of Autoconf being used to create @command{configure} is
1971 earlier than @var{version}, print an error message to the standard
1972 error output and exit with failure (exit status is 63).  For example:
1974 @example
1975 AC_PREREQ([@value{VERSION}])
1976 @end example
1978 This macro may be used before @code{AC_INIT}.
1979 @end defmac
1981 @defmac AC_AUTOCONF_VERSION
1982 @acindex{AUTOCONF_VERSION}
1983 This macro was introduced in Autoconf 2.62.  It identifies the version
1984 of Autoconf that is currently parsing the input file, in a format
1985 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1986 other words, for this release of Autoconf, its value is
1987 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1988 conditional fallbacks based on when a feature was added to Autoconf,
1989 rather than using @code{AC_PREREQ} to require the newer version of
1990 Autoconf.  However, remember that the Autoconf philosophy favors feature
1991 checks over version checks.
1993 You should not expand this macro directly; use
1994 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1995 users might
1996 have a beta version of Autoconf installed, with arbitrary letters
1997 included in its version string.  This means it is possible for the
1998 version string to contain the name of a defined macro, such that
1999 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
2000 macro during rescanning, and change the version string to be different
2001 than what you intended to check.
2002 @end defmac
2004 @node Notices
2005 @section Notices in @command{configure}
2006 @cindex Notices in @command{configure}
2008 The following macros manage version numbers for @command{configure}
2009 scripts.  Using them is optional.
2011 @defmac AC_COPYRIGHT (@var{copyright-notice})
2012 @acindex{COPYRIGHT}
2013 @cindex Copyright Notice
2014 State that, in addition to the Free Software Foundation's copyright on
2015 the Autoconf macros, parts of your @command{configure} are covered by the
2016 @var{copyright-notice}.
2018 The @var{copyright-notice} shows up in both the head of
2019 @command{configure} and in @samp{configure --version}.
2020 @end defmac
2023 @defmac AC_REVISION (@var{revision-info})
2024 @acindex{REVISION}
2025 @cindex Revision
2026 Copy revision stamp @var{revision-info} into the @command{configure}
2027 script, with any dollar signs or double-quotes removed.  This macro lets
2028 you put a revision stamp from @file{configure.ac} into @command{configure}
2029 without RCS or CVS changing it when you check in
2030 @command{configure}.  That way, you can determine easily which revision of
2031 @file{configure.ac} a particular @command{configure} corresponds to.
2033 For example, this line in @file{configure.ac}:
2035 @c The @w prevents RCS from changing the example in the manual.
2036 @example
2037 AC_REVISION([@w{$}Revision: 1.30 $])
2038 @end example
2040 @noindent
2041 produces this in @command{configure}:
2043 @example
2044 #!/bin/sh
2045 # From configure.ac Revision: 1.30
2046 @end example
2047 @end defmac
2050 @node Input
2051 @section Finding @command{configure} Input
2053 @anchor{AC_CONFIG_SRCDIR}
2054 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2055 @acindex{CONFIG_SRCDIR}
2056 @var{unique-file-in-source-dir} is some file that is in the package's
2057 source directory; @command{configure} checks for this file's existence to
2058 make sure that the directory that it is told contains the source code in
2059 fact does.  Occasionally people accidentally specify the wrong directory
2060 with @option{--srcdir}; this is a safety check.  @xref{configure
2061 Invocation}, for more information.
2062 @end defmac
2065 @c FIXME: Remove definitively once --install explained.
2067 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2068 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2069 @c to split the macros in several files.  In this case, Autoconf must be
2070 @c told which files to load, and in which order.
2072 @c @defmac AC_INCLUDE (@var{file}@dots{})
2073 @c @acindex{INCLUDE}
2074 @c @c FIXME: There is no longer shell globbing.
2075 @c Read the macro definitions that appear in the listed files.  A list of
2076 @c space-separated file names or shell globbing patterns is expected.  The
2077 @c files are read in the order they're listed.
2079 @c Because the order of definition of macros is important (only the last
2080 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2081 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2082 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2083 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2084 @c the latter case, non-macro lines from included files may end up in the
2085 @c @file{configure} script, whereas in the former case, they'd be discarded
2086 @c just like any text that appear before @code{AC_INIT}.
2087 @c @end defmac
2089 Packages that do manual configuration or use the @command{install} program
2090 might need to tell @command{configure} where to find some other shell
2091 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2092 it looks are correct for most cases.
2094 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2095 @acindex{CONFIG_AUX_DIR}
2096 Use the auxiliary build tools (e.g., @file{install-sh},
2097 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2098 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2099 These are auxiliary files used in configuration.  @var{dir} can be
2100 either absolute or relative to @file{@var{srcdir}}.  The default is
2101 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2102 @file{@var{srcdir}/../..}, whichever is the first that contains
2103 @file{install-sh}.  The other files are not checked for, so that using
2104 @code{AC_PROG_INSTALL} does not automatically require distributing the
2105 other auxiliary files.  It checks for @file{install.sh} also, but that
2106 name is obsolete because some @command{make} have a rule that creates
2107 @file{install} from it if there is no makefile.
2109 The auxiliary directory is commonly named @file{build-aux}.
2110 If you need portability to DOS variants, do not name the
2111 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2112 @end defmac
2114 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2115 @acindex{REQUIRE_AUX_FILE}
2116 Declares that @var{file} is expected in the directory defined above.  In
2117 Autoconf proper, this macro does nothing: its sole purpose is to be
2118 traced by third-party tools to produce a list of expected auxiliary
2119 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2120 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2121 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2122 @end defmac
2124 Similarly, packages that use @command{aclocal} should declare where
2125 local macros can be found using @code{AC_CONFIG_MACRO_DIRS}.
2127 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2128 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2129 @acindex{CONFIG_MACRO_DIRS}
2130 @acindex{CONFIG_MACRO_DIR}
2131 @acindex{CONFIG_MACRO_DIR_TRACE}
2132 Specify the given directories as the location of additional local Autoconf
2133 macros.  These macros are intended for use by commands like
2134 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2135 be called directly from @file{configure.ac} so that tools that install
2136 macros for @command{aclocal} can find the macros' declarations.  Tools
2137 that want to learn which directories have been selected should trace
2138 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2140 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2141 times and with multiple arguments; in such cases, directories in earlier
2142 calls are expected to be searched before directories in later calls, and
2143 directories appearing in the same call are expected to be searched in
2144 the order in which they appear in the call.  For historical reasons, the
2145 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2146 for tools such as older @command{libtool} that weren't prepared to
2147 handle multiple directories.  For example, a usage like
2149 @smallexample
2150 AC_CONFIG_MACRO_DIR([dir1])
2151 AC_CONFIG_MACRO_DIRS([dir2])
2152 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2153 @end smallexample
2155 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2156 and should cause the directories to be searched in this order:
2157 @samp{dir1 dir2 dir3 dir4}.
2159 Note that if you use @command{aclocal} from an Automake release prior to
2160 1.13 to generate @file{aclocal.m4}, you must also set
2161 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2162 in your top-level @file{Makefile.am}.  Due to a limitation in
2163 the Autoconf implementation of @command{autoreconf}, these include
2164 directives currently must be set on a single line in @file{Makefile.am},
2165 without any backslash-newlines.
2166 @end defmac
2169 @node Output
2170 @section Outputting Files
2171 @cindex Outputting files
2173 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2174 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2175 @file{config.status}, which in turn creates the makefiles and any
2176 other files resulting from configuration.  This is the only required
2177 macro besides @code{AC_INIT} (@pxref{Input}).
2179 @anchor{AC_OUTPUT}
2180 @defmac AC_OUTPUT
2181 @acindex{OUTPUT}
2182 @cindex Instantiation
2183 Generate @file{config.status} and launch it.  Call this macro once, at
2184 the end of @file{configure.ac}.
2186 @file{config.status} performs all the configuration actions: all the
2187 output files (see @ref{Configuration Files}, macro
2188 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2189 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2190 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2191 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2192 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2193 are honored.
2195 The location of your @code{AC_OUTPUT} invocation is the exact point
2196 where configuration actions are taken: any code afterwards is
2197 executed by @command{configure} once @command{config.status} was run.  If
2198 you want to bind actions to @command{config.status} itself
2199 (independently of whether @command{configure} is being run), see
2200 @ref{Configuration Commands, , Running Arbitrary Configuration
2201 Commands}.
2202 @end defmac
2204 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2205 @xref{Obsolete Macros}, for a description of the arguments that
2206 @code{AC_OUTPUT} used to support.
2209 If you run @command{make} in subdirectories, you should run it using the
2210 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2211 @code{MAKE} to the name of the @command{make} program plus any options it
2212 was given.  (But many do not include in it the values of any variables
2213 set on the command line, so those are not passed on automatically.)
2214 Some old versions of @command{make} do not set this variable.  The
2215 following macro allows you to use it even with those versions.
2217 @anchor{AC_PROG_MAKE_SET}
2218 @defmac AC_PROG_MAKE_SET
2219 @acindex{PROG_MAKE_SET}
2220 @ovindex SET_MAKE
2221 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2222 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2223 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2224 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2225 @code{SET_MAKE}.
2226 @end defmac
2228 If you use this macro, place a line like this in each @file{Makefile.in}
2229 that runs @command{MAKE} on other directories:
2231 @example
2232 @@SET_MAKE@@
2233 @end example
2237 @node Configuration Actions
2238 @section Performing Configuration Actions
2239 @cindex Configuration actions
2241 @file{configure} is designed so that it appears to do everything itself,
2242 but there is actually a hidden slave: @file{config.status}.
2243 @file{configure} is in charge of examining your system, but it is
2244 @file{config.status} that actually takes the proper actions based on the
2245 results of @file{configure}.  The most typical task of
2246 @file{config.status} is to @emph{instantiate} files.
2248 @acindex{CONFIG_@var{ITEMS}}
2249 This section describes the common behavior of the four standard
2250 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2251 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2252 have this prototype:
2254 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2255 @c awful.
2256 @example
2257 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2258 @end example
2260 @noindent
2261 where the arguments are:
2263 @table @var
2264 @item tag@dots{}
2265 A blank-or-newline-separated list of tags, which are typically the names of
2266 the files to instantiate.
2268 You are encouraged to use literals as @var{tags}.  In particular, you
2269 should avoid
2271 @example
2272 @dots{} && my_foos="$my_foos fooo"
2273 @dots{} && my_foos="$my_foos foooo"
2274 AC_CONFIG_@var{ITEMS}([$my_foos])
2275 @end example
2277 @noindent
2278 and use this instead:
2280 @example
2281 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2282 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2283 @end example
2285 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2286 special @var{tag} values: they may have the form @samp{@var{output}} or
2287 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2288 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2290 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2291 for example, asks for
2292 the creation of the file @file{Makefile} that contains the expansion of the
2293 output variables in the concatenation of @file{boiler/top.mk} and
2294 @file{boiler/bot.mk}.
2296 The special value @samp{-} might be used to denote the standard output
2297 when used in @var{output}, or the standard input when used in the
2298 @var{inputs}.  You most probably don't need to use this in
2299 @file{configure.ac}, but it is convenient when using the command line
2300 interface of @file{./config.status}, see @ref{config.status Invocation},
2301 for more details.
2303 The @var{inputs} may be absolute or relative file names.  In the latter
2304 case they are first looked for in the build tree, and then in the source
2305 tree.  Input files should be text files, and a line length below 2000
2306 bytes should be safe.
2308 @item commands
2309 Shell commands output literally into @file{config.status}, and
2310 associated with a tag that the user can use to tell @file{config.status}
2311 which commands to run.  The commands are run each time a @var{tag}
2312 request is given to @file{config.status}, typically each time the file
2313 @file{@var{tag}} is created.
2315 The variables set during the execution of @command{configure} are
2316 @emph{not} available here: you first need to set them via the
2317 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2319 @table @code
2320 @item srcdir
2321 @vrindex srcdir
2322 The name of the top source directory, assuming that the working
2323 directory is the top build directory.  This
2324 is what the @command{configure} option @option{--srcdir} sets.
2326 @item ac_top_srcdir
2327 @vrindex ac_top_srcdir
2328 The name of the top source directory, assuming that the working
2329 directory is the current build directory.
2331 @item ac_top_build_prefix
2332 @vrindex ac_top_build_prefix
2333 The name of the top build directory, assuming that the working
2334 directory is the current build directory.
2335 It can be empty, or else ends with a slash, so that you may concatenate
2338 @item ac_srcdir
2339 @vrindex ac_srcdir
2340 The name of the corresponding source directory, assuming that the
2341 working directory is the current build directory.
2343 @item tmp
2344 @vrindex tmp
2345 The name of a temporary directory within the build tree, which you
2346 can use if you need to create additional temporary files.  The
2347 directory is cleaned up when @command{config.status} is done or
2348 interrupted.  Please use package-specific file name prefixes to
2349 avoid clashing with files that @command{config.status} may use
2350 internally.
2351 @end table
2353 @noindent
2354 The @dfn{current} directory refers to the directory (or
2355 pseudo-directory) containing the input part of @var{tags}.  For
2356 instance, running
2358 @example
2359 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2360 @end example
2362 @noindent
2363  with @option{--srcdir=../package} produces the following values:
2365 @example
2366 # Argument of --srcdir
2367 srcdir='../package'
2368 # Reversing deep/dir
2369 ac_top_build_prefix='../../'
2370 # Concatenation of $ac_top_build_prefix and srcdir
2371 ac_top_srcdir='../../../package'
2372 # Concatenation of $ac_top_srcdir and deep/dir
2373 ac_srcdir='../../../package/deep/dir'
2374 @end example
2376 @noindent
2377 independently of @samp{in/in.in}.
2379 @item init-cmds
2380 Shell commands output @emph{unquoted} near the beginning of
2381 @file{config.status}, and executed each time @file{config.status} runs
2382 (regardless of the tag).  Because they are unquoted, for example,
2383 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2384 is typically used by @file{configure} to give @file{config.status} some
2385 variables it needs to run the @var{commands}.
2387 You should be extremely cautious in your variable names: all the
2388 @var{init-cmds} share the same name space and may overwrite each other
2389 in unpredictable ways.  Sorry@enddots{}
2390 @end table
2392 All these macros can be called multiple times, with different
2393 @var{tag} values, of course!
2396 @node Configuration Files
2397 @section Creating Configuration Files
2398 @cindex Creating configuration files
2399 @cindex Configuration file creation
2401 Be sure to read the previous section, @ref{Configuration Actions}.
2403 @anchor{AC_CONFIG_FILES}
2404 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2405 @acindex{CONFIG_FILES}
2406 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2407 file (by default @file{@var{file}.in}), substituting the output variable
2408 values.
2409 @c Before we used to have this feature, which was later rejected
2410 @c because it complicates the writing of makefiles:
2411 @c If the file would be unchanged, it is left untouched, to preserve
2412 @c timestamp.
2413 This macro is one of the instantiating macros; see @ref{Configuration
2414 Actions}.  @xref{Makefile Substitutions}, for more information on using
2415 output variables.  @xref{Setting Output Variables}, for more information
2416 on creating them.  This macro creates the directory that the file is in
2417 if it doesn't exist.  Usually, makefiles are created this way,
2418 but other files, such as @file{.gdbinit}, can be specified as well.
2420 Typical calls to @code{AC_CONFIG_FILES} look like this:
2422 @example
2423 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2424 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2425 @end example
2427 You can override an input file name by appending to @var{file} a
2428 colon-separated list of input files.  Examples:
2430 @example
2431 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2432                 [lib/Makefile:boiler/lib.mk])
2433 @end example
2435 @noindent
2436 Doing this allows you to keep your file names acceptable to
2437 DOS variants, or
2438 to prepend and/or append boilerplate to the file.
2439 @end defmac
2443 @node Makefile Substitutions
2444 @section Substitutions in Makefiles
2445 @cindex Substitutions in makefiles
2446 @cindex Makefile substitutions
2448 Each subdirectory in a distribution that contains something to be
2449 compiled or installed should come with a file @file{Makefile.in}, from
2450 which @command{configure} creates a file @file{Makefile} in that directory.
2451 To create @file{Makefile}, @command{configure} performs a simple variable
2452 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2453 @file{Makefile.in} with the value that @command{configure} has determined
2454 for that variable.  Variables that are substituted into output files in
2455 this way are called @dfn{output variables}.  They are ordinary shell
2456 variables that are set in @command{configure}.  To make @command{configure}
2457 substitute a particular variable into the output files, the macro
2458 @code{AC_SUBST} must be called with that variable name as an argument.
2459 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2460 left unchanged.  @xref{Setting Output Variables}, for more information
2461 on creating output variables with @code{AC_SUBST}.
2463 A software package that uses a @command{configure} script should be
2464 distributed with a file @file{Makefile.in}, but no makefile; that
2465 way, the user has to properly configure the package for the local system
2466 before compiling it.
2468 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2469 GNU Coding Standards}, for more information on what to put in
2470 makefiles.
2472 @menu
2473 * Preset Output Variables::     Output variables that are always set
2474 * Installation Directory Variables::  Other preset output variables
2475 * Changed Directory Variables::  Warnings about @file{datarootdir}
2476 * Build Directories::           Supporting multiple concurrent compiles
2477 * Automatic Remaking::          Makefile rules for configuring
2478 @end menu
2480 @node Preset Output Variables
2481 @subsection Preset Output Variables
2482 @cindex Output variables
2484 Some output variables are preset by the Autoconf macros.  Some of the
2485 Autoconf macros set additional output variables, which are mentioned in
2486 the descriptions for those macros.  @xref{Output Variable Index}, for a
2487 complete list of output variables.  @xref{Installation Directory
2488 Variables}, for the list of the preset ones related to installation
2489 directories.  Below are listed the other preset ones, many of which are
2490 precious variables (@pxref{Setting Output Variables},
2491 @code{AC_ARG_VAR}).
2493 The preset variables which are available during @file{config.status}
2494 (@pxref{Configuration Actions}) may also be used during
2495 @command{configure} tests.  For example, it is permissible to reference
2496 @samp{$srcdir} when constructing a list of directories to pass via
2497 option @option{-I} during a compiler feature check.  When used in this
2498 manner, coupled with the fact that @command{configure} is always run
2499 from the top build directory, it is sufficient to use just
2500 @samp{$srcdir} instead of @samp{$top_srcdir}.
2502 @c Just say no to ASCII sorting!  We're humans, not computers.
2503 @c These variables are listed as they would be in a dictionary:
2504 @c actor
2505 @c Actress
2506 @c actress
2508 @defvar CFLAGS
2509 @evindex CFLAGS
2510 @ovindex CFLAGS
2511 Debugging and optimization options for the C compiler.  If it is not set
2512 in the environment when @command{configure} runs, the default value is set
2513 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2514 uses this variable when compiling or linking programs to test for C features.
2516 If a compiler option affects only the behavior of the preprocessor
2517 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2518 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2519 it should be put into @code{LDFLAGS} instead.  If it
2520 affects only the compiler proper, @code{CFLAGS} is the natural home for
2521 it.  If an option affects multiple phases of the compiler, though,
2522 matters get tricky.  One approach to put such options directly into
2523 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2524 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2526 However, remember that some @file{Makefile} variables are reserved by
2527 the GNU Coding Standards for the use of the ``user''---the person
2528 building the package.  For instance, @code{CFLAGS} is one such variable.
2530 Sometimes package developers are tempted to set user variables such as
2531 @code{CFLAGS} because it appears to make their job easier.  However, the
2532 package itself should never set a user variable, particularly not to
2533 include switches that are required for proper compilation of the
2534 package.  Since these variables are documented as being for the package
2535 builder, that person rightfully expects to be able to override any of
2536 these variables at build time.  If the package developer needs to add
2537 switches without interfering with the user, the proper way to do that is
2538 to introduce an additional variable.  Automake makes this easy by
2539 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2540 automake, GNU Automake}), but the concept is the same even if
2541 Automake is not used.
2542 @end defvar
2544 @defvar configure_input
2545 @ovindex configure_input
2546 A comment saying that the file was generated automatically by
2547 @command{configure} and giving the name of the input file.
2548 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2549 of every makefile it creates.  For other files, you should
2550 reference this variable in a comment at the top of each input file.  For
2551 example, an input shell script should begin like this:
2553 @example
2554 #!/bin/sh
2555 # @@configure_input@@
2556 @end example
2558 @noindent
2559 The presence of that line also reminds people editing the file that it
2560 needs to be processed by @command{configure} in order to be used.
2561 @end defvar
2563 @defvar CPPFLAGS
2564 @evindex CPPFLAGS
2565 @ovindex CPPFLAGS
2566 Preprocessor options for the C, C++, Objective C, and Objective C++
2567 preprocessors and compilers.  If
2568 it is not set in the environment when @command{configure} runs, the default
2569 value is empty.  @command{configure} uses this variable when preprocessing
2570 or compiling programs to test for C, C++, Objective C, and Objective C++
2571 features.
2573 This variable's contents should contain options like @option{-I},
2574 @option{-D}, and @option{-U} that affect only the behavior of the
2575 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2576 can do if an option affects other phases of the compiler as well.
2578 Currently, @command{configure} always links as part of a single
2579 invocation of the compiler that also preprocesses and compiles, so it
2580 uses this variable also when linking programs.  However, it is unwise to
2581 depend on this behavior because the GNU Coding Standards do
2582 not require it and many packages do not use @code{CPPFLAGS} when linking
2583 programs.
2585 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2586 might run into.
2587 @end defvar
2589 @defvar CXXFLAGS
2590 @evindex CXXFLAGS
2591 @ovindex CXXFLAGS
2592 Debugging and optimization options for the C++ compiler.  It acts like
2593 @code{CFLAGS}, but for C++ instead of C.
2594 @end defvar
2596 @defvar DEFS
2597 @ovindex DEFS
2598 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2599 is called, @command{configure} replaces @samp{@@DEFS@@} with
2600 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2601 variable is not defined while @command{configure} is performing its tests,
2602 only when creating the output files.  @xref{Setting Output Variables}, for
2603 how to check the results of previous tests.
2604 @end defvar
2606 @defvar ECHO_C
2607 @defvarx ECHO_N
2608 @defvarx ECHO_T
2609 @ovindex ECHO_C
2610 @ovindex ECHO_N
2611 @ovindex ECHO_T
2612 How does one suppress the trailing newline from @command{echo} for
2613 question-answer message pairs?  These variables provide a way:
2615 @example
2616 echo $ECHO_N "And the winner is... $ECHO_C"
2617 sleep 100000000000
2618 echo "$@{ECHO_T@}dead."
2619 @end example
2621 @noindent
2622 Some old and uncommon @command{echo} implementations offer no means to
2623 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2624 want to use it.
2625 @end defvar
2627 @defvar ERLCFLAGS
2628 @evindex ERLCFLAGS
2629 @ovindex ERLCFLAGS
2630 Debugging and optimization options for the Erlang compiler.  If it is not set
2631 in the environment when @command{configure} runs, the default value is empty.
2632 @command{configure} uses this variable when compiling
2633 programs to test for Erlang features.
2634 @end defvar
2636 @defvar FCFLAGS
2637 @evindex FCFLAGS
2638 @ovindex FCFLAGS
2639 Debugging and optimization options for the Fortran compiler.  If it
2640 is not set in the environment when @command{configure} runs, the default
2641 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2642 @command{configure} uses this variable when compiling or linking
2643 programs to test for Fortran features.
2644 @end defvar
2646 @defvar FFLAGS
2647 @evindex FFLAGS
2648 @ovindex FFLAGS
2649 Debugging and optimization options for the Fortran 77 compiler.  If it
2650 is not set in the environment when @command{configure} runs, the default
2651 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2652 @command{configure} uses this variable when compiling or linking
2653 programs to test for Fortran 77 features.
2654 @end defvar
2656 @defvar LDFLAGS
2657 @evindex LDFLAGS
2658 @ovindex LDFLAGS
2659 Options for the linker.  If it is not set
2660 in the environment when @command{configure} runs, the default value is empty.
2661 @command{configure} uses this variable when linking programs to test for
2662 C, C++, Objective C, Objective C++, Fortran, and Go features.
2664 This variable's contents should contain options like @option{-s} and
2665 @option{-L} that affect only the behavior of the linker.  Please see the
2666 explanation of @code{CFLAGS} for what you can do if an option also
2667 affects other phases of the compiler.
2669 Don't use this variable to pass library names
2670 (@option{-l}) to the linker; use @code{LIBS} instead.
2671 @end defvar
2673 @defvar LIBS
2674 @evindex LIBS
2675 @ovindex LIBS
2676 @option{-l} options to pass to the linker.  The default value is empty,
2677 but some Autoconf macros may prepend extra libraries to this variable if
2678 those libraries are found and provide necessary functions, see
2679 @ref{Libraries}.  @command{configure} uses this variable when linking
2680 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2681 features.
2682 @end defvar
2684 @defvar OBJCFLAGS
2685 @evindex OBJCFLAGS
2686 @ovindex OBJCFLAGS
2687 Debugging and optimization options for the Objective C compiler.  It
2688 acts like @code{CFLAGS}, but for Objective C instead of C.
2689 @end defvar
2691 @defvar OBJCXXFLAGS
2692 @evindex OBJCXXFLAGS
2693 @ovindex OBJCXXFLAGS
2694 Debugging and optimization options for the Objective C++ compiler.  It
2695 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2696 @end defvar
2698 @defvar GOFLAGS
2699 @evindex GOFLAGS
2700 @ovindex GOFLAGS
2701 Debugging and optimization options for the Go compiler.  It acts like
2702 @code{CFLAGS}, but for Go instead of C.
2703 @end defvar
2705 @defvar builddir
2706 @ovindex builddir
2707 Rigorously equal to @samp{.}.  Added for symmetry only.
2708 @end defvar
2710 @defvar abs_builddir
2711 @ovindex abs_builddir
2712 Absolute name of @code{builddir}.
2713 @end defvar
2715 @defvar top_builddir
2716 @ovindex top_builddir
2717 The relative name of the top level of the current build tree.  In the
2718 top-level directory, this is the same as @code{builddir}.
2719 @end defvar
2721 @defvar top_build_prefix
2722 @ovindex top_build_prefix
2723 The relative name of the top level of the current build tree with final
2724 slash if nonempty.  This is the same as @code{top_builddir}, except that
2725 it contains zero or more runs of @code{../}, so it should not be
2726 appended with a slash for concatenation.  This helps for @command{make}
2727 implementations that otherwise do not treat @file{./file} and @file{file}
2728 as equal in the toplevel build directory.
2729 @end defvar
2731 @defvar abs_top_builddir
2732 @ovindex abs_top_builddir
2733 Absolute name of @code{top_builddir}.
2734 @end defvar
2736 @defvar srcdir
2737 @ovindex srcdir
2738 The name of the directory that contains the source code for
2739 that makefile.
2740 @end defvar
2742 @defvar abs_srcdir
2743 @ovindex abs_srcdir
2744 Absolute name of @code{srcdir}.
2745 @end defvar
2747 @defvar top_srcdir
2748 @ovindex top_srcdir
2749 The name of the top-level source code directory for the
2750 package.  In the top-level directory, this is the same as @code{srcdir}.
2751 @end defvar
2753 @defvar abs_top_srcdir
2754 @ovindex abs_top_srcdir
2755 Absolute name of @code{top_srcdir}.
2756 @end defvar
2758 @node Installation Directory Variables
2759 @subsection Installation Directory Variables
2760 @cindex Installation directories
2761 @cindex Directories, installation
2763 The following variables specify the directories for
2764 package installation, see @ref{Directory Variables, , Variables for
2765 Installation Directories, standards, The GNU Coding
2766 Standards}, for more information.  Each variable corresponds to an
2767 argument of @command{configure}; trailing slashes are stripped so that
2768 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2769 between directory names.  See the end of this section for
2770 details on when and how to use these variables.
2772 @defvar bindir
2773 @ovindex bindir
2774 The directory for installing executables that users run.
2775 @end defvar
2777 @defvar datadir
2778 @ovindex datadir
2779 The directory for installing idiosyncratic read-only
2780 architecture-independent data.
2781 @end defvar
2783 @defvar datarootdir
2784 @ovindex datarootdir
2785 The root of the directory tree for read-only architecture-independent
2786 data files.
2787 @end defvar
2789 @defvar docdir
2790 @ovindex docdir
2791 The directory for installing documentation files (other than Info and
2792 man).
2793 @end defvar
2795 @defvar dvidir
2796 @ovindex dvidir
2797 The directory for installing documentation files in DVI format.
2798 @end defvar
2800 @defvar exec_prefix
2801 @ovindex exec_prefix
2802 The installation prefix for architecture-dependent files.  By default
2803 it's the same as @code{prefix}.  You should avoid installing anything
2804 directly to @code{exec_prefix}.  However, the default value for
2805 directories containing architecture-dependent files should be relative
2806 to @code{exec_prefix}.
2807 @end defvar
2809 @defvar htmldir
2810 @ovindex htmldir
2811 The directory for installing HTML documentation.
2812 @end defvar
2814 @defvar includedir
2815 @ovindex includedir
2816 The directory for installing C header files.
2817 @end defvar
2819 @defvar infodir
2820 @ovindex infodir
2821 The directory for installing documentation in Info format.
2822 @end defvar
2824 @defvar libdir
2825 @ovindex libdir
2826 The directory for installing object code libraries.
2827 @end defvar
2829 @defvar libexecdir
2830 @ovindex libexecdir
2831 The directory for installing executables that other programs run.
2832 @end defvar
2834 @defvar localedir
2835 @ovindex localedir
2836 The directory for installing locale-dependent but
2837 architecture-independent data, such as message catalogs.  This directory
2838 usually has a subdirectory per locale.
2839 @end defvar
2841 @defvar localstatedir
2842 @ovindex localstatedir
2843 The directory for installing modifiable single-machine data.  Content in
2844 this directory typically survives a reboot.
2845 @end defvar
2847 @defvar runstatedir
2848 @ovindex runstatedir
2849 The directory for installing temporary modifiable single-machine data.
2850 Content in this directory survives as long as the process is running
2851 (such as pid files), as contrasted with @file{/tmp} that may be
2852 periodically cleaned.  Conversely, this directory is typically cleaned
2853 on a reboot.  By default, this is a subdirectory of
2854 @code{localstatedir}.
2855 @end defvar
2857 @defvar mandir
2858 @ovindex mandir
2859 The top-level directory for installing documentation in man format.
2860 @end defvar
2862 @defvar oldincludedir
2863 @ovindex oldincludedir
2864 The directory for installing C header files for non-GCC compilers.
2865 @end defvar
2867 @defvar pdfdir
2868 @ovindex pdfdir
2869 The directory for installing PDF documentation.
2870 @end defvar
2872 @defvar prefix
2873 @ovindex prefix
2874 The common installation prefix for all files.  If @code{exec_prefix}
2875 is defined to a different value, @code{prefix} is used only for
2876 architecture-independent files.
2877 @end defvar
2879 @defvar psdir
2880 @ovindex psdir
2881 The directory for installing PostScript documentation.
2882 @end defvar
2884 @defvar sbindir
2885 @ovindex sbindir
2886 The directory for installing executables that system
2887 administrators run.
2888 @end defvar
2890 @defvar sharedstatedir
2891 @ovindex sharedstatedir
2892 The directory for installing modifiable architecture-independent data.
2893 @end defvar
2895 @defvar sysconfdir
2896 @ovindex sysconfdir
2897 The directory for installing read-only single-machine data.
2898 @end defvar
2901 Most of these variables have values that rely on @code{prefix} or
2902 @code{exec_prefix}.  It is deliberate that the directory output
2903 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2904 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2905 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2907 This behavior is mandated by the GNU Coding Standards, so that when
2908 the user runs:
2910 @table @samp
2911 @item make
2912 she can still specify a different prefix from the one specified to
2913 @command{configure}, in which case, if needed, the package should hard
2914 code dependencies corresponding to the make-specified prefix.
2916 @item make install
2917 she can specify a different installation location, in which case the
2918 package @emph{must} still depend on the location which was compiled in
2919 (i.e., never recompile when @samp{make install} is run).  This is an
2920 extremely important feature, as many people may decide to install all
2921 the files of a package grouped together, and then install links from
2922 the final locations to there.
2923 @end table
2925 In order to support these features, it is essential that
2926 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2927 so that its value can be expanded based
2928 on the current value of @code{prefix}.
2930 A corollary is that you should not use these variables except in
2931 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2932 in @file{configure} and hard-coding it in makefiles using
2933 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2934 you should add
2935 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2936 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2938 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2939 @code{bindir} and friends in your shell scripts and other files; instead,
2940 let @command{make} manage their replacement.  For instance Autoconf
2941 ships templates of its shell scripts ending with @samp{.in}, and uses a
2942 makefile snippet similar to the following to build scripts like
2943 @command{autoheader} and @command{autom4te}:
2945 @example
2946 @group
2947 edit = sed \
2948         -e 's|@@bindir[@@]|$(bindir)|g' \
2949         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2950         -e 's|@@prefix[@@]|$(prefix)|g'
2951 @end group
2953 @group
2954 autoheader autom4te: Makefile
2955         rm -f $@@ $@@.tmp
2956         srcdir=''; \
2957           test -f ./$@@.in || srcdir=$(srcdir)/; \
2958           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2959 @c $$ restore font-lock
2960         chmod +x $@@.tmp
2961         chmod a-w $@@.tmp
2962         mv $@@.tmp $@@
2963 @end group
2965 @group
2966 autoheader: $(srcdir)/autoheader.in
2967 autom4te: $(srcdir)/autom4te.in
2968 @end group
2969 @end example
2971 Some details are noteworthy:
2973 @table @asis
2974 @item @samp{@@bindir[@@]}
2975 The brackets prevent @command{configure} from replacing
2976 @samp{@@bindir@@} in the Sed expression itself.
2977 Brackets are preferable to a backslash here, since
2978 Posix says @samp{\@@} is not portable.
2980 @item @samp{$(bindir)}
2981 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2982 instead.
2984 @item @samp{$(pkgdatadir)}
2985 The example takes advantage of the variable @samp{$(pkgdatadir)}
2986 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2988 @item @samp{/}
2989 Don't use @samp{/} in the Sed expressions that replace file names since
2990 most likely the
2991 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2992 Use a shell metacharacter instead, such as @samp{|}.
2994 @item special characters
2995 File names, file name components, and the value of @code{VPATH} should
2996 not contain shell metacharacters or white
2997 space.  @xref{Special Chars in Variables}.
2999 @item dependency on @file{Makefile}
3000 Since @code{edit} uses values that depend on the configuration specific
3001 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
3002 the output depends on @file{Makefile}, not @file{configure.ac}.
3004 @item @samp{$@@}
3005 The main rule is generic, and uses @samp{$@@} extensively to
3006 avoid the need for multiple copies of the rule.
3008 @item Separated dependencies and single suffix rules
3009 You can't use them!  The above snippet cannot be (portably) rewritten
3012 @example
3013 autoconf autoheader: Makefile
3014 @group
3015 .in:
3016         rm -f $@@ $@@.tmp
3017         $(edit) $< >$@@.tmp
3018         chmod +x $@@.tmp
3019         mv $@@.tmp $@@
3020 @end group
3021 @end example
3023 @xref{Single Suffix Rules}, for details.
3025 @item @samp{$(srcdir)}
3026 Be sure to specify the name of the source directory,
3027 otherwise the package won't support separated builds.
3028 @end table
3030 For the more specific installation of Erlang libraries, the following variables
3031 are defined:
3033 @defvar ERLANG_INSTALL_LIB_DIR
3034 @ovindex ERLANG_INSTALL_LIB_DIR
3035 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3036 The common parent directory of Erlang library installation directories.
3037 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3038 macro in @file{configure.ac}.
3039 @end defvar
3041 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3042 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3043 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3044 The installation directory for Erlang library @var{library}.
3045 This variable is set by using the
3046 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3047 macro in @file{configure.ac}.
3048 @end defvar
3050 @xref{Erlang Libraries}, for details.
3053 @node Changed Directory Variables
3054 @subsection Changed Directory Variables
3055 @cindex @file{datarootdir}
3057 In Autoconf 2.60, the set of directory variables has changed, and the
3058 defaults of some variables have been adjusted
3059 (@pxref{Installation Directory Variables}) to changes in the
3060 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3061 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3062 upgrading from an earlier Autoconf version, you may need to adjust your files
3063 to ensure that the directory variables are substituted correctly
3064 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3065 in place.  For example, in a @file{Makefile.in}, adding
3067 @example
3068 datarootdir = @@datarootdir@@
3069 @end example
3071 @noindent
3072 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3073 it will add this for you.
3075 To help with the transition, Autoconf warns about files that seem to use
3076 @code{datarootdir} without defining it.  In some cases, it then expands
3077 the value of @code{$datarootdir} in substitutions of the directory
3078 variables.  The following example shows such a warning:
3080 @example
3081 $ @kbd{cat configure.ac}
3082 AC_INIT
3083 AC_CONFIG_FILES([Makefile])
3084 AC_OUTPUT
3085 $ @kbd{cat Makefile.in}
3086 prefix = @@prefix@@
3087 datadir = @@datadir@@
3088 $ @kbd{autoconf}
3089 $ @kbd{configure}
3090 configure: creating ./config.status
3091 config.status: creating Makefile
3092 config.status: WARNING:
3093                Makefile.in seems to ignore the --datarootdir setting
3094 $ @kbd{cat Makefile}
3095 prefix = /usr/local
3096 datadir = $@{prefix@}/share
3097 @end example
3099 Usually one can easily change the file to accommodate both older and newer
3100 Autoconf releases:
3102 @example
3103 $ @kbd{cat Makefile.in}
3104 prefix = @@prefix@@
3105 datarootdir = @@datarootdir@@
3106 datadir = @@datadir@@
3107 $ @kbd{configure}
3108 configure: creating ./config.status
3109 config.status: creating Makefile
3110 $ @kbd{cat Makefile}
3111 prefix = /usr/local
3112 datarootdir = $@{prefix@}/share
3113 datadir = $@{datarootdir@}
3114 @end example
3116 @acindex{DATAROOTDIR_CHECKED}
3117 In some cases, however, the checks may not be able to detect that a suitable
3118 initialization of @code{datarootdir} is in place, or they may fail to detect
3119 that such an initialization is necessary in the output file.  If, after
3120 auditing your package, there are still spurious @file{configure} warnings about
3121 @code{datarootdir}, you may add the line
3123 @example
3124 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3125 @end example
3127 @noindent
3128 to your @file{configure.ac} to disable the warnings.  This is an exception
3129 to the usual rule that you should not define a macro whose name begins with
3130 @code{AC_} (@pxref{Macro Names}).
3134 @node Build Directories
3135 @subsection Build Directories
3136 @cindex Build directories
3137 @cindex Directories, build
3139 You can support compiling a software package for several architectures
3140 simultaneously from the same copy of the source code.  The object files
3141 for each architecture are kept in their own directory.
3143 To support doing this, @command{make} uses the @code{VPATH} variable to
3144 find the files that are in the source directory.  GNU Make
3145 can do this.  Most other recent @command{make} programs can do this as
3146 well, though they may have difficulties and it is often simpler to
3147 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3148 @command{make} programs do not support @code{VPATH}; when using them, the
3149 source code must be in the same directory as the object files.
3151 If you are using GNU Automake, the remaining details in this
3152 section are already covered for you, based on the contents of your
3153 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3154 supporting @code{VPATH} requires the following in your
3155 @file{Makefile.in}:
3157 @example
3158 srcdir = @@srcdir@@
3159 VPATH = @@srcdir@@
3160 @end example
3162 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3163 listed in VPATH}.
3165 @command{configure} substitutes the correct value for @code{srcdir} when
3166 it produces @file{Makefile}.
3168 Do not use the @command{make} variable @code{$<}, which expands to the
3169 file name of the file in the source directory (found with @code{VPATH}),
3170 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3171 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3172 versions of @command{make} do not set @code{$<} in explicit rules; they
3173 expand it to an empty value.
3175 Instead, Make command lines should always refer to source
3176 files by prefixing them with @samp{$(srcdir)/}.  It's safer
3177 to quote the source directory name, in case it contains characters that
3178 are special to the shell.  Because @samp{$(srcdir)} is expanded by Make,
3179 single-quoting works and is safer than double-quoting.  For example:
3181 @example
3182 time.info: time.texinfo
3183         $(MAKEINFO) '$(srcdir)/time.texinfo'
3184 @end example
3186 @node Automatic Remaking
3187 @subsection Automatic Remaking
3188 @cindex Automatic remaking
3189 @cindex Remaking automatically
3191 You can put rules like the following in the top-level @file{Makefile.in}
3192 for a package to automatically update the configuration information when
3193 you change the configuration files.  This example includes all of the
3194 optional files, such as @file{aclocal.m4} and those related to
3195 configuration header files.  Omit from the @file{Makefile.in} rules for
3196 any of these files that your package does not use.
3198 The @samp{$(srcdir)/} prefix is included because of limitations in the
3199 @code{VPATH} mechanism.
3201 The @file{stamp-} files are necessary because the timestamps of
3202 @file{config.h.in} and @file{config.h} are not changed if remaking
3203 them does not change their contents.  This feature avoids unnecessary
3204 recompilation.  You should include the file @file{stamp-h.in} in your
3205 package's distribution, so that @command{make} considers
3206 @file{config.h.in} up to date.  Don't use @command{touch}
3207 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3208 @command{echo} (using
3209 @command{date} would cause needless differences, hence CVS
3210 conflicts, etc.).
3212 @example
3213 @group
3214 $(srcdir)/configure: configure.ac aclocal.m4
3215         cd '$(srcdir)' && autoconf
3217 # autoheader might not change config.h.in, so touch a stamp file.
3218 $(srcdir)/config.h.in: stamp-h.in ;
3219 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3220         cd '$(srcdir)' && autoheader
3221         echo timestamp > '$(srcdir)/stamp-h.in'
3223 config.h: stamp-h ;
3224 stamp-h: config.h.in config.status
3225         ./config.status
3227 Makefile: Makefile.in config.status
3228         ./config.status
3230 config.status: configure
3231         ./config.status --recheck
3232 @end group
3233 @end example
3235 @noindent
3236 (Be careful if you copy these lines directly into your makefile, as you
3237 need to convert the indented lines to start with the tab character.)
3239 In addition, you should use
3241 @example
3242 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3243 @end example
3245 @noindent
3246 so @file{config.status} ensures that @file{config.h} is considered up to
3247 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3249 @xref{config.status Invocation}, for more examples of handling
3250 configuration-related dependencies.
3252 @node Configuration Headers
3253 @section Configuration Header Files
3254 @cindex Configuration Header
3255 @cindex @file{config.h}
3257 When a package contains more than a few tests that define C preprocessor
3258 symbols, the command lines to pass @option{-D} options to the compiler
3259 can get quite long.  This causes two problems.  One is that the
3260 @command{make} output is hard to visually scan for errors.  More
3261 seriously, the command lines can exceed the length limits of some
3262 operating systems.  As an alternative to passing @option{-D} options to
3263 the compiler, @command{configure} scripts can create a C header file
3264 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3265 macro selects this kind of output.  Though it can be called anywhere
3266 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3267 it right after @code{AC_INIT}.
3269 The package should @samp{#include} the configuration header file before
3270 any other header files, to prevent inconsistencies in declarations (for
3271 example, if it redefines @code{const}, or if it defines a macro like
3272 @code{_FILE_OFFSET_BITS} that affects the behavior of system
3273 headers). Note that it is okay to only include @file{config.h} from
3274 @file{.c} files; the project's @file{.h} files can rely on
3275 @file{config.h} already being included first by the corresponding
3276 @file{.c} file.
3278 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3279 option (or @option{-I..}; whichever directory contains @file{config.h}).
3280 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3281 the directory of the currently read file, i.e., the source directory, not
3282 the build directory.
3284 With the appropriate @option{-I} option, you can use
3285 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3286 because in the rare case when the source directory contains another
3287 @file{config.h}, the build directory should be searched first.
3290 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3291 @acindex{CONFIG_HEADERS}
3292 @cvindex HAVE_CONFIG_H
3293 This macro is one of the instantiating macros; see @ref{Configuration
3294 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3295 blank-or-newline-separated list @var{header} containing C preprocessor
3296 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3297 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3298 The usual name for @var{header} is @file{config.h}.
3300 If @var{header} already exists and its contents are identical to what
3301 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3302 making some changes in the configuration without needlessly causing
3303 object files that depend on the header file to be recompiled.
3305 Usually the input file is named @file{@var{header}.in}; however, you can
3306 override the input file name by appending to @var{header} a
3307 colon-separated list of input files.  For example, you might need to make
3308 the input file name acceptable to DOS variants:
3310 @example
3311 AC_CONFIG_HEADERS([config.h:config.hin])
3312 @end example
3314 @end defmac
3316 @defmac AH_HEADER
3317 @ahindex{HEADER}
3318 This macro is defined as the name of the first declared config header
3319 and undefined if no config headers have been declared up to this point.
3320 A third-party macro may, for example, require use of a config header
3321 without invoking AC_CONFIG_HEADERS twice, like this:
3323 @example
3324 AC_CONFIG_COMMANDS_PRE(
3325         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3326 @end example
3328 @end defmac
3330 @xref{Configuration Actions}, for more details on @var{header}.
3332 @menu
3333 * Header Templates::            Input for the configuration headers
3334 * autoheader Invocation::       How to create configuration templates
3335 * Autoheader Macros::           How to specify CPP templates
3336 @end menu
3338 @node Header Templates
3339 @subsection Configuration Header Templates
3340 @cindex Configuration Header Template
3341 @cindex Header templates
3342 @cindex @file{config.h.in}
3344 Your distribution should contain a template file that looks as you want
3345 the final header file to look, including comments, with @code{#undef}
3346 statements which are used as hooks.  For example, suppose your
3347 @file{configure.ac} makes these calls:
3349 @example
3350 AC_CONFIG_HEADERS([conf.h])
3351 AC_CHECK_HEADERS([unistd.h])
3352 @end example
3354 @noindent
3355 Then you could have code like the following in @file{conf.h.in}.
3356 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3357 to 1, if and only if the system has @file{unistd.h}.
3359 @example
3360 @group
3361 /* Define as 1 if you have unistd.h.  */
3362 #undef HAVE_UNISTD_H
3363 @end group
3364 @end example
3366 The format of the template file is stricter than what the C preprocessor
3367 is required to accept.  A directive line should contain only whitespace,
3368 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3369 instead of @samp{#undef}, or of comments on the same line as
3370 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3371 once.  Other preprocessor lines, such as @samp{#ifdef} or
3372 @samp{#include}, are copied verbatim from the template into the
3373 generated header.
3375 Since it is a tedious task to keep a template header up to date, you may
3376 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3378 During the instantiation of the header, each @samp{#undef} line in the
3379 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3380 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3381 been executed during the @command{configure} run, the @samp{#undef} line is
3382 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3383 on many systems, it can be implicitly defined by the compiler, and
3384 undefining it in the header would then break compilation of subsequent
3385 headers.)
3387 Currently, @emph{all} remaining @samp{#undef} lines in the header
3388 template are commented out, whether or not there was a corresponding
3389 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3390 for future releases of Autoconf.
3392 Generally speaking, since you should not use @samp{#define}, and you
3393 cannot guarantee whether a @samp{#undef} directive in the header
3394 template will be converted to a @samp{#define} or commented out in the
3395 generated header file, the template file cannot be used for conditional
3396 definition effects.  Consequently, if you need to use the construct
3398 @example
3399 @group
3400 #ifdef THIS
3401 # define THAT
3402 #endif
3403 @end group
3404 @end example
3406 @noindent
3407 you must place it outside of the template.
3408 If you absolutely need to hook it to the config header itself, please put
3409 the directives to a separate file, and @samp{#include} that file from the
3410 config header template.  If you are using @command{autoheader}, you would
3411 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3414 @node autoheader Invocation
3415 @subsection Using @command{autoheader} to Create @file{config.h.in}
3416 @cindex @command{autoheader}
3418 The @command{autoheader} program can create a template file of C
3419 @samp{#define} statements for @command{configure} to use.
3420 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3421 @file{configure} sources to determine the name of the template.
3422 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3423 input file name, @command{autoheader} uses the first one.)
3425 It is recommended that only one input file is used.  If you want to append
3426 a boilerplate code, it is preferable to use
3427 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3428 File @file{conf_post.h} is not processed during the configuration then,
3429 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3430 prepend a boilerplate code.
3432 In order to do its job, @command{autoheader} needs you to document all
3433 of the symbols that you might use.  Typically this is done via an
3434 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3435 is a literal symbol and whose third argument describes the symbol
3436 (@pxref{Defining Symbols}).  Alternatively, you can use
3437 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3438 suitable input file for a subsequent configuration header file.
3439 Symbols defined by Autoconf's builtin tests are already documented properly;
3440 you need to document only those that you
3441 define yourself.
3443 You might wonder why @command{autoheader} is needed: after all, why
3444 would @command{configure} need to ``patch'' a @file{config.h.in} to
3445 produce a @file{config.h} instead of just creating @file{config.h} from
3446 scratch?  Well, when everything rocks, the answer is just that we are
3447 wasting our time maintaining @command{autoheader}: generating
3448 @file{config.h} directly is all that is needed.  When things go wrong,
3449 however, you'll be thankful for the existence of @command{autoheader}.
3451 The fact that the symbols are documented is important in order to
3452 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3453 well-defined list of symbols that should be defined (or not) is
3454 also important for people who are porting packages to environments where
3455 @command{configure} cannot be run: they just have to @emph{fill in the
3456 blanks}.
3458 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3460 If you give @command{autoheader} an argument, it uses that file instead
3461 of @file{configure.ac} and writes the header file to the standard output
3462 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3463 argument of @option{-}, it reads the standard input instead of
3464 @file{configure.ac} and writes the header file to the standard output.
3466 @command{autoheader} accepts the following options:
3468 @table @option
3469 @item --help
3470 @itemx -h
3471 Print a summary of the command line options and exit.
3473 @item --version
3474 @itemx -V
3475 Print the version number of Autoconf and exit.
3477 @item --verbose
3478 @itemx -v
3479 Report processing steps.
3481 @item --debug
3482 @itemx -d
3483 Don't remove the temporary files.
3485 @item --force
3486 @itemx -f
3487 Remake the template file even if newer than its input files.
3489 @item --include=@var{dir}
3490 @itemx -I @var{dir}
3491 Append @var{dir} to the include path.  Multiple invocations accumulate.
3493 @item --prepend-include=@var{dir}
3494 @itemx -B @var{dir}
3495 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3497 @item --warnings=@var{category}
3498 @itemx -W @var{category}
3499 @evindex WARNINGS
3500 Report the warnings related to @var{category} (which can actually be a
3501 comma separated list).  Current categories include:
3503 @table @samp
3504 @item obsolete
3505 report the uses of obsolete constructs
3507 @item all
3508 report all the warnings
3510 @item none
3511 report none
3513 @item error
3514 treats warnings as errors
3516 @item no-@var{category}
3517 disable warnings falling into @var{category}
3518 @end table
3520 @end table
3524 @node Autoheader Macros
3525 @subsection Autoheader Macros
3526 @cindex Autoheader macros
3528 @command{autoheader} scans @file{configure.ac} and figures out which C
3529 preprocessor symbols it might define.  It knows how to generate
3530 templates for symbols defined by @code{AC_CHECK_HEADERS},
3531 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3532 symbol, you must define a template for it.  If there are missing
3533 templates, @command{autoheader} fails with an error message.
3535 The template for a @var{symbol} is created
3536 by @command{autoheader} from
3537 the @var{description} argument to an @code{AC_DEFINE};
3538 see @ref{Defining Symbols}.
3540 For special needs, you can use the following macros.
3543 @defmac AH_TEMPLATE (@var{key}, @var{description})
3544 @ahindex{TEMPLATE}
3545 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3546 generates standard templates just like @code{AC_DEFINE} when a
3547 @var{description} is given.
3549 For example:
3551 @example
3552 AH_TEMPLATE([CRAY_STACKSEG_END],
3553             [Define to one of _getb67, GETB67, getb67
3554              for Cray-2 and Cray-YMP systems.  This
3555              function is required for alloca.c support
3556              on those systems.])
3557 @end example
3559 @noindent
3560 generates the following template, with the description properly
3561 justified.
3563 @example
3564 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3565    Cray-YMP systems.  This function is required for alloca.c
3566    support on those systems.  */
3567 #undef CRAY_STACKSEG_END
3568 @end example
3569 @end defmac
3572 @defmac AH_VERBATIM (@var{key}, @var{template})
3573 @ahindex{VERBATIM}
3574 Tell @command{autoheader} to include the @var{template} as-is in the header
3575 template file.  This @var{template} is associated with the @var{key},
3576 which is used to sort all the different templates and guarantee their
3577 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3578 @end defmac
3581 @defmac AH_TOP (@var{text})
3582 @ahindex{TOP}
3583 Include @var{text} at the top of the header template file.
3584 @end defmac
3587 @defmac AH_BOTTOM (@var{text})
3588 @ahindex{BOTTOM}
3589 Include @var{text} at the bottom of the header template file.
3590 @end defmac
3593 Please note that @var{text} gets included ``verbatim'' to the template file,
3594 not to the resulting config header, so it can easily get mangled when the
3595 template is processed.  There is rarely a need for something other than
3597 @example
3598 AH_BOTTOM([#include <custom.h>])
3599 @end example
3603 @node Configuration Commands
3604 @section Running Arbitrary Configuration Commands
3605 @cindex Configuration commands
3606 @cindex Commands for configuration
3608 You can execute arbitrary commands before, during, and after
3609 @file{config.status} is run.  The three following macros accumulate the
3610 commands to run when they are called multiple times.
3611 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3612 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3614 @anchor{AC_CONFIG_COMMANDS}
3615 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3616 @acindex{CONFIG_COMMANDS}
3617 Specify additional shell commands to run at the end of
3618 @file{config.status}, and shell commands to initialize any variables
3619 from @command{configure}.  Associate the commands with @var{tag}.
3620 Since typically the @var{cmds} create a file, @var{tag} should
3621 naturally be the name of that file.  If needed, the directory hosting
3622 @var{tag} is created.  This macro is one of the instantiating macros;
3623 see @ref{Configuration Actions}.
3625 Here is an unrealistic example:
3626 @example
3627 fubar=42
3628 AC_CONFIG_COMMANDS([fubar],
3629                    [echo this is extra $fubar, and so on.],
3630                    [fubar=$fubar])
3631 @end example
3633 Here is a better one:
3634 @example
3635 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3636 @end example
3637 @end defmac
3639 The following two macros look similar, but in fact they are not of the same
3640 breed: they are executed directly by @file{configure}, so you cannot use
3641 @file{config.status} to rerun them.
3643 @c Yet it is good to leave them here.  The user sees them together and
3644 @c decides which best fits their needs.
3646 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3647 @acindex{CONFIG_COMMANDS_PRE}
3648 Execute the @var{cmds} right before creating @file{config.status}.
3650 This macro presents the last opportunity to call @code{AC_SUBST},
3651 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3652 @end defmac
3654 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3655 @acindex{CONFIG_COMMANDS_POST}
3656 Execute the @var{cmds} right after creating @file{config.status}.
3657 @end defmac
3662 @node Configuration Links
3663 @section Creating Configuration Links
3664 @cindex Configuration links
3665 @cindex Links for configuration
3667 You may find it convenient to create links whose destinations depend upon
3668 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3669 creation of relative symbolic links can be delicate when the package is
3670 built in a directory different from the source directory.
3672 @anchor{AC_CONFIG_LINKS}
3673 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3674   @ovar{init-cmds})
3675 @acindex{CONFIG_LINKS}
3676 @cindex Links
3677 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3678 the corresponding link name @var{dest}.  Makes a symbolic link if
3679 possible, otherwise a hard link if possible, otherwise a copy.  The
3680 @var{dest} and @var{source} names should be relative to the top level
3681 source or build directory.  This macro is one of the instantiating
3682 macros; see @ref{Configuration Actions}.
3684 For example, this call:
3686 @example
3687 AC_CONFIG_LINKS([host.h:config/$machine.h
3688                 object.h:config/$obj_format.h])
3689 @end example
3691 @noindent
3692 creates in the current directory @file{host.h} as a link to
3693 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3694 link to @file{@var{srcdir}/config/$obj_format.h}.
3696 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3697 impossible for @samp{config.status} to guess the links to establish.
3699 One can then run:
3700 @example
3701 ./config.status host.h object.h
3702 @end example
3703 @noindent
3704 to create the links.
3705 @end defmac
3709 @node Subdirectories
3710 @section Configuring Other Packages in Subdirectories
3711 @cindex Configure subdirectories
3712 @cindex Subdirectory configure
3714 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3715 makefiles in subdirectories.  However, @command{configure} scripts
3716 that control more than one independent package can use
3717 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3718 packages in subdirectories.
3720 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3721 @acindex{CONFIG_SUBDIRS}
3722 @ovindex subdirs
3723 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3724 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3725 be a literal, i.e., please do not use:
3727 @example
3728 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3729 if test "x$package_foo_enabled" = xyes; then
3730   my_subdirs="$my_subdirs foo"
3732 AC_CONFIG_SUBDIRS([$my_subdirs])
3733 @end example
3735 @noindent
3736 because this prevents @samp{./configure --help=recursive} from
3737 displaying the options of the package @code{foo}.  Instead, you should
3738 write:
3740 @example
3741 if test "x$package_foo_enabled" = xyes; then
3742   AC_CONFIG_SUBDIRS([foo])
3744 @end example
3746 If a given @var{dir} is not found at @command{configure} run time, a
3747 warning is reported; if the subdirectory is optional, write:
3749 @example
3750 if test -d "$srcdir/foo"; then
3751   AC_CONFIG_SUBDIRS([foo])
3753 @end example
3755 @c NB: Yes, below we mean configure.in, not configure.ac.
3756 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3757 of @command{configure}.  This is for packages that might use a
3758 non-Autoconf script @command{Configure}, which can't be called through a
3759 wrapper @command{configure} since it would be the same file on
3760 case-insensitive file systems.  Likewise, if a @var{dir} contains
3761 @file{configure.in} but no @command{configure}, the Cygnus
3762 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3764 The subdirectory @command{configure} scripts are given the same command
3765 line options that were given to this @command{configure} script, with minor
3766 changes if needed, which include:
3768 @itemize @minus
3769 @item
3770 adjusting a relative name for the cache file;
3772 @item
3773 adjusting a relative name for the source directory;
3775 @item
3776 propagating the current value of @code{$prefix}, including if it was
3777 defaulted, and if the default values of the top level and of the subdirectory
3778 @file{configure} differ.
3779 @end itemize
3781 This macro also sets the output variable @code{subdirs} to the list of
3782 directories @samp{@var{dir} @dots{}}.  Make rules can use
3783 this variable to determine which subdirectories to recurse into.
3785 This macro may be called multiple times.
3786 @end defmac
3788 @node Default Prefix
3789 @section Default Prefix
3790 @cindex Install prefix
3791 @cindex Prefix for install
3793 By default, @command{configure} sets the prefix for files it installs to
3794 @file{/usr/local}.  The user of @command{configure} can select a different
3795 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3796 There are two ways to change the default: when creating
3797 @command{configure}, and when running it.
3799 Some software packages might want to install in a directory other than
3800 @file{/usr/local} by default.  To accomplish that, use the
3801 @code{AC_PREFIX_DEFAULT} macro.
3803 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3804 @acindex{PREFIX_DEFAULT}
3805 Set the default installation prefix to @var{prefix} instead of
3806 @file{/usr/local}.
3807 @end defmac
3809 It may be convenient for users to have @command{configure} guess the
3810 installation prefix from the location of a related program that they
3811 have already installed.  If you wish to do that, you can call
3812 @code{AC_PREFIX_PROGRAM}.
3814 @anchor{AC_PREFIX_PROGRAM}
3815 @defmac AC_PREFIX_PROGRAM (@var{program})
3816 @acindex{PREFIX_PROGRAM}
3817 If the user did not specify an installation prefix (using the
3818 @option{--prefix} option), guess a value for it by looking for
3819 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3820 is found, set the prefix to the parent of the directory containing
3821 @var{program}, else default the prefix as described above
3822 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3823 @var{program} is @code{gcc} and the @env{PATH} contains
3824 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3825 @end defmac
3829 @c ======================================================== Existing tests
3831 @node Existing Tests
3832 @chapter Existing Tests
3834 These macros test for particular system features that packages might
3835 need or want to use.  If you need to test for a kind of feature that
3836 none of these macros check for, you can probably do it by calling
3837 primitive test macros with appropriate arguments (@pxref{Writing
3838 Tests}).
3840 These tests print messages telling the user which feature they're
3841 checking for, and what they find.  They cache their results for future
3842 @command{configure} runs (@pxref{Caching Results}).
3844 Some of these macros set output variables.  @xref{Makefile
3845 Substitutions}, for how to get their values.  The phrase ``define
3846 @var{name}'' is used below as a shorthand to mean ``define the C
3847 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3848 Symbols}, for how to get those symbol definitions into your program.
3850 @menu
3851 * Common Behavior::             Macros' standard schemes
3852 * Alternative Programs::        Selecting between alternative programs
3853 * Files::                       Checking for the existence of files
3854 * Libraries::                   Library archives that might be missing
3855 * Library Functions::           C library functions that might be missing
3856 * Header Files::                Header files that might be missing
3857 * Declarations::                Declarations that may be missing
3858 * Structures::                  Structures or members that might be missing
3859 * Types::                       Types that might be missing
3860 * Compilers and Preprocessors::  Checking for compiling programs
3861 * System Services::             Operating system services
3862 * C and Posix Variants::        Kludges for C and Posix variants
3863 * Erlang Libraries::            Checking for the existence of Erlang libraries
3864 @end menu
3866 @node Common Behavior
3867 @section Common Behavior
3868 @cindex Common autoconf behavior
3870 Much effort has been expended to make Autoconf easy to learn.  The most
3871 obvious way to reach this goal is simply to enforce standard interfaces
3872 and behaviors, avoiding exceptions as much as possible.  Because of
3873 history and inertia, unfortunately, there are still too many exceptions
3874 in Autoconf; nevertheless, this section describes some of the common
3875 rules.
3877 @menu
3878 * Standard Symbols::            Symbols defined by the macros
3879 * Default Includes::            Includes used by the generic macros
3880 @end menu
3882 @node Standard Symbols
3883 @subsection Standard Symbols
3884 @cindex Standard symbols
3886 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3887 their test transform their @var{argument} values to a standard alphabet.
3888 First, @var{argument} is converted to upper case and any asterisks
3889 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3890 that are not alphanumeric are converted to underscores.
3892 For instance,
3894 @example
3895 AC_CHECK_TYPES([struct $Expensive*])
3896 @end example
3898 @noindent
3899 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3900 succeeds.
3903 @node Default Includes
3904 @subsection Default Includes
3905 @cindex Default includes
3906 @cindex Includes, default
3907 @hdrindex{assert.h}
3908 @hdrindex{ctype.h}
3909 @hdrindex{errno.h}
3910 @hdrindex{float.h}
3911 @hdrindex{iso646.h}
3912 @hdrindex{limits.h}
3913 @hdrindex{locale.h}
3914 @hdrindex{math.h}
3915 @hdrindex{setjmp.h}
3916 @hdrindex{signal.h}
3917 @hdrindex{stdarg.h}
3918 @hdrindex{stddef.h}
3919 @hdrindex{stdio.h}
3920 @hdrindex{stdlib.h}
3921 @hdrindex{string.h}
3922 @hdrindex{time.h}
3923 @hdrindex{wchar.h}
3924 @hdrindex{wctype.h}
3926 Test programs frequently need to include headers that may or may not be
3927 available on the system whose features are being tested.  Each test can
3928 use all the preprocessor macros that have been @code{AC_DEFINE}d by
3929 previous tests, so for example one may write
3931 @example
3932 @group
3933 #include <time.h>
3934 #ifdef HAVE_SYS_TIME_H
3935 # include <sys/time.h>
3936 #endif
3937 @end group
3938 @end example
3940 @noindent
3941 if @file{sys/time.h} has already been tested for.
3943 All hosted environments that are still of interest for portable code
3944 provide all of the headers specified in ISO C90 (as amended in 1995):
3945 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
3946 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
3947 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
3948 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
3949 @file{wchar.h}, and @file{wctype.h}.  Most programs can safely include
3950 these headers unconditionally.  All other headers, including all headers
3951 from later revisions of the C standard, need to be tested for
3952 (@pxref{Header Files}).
3954 If your program needs to be portable to a @emph{freestanding}
3955 environment, such as an embedded OS that doesn't provide all of the
3956 facilities of the C90 standard library, you may need to test for some of
3957 the above headers as well.  Note that many Autoconf macros internally
3958 assume that the complete set of C90 headers are available.
3960 Most generic macros use the following macro to provide a default set
3961 of includes:
3963 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3964 @acindex{INCLUDES_DEFAULT}
3965 Expand to @var{include-directives} if present and nonempty, otherwise to:
3967 @example
3968 @group
3969 #include <stddef.h>
3970 #include <stdio.h>
3971 #include <stdlib.h>
3972 #include <string.h>
3973 #ifdef HAVE_SYS_TYPES_H
3974 # include <sys/types.h>
3975 #endif
3976 #ifdef HAVE_SYS_STAT_H
3977 # include <sys/stat.h>
3978 #endif
3979 #ifdef HAVE_STRINGS_H
3980 # include <strings.h>
3981 #endif
3982 #ifdef HAVE_INTTYPES_H
3983 # include <inttypes.h>
3984 #endif
3985 #ifdef HAVE_STDINT_H
3986 # include <stdint.h>
3987 #endif
3988 #ifdef HAVE_UNISTD_H
3989 # include <unistd.h>
3990 #endif
3991 @end group
3992 @end example
3994 Using this macro without @var{include-directives} has the side effect of
3995 checking for @file{sys/types.h}, @file{sys/stat.h}, @file{strings.h},
3996 @file{inttypes.h}, @file{stdint.h}, and @file{unistd.h}, as if by
3997 @code{AC_CHECK_HEADERS}.  For backward compatibility's sake, it also
3998 unconditionally defines @code{HAVE_STRING_H}, @code{HAVE_STDLIB_H}, and
3999 @code{STDC_HEADERS}.  New code should not make use of these preprocessor
4000 macros.
4001 @end defmac
4003 @defmac AC_CHECK_INCLUDES_DEFAULT
4004 @acindex{CHECK_INCLUDES_DEFAULT}
4005 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
4006 for as a side-effect, if this has not already happened.
4008 This macro mainly exists so that @code{autoupdate} can replace certain
4009 obsolete constructs with it. You should not need to use it yourself; in
4010 fact, it is likely to be safe to delete it from any script in which it
4011 appears.  (@code{autoupdate} does not know whether preprocessor macros
4012 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
4013 would get defined as a side-effect of other checks.)
4014 @end defmac
4016 @node Alternative Programs
4017 @section Alternative Programs
4018 @cindex Programs, checking
4020 These macros check for the presence or behavior of particular programs.
4021 They are used to choose between several alternative programs and to
4022 decide what to do once one has been chosen.  If there is no macro
4023 specifically defined to check for a program you need, and you don't need
4024 to check for any special properties of it, then you can use one of the
4025 general program-check macros.
4027 @menu
4028 * Particular Programs::         Special handling to find certain programs
4029 * Generic Programs::            How to find other programs
4030 @end menu
4032 @node Particular Programs
4033 @subsection Particular Program Checks
4035 These macros check for particular programs---whether they exist, and
4036 in some cases whether they support certain features.
4038 @defmac AC_PROG_AWK
4039 @acindex{PROG_AWK}
4040 @ovindex AWK
4041 @caindex prog_AWK
4042 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4043 order, and set output variable @code{AWK} to the first one that is found.
4044 It tries @code{gawk} first because that is reported to be the
4045 best implementation.  The result can be overridden by setting the
4046 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4048 Using this macro is sufficient to avoid the pitfalls of traditional
4049 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4050 @end defmac
4052 @defmac AC_PROG_GREP
4053 @acindex{PROG_GREP}
4054 @ovindex GREP
4055 @caindex prog_GREP
4056 Look for the best available @code{grep} or @code{ggrep} that accepts the
4057 longest input lines possible, and that supports multiple @option{-e} options.
4058 Set the output variable @code{GREP} to whatever is chosen.
4059 @xref{grep, , Limitations of Usual Tools}, for more information about
4060 portability problems with the @command{grep} command family.  The result
4061 can be overridden by setting the @code{GREP} variable and is cached in the
4062 @code{ac_cv_path_GREP} variable.
4063 @end defmac
4065 @defmac AC_PROG_EGREP
4066 @acindex{PROG_EGREP}
4067 @ovindex EGREP
4068 @caindex prog_EGREP
4069 Check whether @code{$GREP -E} works, or else look for the best available
4070 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4071 Set the output variable @code{EGREP} to whatever is chosen.  The result
4072 can be overridden by setting the @code{EGREP} variable and is cached in the
4073 @code{ac_cv_path_EGREP} variable.
4074 @end defmac
4076 @defmac AC_PROG_FGREP
4077 @acindex{PROG_FGREP}
4078 @ovindex FGREP
4079 @caindex prog_FGREP
4080 Check whether @code{$GREP -F} works, or else look for the best available
4081 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4082 Set the output variable @code{FGREP} to whatever is chosen.  The result
4083 can be overridden by setting the @code{FGREP} variable and is cached in the
4084 @code{ac_cv_path_FGREP} variable.
4085 @end defmac
4087 @defmac AC_PROG_INSTALL
4088 @acindex{PROG_INSTALL}
4089 @ovindex INSTALL
4090 @ovindex INSTALL_PROGRAM
4091 @ovindex INSTALL_DATA
4092 @ovindex INSTALL_SCRIPT
4093 @caindex path_install
4094 Set output variable @code{INSTALL} to the name of a BSD-compatible
4095 @command{install} program, if one is found in the current @env{PATH}.
4096 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4097 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4098 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4099 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4100 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4102 @samp{@@INSTALL@@} is special, as its value may vary for different
4103 configuration files.
4105 This macro screens out various instances of @command{install} known not to
4106 work.  It prefers to find a C program rather than a shell script, for
4107 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4108 but that name is obsolete because some @command{make} programs have a rule
4109 that creates @file{install} from it if there is no makefile.  Further, this
4110 macro requires @command{install} to be able to install multiple files into a
4111 target directory in a single invocation.
4113 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4114 you use @code{AC_PROG_INSTALL}, you must include either
4115 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4116 @command{configure} produces an error message saying it can't find
4117 them---even if the system you're on has a good @command{install} program.
4118 This check is a safety measure to prevent you from accidentally leaving
4119 that file out, which would prevent your package from installing on
4120 systems that don't have a BSD-compatible @command{install} program.
4122 If you need to use your own installation program because it has features
4123 not found in standard @command{install} programs, there is no reason to use
4124 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4125 @file{Makefile.in} files.
4127 The result of the test can be overridden by setting the variable
4128 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4129 @end defmac
4131 @defmac AC_PROG_MKDIR_P
4132 @acindex{PROG_MKDIR_P}
4133 @ovindex MKDIR_P
4134 @caindex path_mkdir
4135 Set output variable @code{MKDIR_P} to a program that ensures that for
4136 each argument, a directory named by this argument exists, creating it
4137 and its parent directories if needed, and without race conditions when
4138 two instances of the program attempt to make the same directory at
4139 nearly the same time.
4141 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4142 falls back on invoking @command{install-sh} with the @option{-d} option,
4143 so your package should
4144 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4145 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4146 is vulnerable to race conditions, so if you want to support parallel
4147 installs from
4148 different packages into the same directory you need to make sure you
4149 have an up-to-date @file{install-sh}.  In particular, be careful about
4150 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4152 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4153 in M4sh}), but it sets an output variable intended for use in other
4154 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4155 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4156 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4157 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4158 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4159 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4160 Finally, @code{AS_MKDIR_P} does not check for race condition
4161 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4163 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4164 configuration files.
4166 The result of the test can be overridden by setting the variable
4167 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4168 @end defmac
4170 @anchor{AC_PROG_LEX}
4171 @defmac AC_PROG_LEX
4172 @acindex{PROG_LEX}
4173 @ovindex LEX
4174 @ovindex LEXLIB
4175 @cvindex YYTEXT_POINTER
4176 @ovindex LEX_OUTPUT_ROOT
4177 @caindex prog_LEX
4178 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4179 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4180 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4181 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4182 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4183 alongside the source @file{file.l}, this default allows users without a
4184 lexer generator to still build the package even if the timestamp for
4185 @file{file.l} is inadvertently changed.
4187 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4188 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4189 the base of the file name that the lexer generates; usually
4190 @file{lex.yy}, but sometimes something else.  These results vary
4191 according to whether @code{lex} or @code{flex} is being used.
4193 You are encouraged to use Flex in your sources, since it is both more
4194 pleasant to use than plain Lex and the C source it produces is portable.
4195 In order to ensure portability, however, you must either provide a
4196 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4197 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4198 statement in the scanner's source.  Once this done, the scanner is
4199 portable (unless @emph{you} felt free to use nonportable constructs) and
4200 does not depend on any library.  In this case, and in this case only, it
4201 is suggested that you use this Autoconf snippet:
4203 @example
4204 AC_PROG_LEX
4205 if test "x$LEX" != xflex; then
4206   LEX="$SHELL $missing_dir/missing flex"
4207   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4208   AC_SUBST([LEXLIB], [''])
4210 @end example
4212 The shell script @command{missing} can be found in the Automake
4213 distribution.
4215 Remember that the user may have supplied an alternate location in
4216 @env{LEX}, so if Flex is required, it is better to check that the user
4217 provided something sufficient by parsing the output of @samp{$LEX
4218 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4220 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4221 (indirectly) this macro twice, which causes an annoying but benign
4222 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4223 of Automake will fix this issue; meanwhile, just ignore this message.
4225 As part of running the test, this macro may delete any file in the
4226 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4228 The result of this test can be influenced by setting the variable
4229 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4230 @end defmac
4232 @anchor{AC_PROG_LN_S}
4233 @defmac AC_PROG_LN_S
4234 @acindex{PROG_LN_S}
4235 @ovindex LN_S
4236 If @samp{ln -s} works on the current file system (the operating system
4237 and file system support symbolic links), set the output variable
4238 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4239 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4241 If you make a link in a directory other than the current directory, its
4242 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4243 create links using @samp{$(LN_S)}, either find out which form is used
4244 and adjust the arguments, or always invoke @code{ln} in the directory
4245 where the link is to be created.
4247 In other words, it does not work to do:
4248 @example
4249 $(LN_S) foo /x/bar
4250 @end example
4252 Instead, do:
4254 @example
4255 (cd /x && $(LN_S) foo bar)
4256 @end example
4257 @end defmac
4259 @defmac AC_PROG_RANLIB
4260 @acindex{PROG_RANLIB}
4261 @ovindex RANLIB
4262 @c @caindex prog_RANLIB
4263 @c @caindex prog_ac_ct_RANLIB
4264 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4265 is found, and otherwise to @samp{:} (do nothing).
4266 @end defmac
4268 @defmac AC_PROG_SED
4269 @acindex{PROG_SED}
4270 @ovindex SED
4271 @caindex path_SED
4272 Set output variable @code{SED} to a Sed implementation that conforms to
4273 Posix and does not have arbitrary length limits.  Report an error if no
4274 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4275 information about portability problems with Sed.
4277 The result of this test can be overridden by setting the @code{SED} variable
4278 and is cached in the @code{ac_cv_path_SED} variable.
4279 @end defmac
4281 @defmac AC_PROG_YACC
4282 @acindex{PROG_YACC}
4283 @evindex YACC
4284 @evindex YFLAGS
4285 @ovindex YACC
4286 @caindex prog_YACC
4287 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4288 -o y.tab.c}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4289 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4290 The result of this test can be influenced by setting the variable
4291 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4292 @end defmac
4294 @node Generic Programs
4295 @subsection Generic Program and File Checks
4297 These macros are used to find programs not covered by the ``particular''
4298 test macros.  If you need to check the behavior of a program as well as
4299 find out whether it is present, you have to write your own test for it
4300 (@pxref{Writing Tests}).  By default, these macros use the environment
4301 variable @env{PATH}.  If you need to check for a program that might not
4302 be in the user's @env{PATH}, you can pass a modified path to use
4303 instead, like this:
4305 @example
4306 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4307              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4308 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4309 @end example
4311 You are strongly encouraged to declare the @var{variable} passed to
4312 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4313 @code{AC_ARG_VAR}, for more details.
4315 @anchor{AC_CHECK_PROG}
4316 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4317   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4318   @ovar{reject})
4319 @acindex{CHECK_PROG}
4320 @caindex prog_@var{variable}
4321 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4322 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4323 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4324 absolute file name) even if it is the first found in the search path; in
4325 that case, set @var{variable} using the absolute file name of the
4326 @var{prog-to-check-for} found that is not @var{reject}.  If
4327 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4328 @var{variable}.  The result of this test can be overridden by setting the
4329 @var{variable} variable or the cache variable
4330 @code{ac_cv_prog_@var{variable}}.
4331 @end defmac
4333 @anchor{AC_CHECK_PROGS}
4334 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4335   @ovar{value-if-not-found}, @dvar{path, $PATH})
4336 @acindex{CHECK_PROGS}
4337 @caindex prog_@var{variable}
4338 Check for each program in the blank-separated list
4339 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4340 @var{variable} to the name of that program.  Otherwise, continue
4341 checking the next program in the list.  If none of the programs in the
4342 list are found, set @var{variable} to @var{value-if-not-found}; if
4343 @var{value-if-not-found} is not specified, the value of @var{variable}
4344 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4345 this test can be overridden by setting the @var{variable} variable or the
4346 cache variable @code{ac_cv_prog_@var{variable}}.
4347 @end defmac
4349 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4350   @ovar{value-if-not-found}, @dvar{path, $PATH})
4351 @acindex{CHECK_TARGET_TOOL}
4352 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4353 with a prefix of the target type as determined by
4354 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4355 If the tool cannot be found with a prefix, and if the build and target
4356 types are equal, then it is also searched for without a prefix.
4358 As noted in @ref{Specifying Target Triplets}, the
4359 target is rarely specified, because most of the time it is the same
4360 as the host: it is the type of system for which any compiler tool in
4361 the package produces code.  What this macro looks for is,
4362 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4363 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4364 uses to produce objects, archives or executables}.
4365 @end defmac
4367 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4368   @ovar{value-if-not-found}, @dvar{path, $PATH})
4369 @acindex{CHECK_TOOL}
4370 @c @caindex prog_@var{VARIABLE}
4371 @c @caindex prog_ac_ct_@var{VARIABLE}
4372 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4373 with a prefix of the host type as specified by @option{--host}, followed by a
4374 dash.  For example, if the user runs
4375 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4376 @example
4377 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4378 @end example
4379 @noindent
4380 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4381 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4382 @var{path}, or to @samp{:} if neither program exists.
4384 When cross-compiling, this macro will issue a warning if no program
4385 prefixed with the host type could be found.
4386 For more information, see @ref{Specifying Target Triplets}.
4387 @end defmac
4389 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4390   @ovar{value-if-not-found}, @dvar{path, $PATH})
4391 @acindex{CHECK_TARGET_TOOLS}
4392 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4393 @var{progs-to-check-for} are checked with a prefix of the target type as
4394 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4395 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4396 prefix, and if the build and target types are equal, then the first one
4397 without a prefix is used.  If a tool is found, set @var{variable} to
4398 the name of that program.  If none of the tools in the list are found,
4399 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4400 is not specified, the value of @var{variable} is not changed.  Calls
4401 @code{AC_SUBST} for @var{variable}.
4402 @end defmac
4404 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4405   @ovar{value-if-not-found}, @dvar{path, $PATH})
4406 @acindex{CHECK_TOOLS}
4407 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4408 @var{progs-to-check-for} are checked with a prefix of the host type as
4409 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4410 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4411 prefix, then the first one without a prefix is used.  If a tool is found,
4412 set @var{variable} to the name of that program.  If none of the tools in
4413 the list are found, set @var{variable} to @var{value-if-not-found}; if
4414 @var{value-if-not-found} is not specified, the value of @var{variable}
4415 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4417 When cross-compiling, this macro will issue a warning if no program
4418 prefixed with the host type could be found.
4419 For more information, see @ref{Specifying Target Triplets}.
4420 @end defmac
4422 @anchor{AC_PATH_PROG}
4423 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4424   @ovar{value-if-not-found}, @dvar{path, $PATH})
4425 @acindex{PATH_PROG}
4426 @caindex path_@var{variable}
4427 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4428 name of @var{prog-to-check-for} if found.  The result of this test
4429 can be overridden by setting the @var{variable} variable.  A positive
4430 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4431 variable.
4432 @end defmac
4434 @anchor{AC_PATH_PROGS}
4435 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4436   @ovar{value-if-not-found}, @dvar{path, $PATH})
4437 @acindex{PATH_PROGS}
4438 @caindex path_@var{variable}
4439 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4440 are found, set @var{variable} to the absolute name of the program
4441 found.  The result of this test can be overridden by setting the
4442 @var{variable} variable.  A positive result of this test is cached in
4443 the @code{ac_cv_path_@var{variable}} variable.
4444 @end defmac
4446 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4447   @var{progs-to-check-for}, @var{feature-test}, @
4448   @ovar{action-if-not-found}, @dvar{path, $PATH})
4449 @acindex{PATH_PROGS_FEATURE_CHECK}
4450 @caindex path_@var{variable}
4451 @vrindex ac_path_@var{variable}
4452 @vrindex ac_path_@var{variable}_found
4453 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4454 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4455 its value.  Otherwise, check for each program in the blank-separated
4456 list @var{progs-to-check-for} existing in @var{path}.  For each program
4457 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4458 set to the absolute name of the candidate program.  If no invocation of
4459 @var{feature-test} sets the shell variable
4460 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4461 executed.  @var{feature-test} will be run even when
4462 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4463 choose a better candidate found later in @var{path}; to accept the
4464 current setting and bypass all further checks, @var{feature-test} can
4465 execute @code{ac_path_@var{variable}_found=:}.
4467 Note that this macro has some subtle differences from
4468 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4469 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4470 particular, @var{variable} is not set to the final value of
4471 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4472 run.  Also, on failure, any action can be performed, whereas
4473 @code{AC_CHECK_PROGS} only performs
4474 @code{@var{variable}=@var{value-if-not-found}}.
4476 Here is an example, similar to what Autoconf uses in its own configure
4477 script.  It will search for an implementation of @command{m4} that
4478 supports the @code{indir} builtin, even if it goes by the name
4479 @command{gm4} or is not the first implementation on @env{PATH}.
4481 @example
4482 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4483   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4484     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4485       test "x$m4out" = x0 \
4486       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4487     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4488 AC_SUBST([M4], [$ac_cv_path_M4])
4489 @end example
4490 @end defmac
4492 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4493   @ovar{value-if-not-found}, @dvar{path, $PATH})
4494 @acindex{PATH_TARGET_TOOL}
4495 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4496 name of the program if it is found.
4497 @end defmac
4499 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4500   @ovar{value-if-not-found}, @dvar{path, $PATH})
4501 @acindex{PATH_TOOL}
4502 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4503 name of the program if it is found.
4505 When cross-compiling, this macro will issue a warning if no program
4506 prefixed with the host type could be found.
4507 For more information, see @ref{Specifying Target Triplets}.
4508 @end defmac
4511 @node Files
4512 @section Files
4513 @cindex File, checking
4515 You might also need to check for the existence of files.  Before using
4516 these macros, ask yourself whether a runtime test might not be a better
4517 solution.  Be aware that, like most Autoconf macros, they test a feature
4518 of the host machine, and therefore, they die when cross-compiling.
4520 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4521   @ovar{action-if-not-found})
4522 @acindex{CHECK_FILE}
4523 @caindex file_@var{file}
4524 Check whether file @var{file} exists on the native system.  If it is
4525 found, execute @var{action-if-found}, otherwise do
4526 @var{action-if-not-found}, if given.  Cache the result of this test
4527 in the @code{ac_cv_file_@var{file}} variable, with characters not
4528 suitable for a variable name mapped to underscores.
4529 @end defmac
4531 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4532   @ovar{action-if-not-found})
4533 @acindex{CHECK_FILES}
4534 @caindex file_@var{file}
4535 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4536 and perform either @var{action-if-found} or @var{action-if-not-found}.
4537 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4538 (@pxref{Standard Symbols}) for each file found and caches the results of
4539 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4540 not suitable for a variable name mapped to underscores.
4541 @end defmac
4544 @node Libraries
4545 @section Library Files
4546 @cindex Library, checking
4548 The following macros check for the presence of certain C, C++, Fortran,
4549 or Go library archive files.
4551 @anchor{AC_CHECK_LIB}
4552 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4553   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4554 @acindex{CHECK_LIB}
4555 @caindex lib_@var{library}_@var{function}
4556 Test whether the library @var{library} is available by trying to link
4557 a test program that calls function @var{function} with the library.
4558 @var{function} should be a function provided by the library.
4559 Use the base
4560 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4561 the @var{library} argument.
4563 @var{action-if-found} is a list of shell commands to run if the link
4564 with the library succeeds; @var{action-if-not-found} is a list of shell
4565 commands to run if the link fails.  If @var{action-if-found} is not
4566 specified, the default action prepends @option{-l@var{library}} to
4567 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4568 capitals).  This macro is intended to support building @code{LIBS} in
4569 a right-to-left (least-dependent to most-dependent) fashion such that
4570 library dependencies are satisfied as a natural side effect of
4571 consecutive tests.  Linkers are sensitive to library ordering
4572 so the order in which @code{LIBS} is generated is important to reliable
4573 detection of libraries.
4575 If linking with @var{library} results in unresolved symbols that would
4576 be resolved by linking with additional libraries, give those libraries
4577 as the @var{other-libraries} argument, separated by spaces:
4578 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4579 that @var{library} is present, because linking the test program can
4580 fail with unresolved symbols.  The @var{other-libraries} argument
4581 should be limited to cases where it is desirable to test for one library
4582 in the presence of another that is not already in @code{LIBS}.
4584 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4585 in some common cases.  Many standard functions like @code{gethostbyname}
4586 appear in the standard C library on some hosts, and in special libraries
4587 like @code{nsl} on other hosts.  On some hosts the special libraries
4588 contain variant implementations that you may not want to use.  These
4589 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4590 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4592 The result of this test is cached in the
4593 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4594 @end defmac
4596 @anchor{AC_SEARCH_LIBS}
4597 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4598   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4599 @acindex{SEARCH_LIBS}
4600 @caindex search_@var{function}
4601 Search for a library defining @var{function} if it's not already
4602 available.  This equates to calling
4603 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4604 no libraries, then for each library listed in @var{search-libs}.
4606 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4607 to contain @var{function}, and run @var{action-if-found}.  If the
4608 function is not found, run @var{action-if-not-found}.
4610 If linking with @var{library} results in unresolved symbols that would
4611 be resolved by linking with additional libraries, give those libraries
4612 as the @var{other-libraries} argument, separated by spaces:
4613 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4614 that @var{function} is present, because linking the test program
4615 always fails with unresolved symbols.
4617 The result of this test is cached in the
4618 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4619 @var{function} is already available, as @samp{no} if no library
4620 containing @var{function} was found, otherwise as the
4621 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4622 @end defmac
4626 @node Library Functions
4627 @section Library Functions
4629 The following macros check for particular C library functions.
4630 If there is no macro specifically defined to check for a function you need,
4631 and you don't need to check for any special properties of
4632 it, then you can use one of the general function-check macros.
4634 @menu
4635 * Function Portability::        Pitfalls with usual functions
4636 * Particular Functions::        Special handling to find certain functions
4637 * Generic Functions::           How to find other functions
4638 @end menu
4640 @node Function Portability
4641 @subsection Portability of C Functions
4642 @cindex Portability of C functions
4643 @cindex C function portability
4645 Most usual functions can either be missing, or be buggy, or be limited
4646 on some architectures.  This section tries to make an inventory of these
4647 portability issues.  By definition, this list always requires
4648 additions.  A much more complete list is maintained by the Gnulib
4649 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4650 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4651 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4652 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4653 help us keep the gnulib list as complete as possible.
4655 @table @asis
4656 @item @code{exit}
4657 @c @fuindex exit
4658 @prindex @code{exit}
4659 On ancient hosts, @code{exit} returned @code{int}.
4660 This is because @code{exit} predates @code{void}, and there was a long
4661 tradition of it returning @code{int}.
4663 On current hosts, the problem more likely is that @code{exit} is not
4664 declared, due to C++ problems of some sort or another.  For this reason
4665 we suggest that test programs not invoke @code{exit}, but return from
4666 @code{main} instead.
4668 @item @code{free}
4669 @c @fuindex free
4670 @prindex @code{free}
4671 The C standard says a call @code{free (NULL)} does nothing, but
4672 some old systems don't support this (e.g., NextStep).
4674 @item @code{isinf}
4675 @itemx @code{isnan}
4676 @c @fuindex isinf
4677 @c @fuindex isnan
4678 @prindex @code{isinf}
4679 @prindex @code{isnan}
4680 In C99 and later, @code{isinf} and @code{isnan} are
4681 macros.  On some systems just macros are available
4682 (e.g., HP-UX and Solaris 10), on
4683 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4684 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4685 these functions are declared in nonstandard headers like
4686 @code{<sunmath.h>} and defined in non-default libraries like
4687 @option{-lm} or @option{-lsunmath}.
4689 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4690 @code{long double} arguments, but pre-C99 systems that use functions
4691 typically assume @code{double} arguments.  On such a system,
4692 @code{isinf} incorrectly returns true for a finite @code{long double}
4693 argument that is outside the range of @code{double}.
4695 The best workaround for these issues is to use gnulib modules
4696 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4697 solution involves code like the following.
4699 @smallexample
4700 #include <math.h>
4702 #ifndef isnan
4703 # define isnan(x) \
4704     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4705      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4706      : isnan_f (x))
4707 static int isnan_f  (float       x) @{ return x != x; @}
4708 static int isnan_d  (double      x) @{ return x != x; @}
4709 static int isnan_ld (long double x) @{ return x != x; @}
4710 #endif
4712 #ifndef isinf
4713 # define isinf(x) \
4714     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4715      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4716      : isinf_f (x))
4717 static int isinf_f  (float       x)
4718 @{ return !isnan (x) && isnan (x - x); @}
4719 static int isinf_d  (double      x)
4720 @{ return !isnan (x) && isnan (x - x); @}
4721 static int isinf_ld (long double x)
4722 @{ return !isnan (x) && isnan (x - x); @}
4723 #endif
4724 @end smallexample
4726 Some optimizing compilers mishandle these definitions, but systems with that bug
4727 typically have many other floating point corner-case compliance problems
4728 anyway, so it's probably not worth worrying about.
4730 @item @code{malloc}
4731 @c @fuindex malloc
4732 @prindex @code{malloc}
4733 The C standard says a call @code{malloc (0)} is implementation
4734 dependent.  It can return either @code{NULL} or a new non-null pointer.
4735 The latter is more common (e.g., the GNU C Library) but is by
4736 no means universal.  @code{AC_FUNC_MALLOC}
4737 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4739 @item @code{putenv}
4740 @c @fuindex putenv
4741 @prindex @code{putenv}
4742 Posix prefers @code{setenv} to @code{putenv}; among other things,
4743 @code{putenv} is not required of all Posix implementations, but
4744 @code{setenv} is.
4746 Posix specifies that @code{putenv} puts the given string directly in
4747 @code{environ}, but some systems make a copy of it instead (e.g.,
4748 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4749 not free it, causing a memory leak (e.g., FreeBSD 4).
4751 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4752 environment, but this is not standard usage and it dumps core
4753 on some systems (e.g., AIX).
4755 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4756 environment, rather than inserting it with an empty value.
4758 @item @code{realloc}
4759 @c @fuindex realloc
4760 @prindex @code{realloc}
4761 The C standard says a call @code{realloc (NULL, size)} is equivalent
4762 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4763 NextStep).
4765 @item @code{signal} handler
4766 @c @fuindex signal
4767 @prindex @code{signal}
4768 @prindex @code{sigaction}
4769 Normally @code{signal} takes a handler function with a return type of
4770 @code{void}, but some old systems required @code{int} instead.  Any
4771 actual @code{int} value returned is not used; this is only a
4772 difference in the function prototype demanded.
4774 All systems we know of in current use return @code{void}.  The
4775 @code{int} was to support K&R C, where of course @code{void} is not
4776 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4777 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4778 all cases.
4780 In most cases, it is more robust to use @code{sigaction} when it is
4781 available, rather than @code{signal}.
4783 @item @code{snprintf}
4784 @c @fuindex snprintf
4785 @prindex @code{snprintf}
4786 @c @fuindex vsnprintf
4787 @prindex @code{vsnprintf}
4788 In C99 and later, if the output array isn't big enough
4789 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4790 truncate the output and return the number of bytes that ought to have
4791 been produced.  Some older systems return the truncated length (e.g.,
4792 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4793 (e.g., earlier GNU C Library versions), and some the buffer
4794 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4795 older systems ignore the length and overrun the buffer (e.g., 64-bit
4796 Solaris 7).
4798 @item @code{sprintf}
4799 @c @fuindex sprintf
4800 @prindex @code{sprintf}
4801 @c @fuindex vsprintf
4802 @prindex @code{vsprintf}
4803 The C standard says @code{sprintf} and @code{vsprintf} return the
4804 number of bytes written.  On some ancient systems (SunOS 4 for
4805 instance) they return the buffer pointer instead, but these no
4806 longer need to be worried about.
4808 @item @code{sscanf}
4809 @c @fuindex sscanf
4810 @prindex @code{sscanf}
4811 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4812 that its
4813 input string be writable (though it doesn't actually change it).  This
4814 can be a problem when using @command{gcc} since it normally puts
4815 constant strings in read-only memory (@pxref{Incompatibilities,
4816 Incompatibilities of GCC, , gcc, Using and
4817 Porting the GNU Compiler Collection}).  Apparently in some cases even
4818 having format strings read-only can be a problem.
4820 @item @code{strerror_r}
4821 @c @fuindex strerror_r
4822 @prindex @code{strerror_r}
4823 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4824 systems (e.g., GNU C Library version 2.2.4) provide a
4825 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4826 can detect which is in use (@pxref{Particular Functions}).
4828 @item @code{strnlen}
4829 @c @fuindex strnlen
4830 @prindex @code{strnlen}
4831 AIX 4.3 provides a broken version which produces the
4832 following results:
4834 @example
4835 strnlen ("foobar", 0) = 0
4836 strnlen ("foobar", 1) = 3
4837 strnlen ("foobar", 2) = 2
4838 strnlen ("foobar", 3) = 1
4839 strnlen ("foobar", 4) = 0
4840 strnlen ("foobar", 5) = 6
4841 strnlen ("foobar", 6) = 6
4842 strnlen ("foobar", 7) = 6
4843 strnlen ("foobar", 8) = 6
4844 strnlen ("foobar", 9) = 6
4845 @end example
4847 @item @code{sysconf}
4848 @c @fuindex sysconf
4849 @prindex @code{sysconf}
4850 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4851 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4852 @code{#ifdef}.
4854 @item @code{unlink}
4855 @c @fuindex unlink
4856 @prindex @code{unlink}
4857 The Posix spec says that @code{unlink} causes the given file to be
4858 removed only after there are no more open file handles for it.  Some
4859 non-Posix hosts have trouble with this requirement, though,
4860 and some DOS variants even corrupt the file system.
4862 @item @code{unsetenv}
4863 @c @fuindex unsetenv
4864 @prindex @code{unsetenv}
4865 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4866 can be removed with a call @code{putenv ("FOO=")}, as described under
4867 @code{putenv} above.
4869 @item @code{va_copy}
4870 @c @fuindex va_copy
4871 @prindex @code{va_copy}
4872 C99 and later provide @code{va_copy} for copying
4873 @code{va_list} variables.  It may be available in older environments
4874 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4875 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4876 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4877 portability.
4879 @item @code{va_list}
4880 @c @fuindex va_list
4881 @prindex @code{va_list}
4882 @code{va_list} is not necessarily just a pointer.  It can be a
4883 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4884 not portable.  Or it can be an array (e.g., @command{gcc} in some
4885 PowerPC configurations), which means as a function parameter it can be
4886 effectively call-by-reference and library routines might modify the
4887 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4888 2.1).
4890 @item Signed @code{>>}
4891 Normally the C @code{>>} right shift of a signed type replicates the
4892 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4893 taken since Standard C doesn't require that behavior.  On those
4894 few processors without a native arithmetic shift (for instance Cray
4895 vector systems) zero bits may be shifted in, the same as a shift of an
4896 unsigned type.
4898 @item Integer @code{/}
4899 C divides signed integers by truncating their quotient toward zero,
4900 yielding the same result as Fortran.  However, before C99 the standard
4901 allowed C implementations to take the floor or ceiling of the quotient
4902 in some cases.  Hardly any implementations took advantage of this
4903 freedom, though, and it's probably not worth worrying about this issue
4904 nowadays.
4905 @end table
4908 @node Particular Functions
4909 @subsection Particular Function Checks
4910 @cindex Function, checking
4912 These macros check for particular C functions---whether they exist, and
4913 in some cases how they respond when given certain arguments.
4915 @anchor{AC_FUNC_ALLOCA}
4916 @defmac AC_FUNC_ALLOCA
4917 @acindex{FUNC_ALLOCA}
4918 @cvindex C_ALLOCA
4919 @cvindex HAVE_ALLOCA_H
4920 @ovindex ALLOCA
4921 @c @fuindex alloca
4922 @prindex @code{alloca}
4923 @hdrindex{alloca.h}
4924 @c @caindex working_alloca_h
4925 Check for the @code{alloca} function.  Define @code{HAVE_ALLOCA_H} if
4926 @file{alloca.h} defines a working @code{alloca}.  If not, look for a
4927 builtin alternative.  If either method succeeds, define
4928 @code{HAVE_ALLOCA}.  Otherwise, set the output variable @code{ALLOCA} to
4929 @samp{$@{LIBOBJDIR@}alloca.o} and define
4930 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4931 garbage collect).  This variable is separate from @code{LIBOBJS} so
4932 multiple programs can share the value of @code{ALLOCA} without needing
4933 to create an actual library, in case only some of them use the code in
4934 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4935 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4937 Source files that use @code{alloca} should start with a piece of code
4938 like the following, to declare it properly.
4940 @example
4941 @group
4942 #include <stdlib.h>
4943 #include <stddef.h>
4944 #ifdef HAVE_ALLOCA_H
4945 # include <alloca.h>
4946 #elif !defined alloca
4947 # ifdef __GNUC__
4948 #  define alloca __builtin_alloca
4949 # elif defined _MSC_VER
4950 #  include <malloc.h>
4951 #  define alloca _alloca
4952 # elif !defined HAVE_ALLOCA
4953 #  ifdef  __cplusplus
4954 extern "C"
4955 #  endif
4956 void *alloca (size_t);
4957 # endif
4958 #endif
4959 @end group
4960 @end example
4961 @end defmac
4963 @defmac AC_FUNC_CHOWN
4964 @acindex{FUNC_CHOWN}
4965 @cvindex HAVE_CHOWN
4966 @c @fuindex chown
4967 @prindex @code{chown}
4968 @caindex func_chown_works
4969 If the @code{chown} function is available and works (in particular, it
4970 should accept @option{-1} for @code{uid} and @code{gid}), define
4971 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4972 @code{ac_cv_func_chown_works} variable.
4973 @end defmac
4975 @anchor{AC_FUNC_CLOSEDIR_VOID}
4976 @defmac AC_FUNC_CLOSEDIR_VOID
4977 @acindex{FUNC_CLOSEDIR_VOID}
4978 @cvindex CLOSEDIR_VOID
4979 @c @fuindex closedir
4980 @prindex @code{closedir}
4981 @caindex func_closedir_void
4982 If the @code{closedir} function does not return a meaningful value,
4983 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4984 return value for an error indicator.
4986 Currently this test is implemented by running a test program.  When
4987 cross compiling the pessimistic assumption that @code{closedir} does not
4988 return a meaningful value is made.
4990 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4991 variable.
4993 This macro is obsolescent, as @code{closedir} returns a meaningful value
4994 on current systems.  New programs need not use this macro.
4995 @end defmac
4997 @defmac AC_FUNC_ERROR_AT_LINE
4998 @acindex{FUNC_ERROR_AT_LINE}
4999 @c @fuindex error_at_line
5000 @prindex @code{error_at_line}
5001 @caindex lib_error_at_line
5002 If the @code{error_at_line} function is not found, require an
5003 @code{AC_LIBOBJ} replacement of @samp{error}.
5005 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
5006 variable.
5008 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
5009 should use Gnulib's @code{error} module.  @xref{Gnulib}.
5010 @end defmac
5012 @defmac AC_FUNC_FNMATCH
5013 @acindex{FUNC_FNMATCH}
5014 @c @fuindex fnmatch
5015 @prindex @code{fnmatch}
5016 @caindex func_fnmatch_works
5017 If the @code{fnmatch} function conforms to Posix, define
5018 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
5019 the bugs in Solaris 2.4.
5021 Unlike the other specific
5022 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5023 broken/missing @code{fnmatch}.  This is for historical reasons.
5024 See @code{AC_REPLACE_FNMATCH} below.
5026 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5027 variable.
5029 This macro is obsolescent.  New programs should use Gnulib's
5030 @code{fnmatch-posix} module.  @xref{Gnulib}.
5031 @end defmac
5033 @defmac AC_FUNC_FNMATCH_GNU
5034 @acindex{FUNC_FNMATCH_GNU}
5035 @c @fuindex fnmatch
5036 @prindex @code{fnmatch}
5037 @caindex func_fnmatch_gnu
5038 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5039 whether @code{fnmatch} supports GNU extensions.  Detect common
5040 implementation bugs, for example, the bugs in the GNU C
5041 Library 2.1.
5043 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5044 variable.
5046 This macro is obsolescent.  New programs should use Gnulib's
5047 @code{fnmatch-gnu} module.  @xref{Gnulib}.
5048 @end defmac
5050 @anchor{AC_FUNC_FORK}
5051 @defmac AC_FUNC_FORK
5052 @acindex{FUNC_FORK}
5053 @cvindex HAVE_VFORK_H
5054 @cvindex HAVE_WORKING_FORK
5055 @cvindex HAVE_WORKING_VFORK
5056 @cvindex vfork
5057 @c @fuindex fork
5058 @prindex @code{fork}
5059 @c @fuindex vfork
5060 @prindex @code{vfork}
5061 @hdrindex{vfork.h}
5062 @c @caindex func_fork
5063 @c @caindex func_fork_works
5064 This macro checks for the @code{fork} and @code{vfork} functions.  If a
5065 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
5066 checks whether @code{fork} is just a stub by trying to run it.
5068 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
5069 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
5070 define @code{vfork} to be @code{fork} for backward compatibility with
5071 previous versions of @command{autoconf}.  This macro checks for several known
5072 errors in implementations of @code{vfork} and considers the system to not
5073 have a working @code{vfork} if it detects any of them.
5075 Since this macro defines @code{vfork} only for backward compatibility with
5076 previous versions of @command{autoconf} you're encouraged to define it
5077 yourself in new code:
5078 @example
5079 @group
5080 #ifndef HAVE_WORKING_VFORK
5081 # define vfork fork
5082 #endif
5083 @end group
5084 @end example
5086 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5087 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5088 test, you also need to set the @code{ac_cv_func_fork} and
5089 @code{ac_cv_func_vfork} variables.
5090 @end defmac
5092 @defmac AC_FUNC_FSEEKO
5093 @acindex{FUNC_FSEEKO}
5094 @cvindex _LARGEFILE_SOURCE
5095 @cvindex HAVE_FSEEKO
5096 @c @fuindex fseeko
5097 @prindex @code{fseeko}
5098 @c @fuindex ftello
5099 @prindex @code{ftello}
5100 @c @caindex sys_largefile_source
5101 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5102 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5103 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5104 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5105 largefile-sensitive systems where @code{off_t} does not default to a
5106 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5107 @end defmac
5109 @defmac AC_FUNC_GETGROUPS
5110 @acindex{FUNC_GETGROUPS}
5111 @cvindex HAVE_GETGROUPS
5112 @ovindex GETGROUPS_LIBS
5113 @c @fuindex getgroups
5114 @prindex @code{getgroups}
5115 @caindex func_getgroups_works
5116 If the @code{getgroups} function is available and works (unlike on
5117 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5118 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5119 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5120 @end defmac
5122 @anchor{AC_FUNC_GETLOADAVG}
5123 @defmac AC_FUNC_GETLOADAVG
5124 @acindex{FUNC_GETLOADAVG}
5125 @cvindex SVR4
5126 @cvindex DGUX
5127 @cvindex UMAX
5128 @cvindex UMAX4_3
5129 @cvindex HAVE_NLIST_H
5130 @cvindex NLIST_NAME_UNION
5131 @cvindex GETLOADAVG_PRIVILEGED
5132 @cvindex NEED_SETGID
5133 @cvindex C_GETLOADAVG
5134 @ovindex LIBOBJS
5135 @ovindex NEED_SETGID
5136 @ovindex KMEM_GROUP
5137 @ovindex GETLOADAVG_LIBS
5138 @c @fuindex getloadavg
5139 @prindex @code{getloadavg}
5140 Check how to get the system load averages.  To perform its tests
5141 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5142 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5143 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5145 If the system has the @code{getloadavg} function, define
5146 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5147 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5148 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5149 @samp{getloadavg} and possibly define several other C preprocessor
5150 macros and output variables:
5152 @enumerate
5153 @item
5154 Define @code{C_GETLOADAVG}.
5156 @item
5157 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5158 those systems.
5160 @item
5161 @hdrindex{nlist.h}
5162 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5164 @item
5165 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5166 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5167 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5169 @item
5170 Programs may need to be installed set-group-ID (or set-user-ID) for
5171 @code{getloadavg} to work.  In this case, define
5172 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5173 to @samp{true} (and otherwise to @samp{false}), and set
5174 @code{KMEM_GROUP} to the name of the group that should own the installed
5175 program.
5176 @end enumerate
5178 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5179 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5180 @end defmac
5182 @anchor{AC_FUNC_GETMNTENT}
5183 @defmac AC_FUNC_GETMNTENT
5184 @acindex{FUNC_GETMNTENT}
5185 @cvindex HAVE_GETMNTENT
5186 @c @fuindex getmntent
5187 @prindex @code{getmntent}
5188 @caindex search_getmntent
5189 Check for @code{getmntent} in the standard C library, and then in the
5190 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5191 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5192 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5193 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5194 @code{ac_cv_func_getmntent} to @code{no}.
5196 The result of this macro can be overridden by setting the cache variable
5197 @code{ac_cv_search_getmntent}.
5198 @end defmac
5200 @defmac AC_FUNC_GETPGRP
5201 @acindex{FUNC_GETPGRP}
5202 @cvindex GETPGRP_VOID
5203 @c @fuindex getpgid
5204 @c @fuindex getpgrp
5205 @prindex @code{getpgid}
5206 @prindex @code{getpgrp}
5207 @caindex func_getpgrp_void
5208 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5209 @code{getpgrp}; this is the Posix behavior.  On older BSD
5210 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5211 behaves like Posix's @code{getpgid}.
5213 @example
5214 #ifdef GETPGRP_VOID
5215   pid = getpgrp ();
5216 #else
5217   pid = getpgrp (0);
5218 #endif
5219 @end example
5221 This macro does not check whether
5222 @code{getpgrp} exists at all; if you need to work in that situation,
5223 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5225 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5226 variable.
5228 This macro is obsolescent, as current systems have a @code{getpgrp}
5229 whose signature conforms to Posix.  New programs need not use this macro.
5230 @end defmac
5232 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5233 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5234 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5235 @c @fuindex lstat
5236 @prindex @code{lstat}
5237 @caindex func_lstat_dereferences_slashed_symlink
5238 If @file{link} is a symbolic link, then @code{lstat} should treat
5239 @file{link/} the same as @file{link/.}.  However, many older
5240 @code{lstat} implementations incorrectly ignore trailing slashes.
5242 It is safe to assume that if @code{lstat} incorrectly ignores
5243 trailing slashes, then other symbolic-link-aware functions like
5244 @code{unlink} also incorrectly ignore trailing slashes.
5246 If @code{lstat} behaves properly, define
5247 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5248 @code{AC_LIBOBJ} replacement of @code{lstat}.
5250 The result of this macro is cached in the
5251 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5253 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5254 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5255 @end defmac
5257 @defmac AC_FUNC_MALLOC
5258 @acindex{FUNC_MALLOC}
5259 @cvindex HAVE_MALLOC
5260 @cvindex malloc
5261 @c @fuindex malloc
5262 @prindex @code{malloc}
5263 @caindex func_malloc_0_nonnull
5264 If the @code{malloc} function is compatible with the GNU C
5265 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5266 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5267 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5268 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5269 native @code{malloc} is not used in the main project.
5271 Typically, the replacement file @file{malloc.c} should look like (note
5272 the @samp{#undef malloc}):
5274 @verbatim
5275 #include <config.h>
5276 #undef malloc
5278 #include <sys/types.h>
5280 void *malloc ();
5282 /* Allocate an N-byte block of memory from the heap.
5283    If N is zero, allocate a 1-byte block.  */
5285 void *
5286 rpl_malloc (size_t n)
5288   if (n == 0)
5289     n = 1;
5290   return malloc (n);
5292 @end verbatim
5294 The result of this macro is cached in the
5295 @code{ac_cv_func_malloc_0_nonnull} variable.
5296 @end defmac
5298 @defmac AC_FUNC_MBRTOWC
5299 @acindex{FUNC_MBRTOWC}
5300 @cvindex HAVE_MBRTOWC
5301 @c @fuindex mbrtowc
5302 @prindex @code{mbrtowc}
5303 @caindex func_mbrtowc
5304 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5305 type @code{mbstate_t} are properly declared.
5307 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5308 variable.
5309 @end defmac
5311 @defmac AC_FUNC_MEMCMP
5312 @acindex{FUNC_MEMCMP}
5313 @ovindex LIBOBJS
5314 @c @fuindex memcmp
5315 @prindex @code{memcmp}
5316 @caindex func_memcmp_working
5317 If the @code{memcmp} function is not available, or does not work on
5318 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5319 bytes or more and with at least one buffer not starting on a 4-byte
5320 boundary (such as the one on NeXT x86 OpenStep), require an
5321 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5323 The result of this macro is cached in the
5324 @code{ac_cv_func_memcmp_working} variable.
5326 This macro is obsolescent, as current systems have a working
5327 @code{memcmp}.  New programs need not use this macro.
5328 @end defmac
5330 @defmac AC_FUNC_MKTIME
5331 @acindex{FUNC_MKTIME}
5332 @ovindex LIBOBJS
5333 @c @fuindex mktime
5334 @prindex @code{mktime}
5335 @caindex func_working_mktime
5336 If the @code{mktime} function is not available, or does not work
5337 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5338 For the purposes of this test, @code{mktime} should conform to the
5339 Posix standard and should be the inverse of
5340 @code{localtime}.
5342 The result of this macro is cached in the
5343 @code{ac_cv_func_working_mktime} variable.
5345 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5346 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5347 @end defmac
5349 @anchor{AC_FUNC_MMAP}
5350 @defmac AC_FUNC_MMAP
5351 @acindex{FUNC_MMAP}
5352 @cvindex HAVE_MMAP
5353 @c @fuindex mmap
5354 @prindex @code{mmap}
5355 @caindex func_mmap_fixed_mapped
5356 If the @code{mmap} function exists and works correctly, define
5357 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5358 memory.
5360 The result of this macro is cached in the
5361 @code{ac_cv_func_mmap_fixed_mapped} variable.
5362 @end defmac
5364 @defmac AC_FUNC_OBSTACK
5365 @acindex{FUNC_OBSTACK}
5366 @cvindex HAVE_OBSTACK
5367 @cindex obstack
5368 @caindex func_obstack
5369 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5370 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5372 The result of this macro is cached in the @code{ac_cv_func_obstack}
5373 variable.
5374 @end defmac
5376 @defmac AC_FUNC_REALLOC
5377 @acindex{FUNC_REALLOC}
5378 @cvindex HAVE_REALLOC
5379 @cvindex realloc
5380 @c @fuindex realloc
5381 @prindex @code{realloc}
5382 @caindex func_realloc_0_nonnull
5383 If the @code{realloc} function is compatible with the GNU C
5384 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5385 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5386 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5387 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5388 the native @code{realloc} is not used in the main project.  See
5389 @code{AC_FUNC_MALLOC} for details.
5391 The result of this macro is cached in the
5392 @code{ac_cv_func_realloc_0_nonnull} variable.
5393 @end defmac
5395 @defmac AC_FUNC_SELECT_ARGTYPES
5396 @acindex{FUNC_SELECT_ARGTYPES}
5397 @cvindex SELECT_TYPE_ARG1
5398 @cvindex SELECT_TYPE_ARG234
5399 @cvindex SELECT_TYPE_ARG5
5400 @c @fuindex select
5401 @prindex @code{select}
5402 @c @caindex func_select_args
5403 Determines the correct type to be passed for each of the
5404 @code{select} function's arguments, and defines those types
5405 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5406 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5407 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5408 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5410 This macro is obsolescent, as current systems have a @code{select} whose
5411 signature conforms to Posix.  New programs need not use this macro.
5412 @end defmac
5414 @defmac AC_FUNC_SETPGRP
5415 @acindex{FUNC_SETPGRP}
5416 @cvindex SETPGRP_VOID
5417 @c @fuindex setpgrp
5418 @prindex @code{setpgrp}
5419 @caindex func_setpgrp_void
5420 If @code{setpgrp} takes no argument (the Posix version), define
5421 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5422 two process IDs as arguments.  This macro does not check whether
5423 @code{setpgrp} exists at all; if you need to work in that situation,
5424 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5426 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5427 variable.
5429 This macro is obsolescent, as current systems have a @code{setpgrp}
5430 whose signature conforms to Posix.  New programs need not use this macro.
5431 @end defmac
5433 @defmac AC_FUNC_STAT
5434 @defmacx AC_FUNC_LSTAT
5435 @acindex{FUNC_STAT}
5436 @acindex{FUNC_LSTAT}
5437 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5438 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5439 @c @fuindex stat
5440 @prindex @code{stat}
5441 @c @fuindex lstat
5442 @prindex @code{lstat}
5443 @caindex func_stat_empty_string_bug
5444 @caindex func_lstat_empty_string_bug
5445 Determine whether @code{stat} or @code{lstat} have the bug that it
5446 succeeds when given the zero-length file name as argument.  The @code{stat}
5447 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5448 this.
5450 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5451 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5452 replacement of it.
5454 The results of these macros are cached in the
5455 @code{ac_cv_func_stat_empty_string_bug} and the
5456 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5458 These macros are obsolescent, as no current systems have the bug.
5459 New programs need not use these macros.
5460 @end defmac
5462 @anchor{AC_FUNC_STRCOLL}
5463 @defmac AC_FUNC_STRCOLL
5464 @acindex{FUNC_STRCOLL}
5465 @cvindex HAVE_STRCOLL
5466 @c @fuindex strcoll
5467 @prindex @code{strcoll}
5468 @caindex func_strcoll_works
5469 If the @code{strcoll} function exists and works correctly, define
5470 @code{HAVE_STRCOLL}.  This does a bit more than
5471 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5472 definitions of @code{strcoll} that should not be used.
5474 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5475 variable.
5476 @end defmac
5478 @defmac AC_FUNC_STRERROR_R
5479 @acindex{FUNC_STRERROR_R}
5480 @cvindex HAVE_STRERROR_R
5481 @cvindex HAVE_DECL_STRERROR_R
5482 @cvindex STRERROR_R_CHAR_P
5483 @c @fuindex strerror_r
5484 @caindex func_strerror_r_char_p
5485 @prindex @code{strerror_r}
5486 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5487 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5488 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5489 returns an @code{int} error number.  The Thread-Safe Functions option of
5490 Posix requires @code{strerror_r} to return @code{int}, but
5491 many systems (including, for example, version 2.2.4 of the GNU C
5492 Library) return a @code{char *} value that is not necessarily equal to
5493 the buffer argument.
5495 The result of this macro is cached in the
5496 @code{ac_cv_func_strerror_r_char_p} variable.
5497 @end defmac
5499 @anchor{AC_FUNC_STRFTIME}
5500 @defmac AC_FUNC_STRFTIME
5501 @acindex{FUNC_STRFTIME}
5502 @cvindex HAVE_STRFTIME
5503 @c @fuindex strftime
5504 @prindex @code{strftime}
5505 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5506 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5508 This macro is obsolescent, as no current systems require the @file{intl}
5509 library for @code{strftime}.  New programs need not use this macro.
5510 @end defmac
5512 @defmac AC_FUNC_STRTOD
5513 @acindex{FUNC_STRTOD}
5514 @ovindex POW_LIB
5515 @c @fuindex strtod
5516 @prindex @code{strtod}
5517 @caindex func_strtod
5518 @caindex func_pow
5519 If the @code{strtod} function does not exist or doesn't work correctly,
5520 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5521 because @file{strtod.c} is likely to need @samp{pow}, set the output
5522 variable @code{POW_LIB} to the extra library needed.
5524 This macro caches its result in the @code{ac_cv_func_strtod} variable
5525 and depends upon the result in the @code{ac_cv_func_pow} variable.
5527 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5528 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5529 @end defmac
5531 @defmac AC_FUNC_STRTOLD
5532 @acindex{FUNC_STRTOLD}
5533 @cvindex HAVE_STRTOLD
5534 @prindex @code{strtold}
5535 @caindex func_strtold
5536 If the @code{strtold} function exists and conforms to C99 or later, define
5537 @code{HAVE_STRTOLD}.
5539 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5540 @end defmac
5542 @defmac AC_FUNC_STRNLEN
5543 @acindex{FUNC_STRNLEN}
5544 @cvindex HAVE_STRNLEN
5545 @c @fuindex strnlen
5546 @prindex @code{strnlen}
5547 @caindex func_strnlen_working
5548 If the @code{strnlen} function is not available, or is buggy (like the one
5549 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5551 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5552 variable.
5553 @end defmac
5555 @anchor{AC_FUNC_UTIME_NULL}
5556 @defmac AC_FUNC_UTIME_NULL
5557 @acindex{FUNC_UTIME_NULL}
5558 @cvindex HAVE_UTIME_NULL
5559 @c @fuindex utime
5560 @prindex @code{utime}
5561 @caindex func_utime_null
5562 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5563 the present, define @code{HAVE_UTIME_NULL}.
5565 This macro caches its result in the @code{ac_cv_func_utime_null}
5566 variable.
5568 This macro is obsolescent, as all current systems have a @code{utime}
5569 that behaves this way.  New programs need not use this macro.
5570 @end defmac
5572 @anchor{AC_FUNC_VPRINTF}
5573 @defmac AC_FUNC_VPRINTF
5574 @acindex{FUNC_VPRINTF}
5575 @cvindex HAVE_VPRINTF
5576 @cvindex HAVE_DOPRNT
5577 @c @fuindex vprintf
5578 @prindex @code{vprintf}
5579 @c @fuindex vsprintf
5580 @prindex @code{vsprintf}
5581 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5582 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5583 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5584 are also available.)
5586 This macro is obsolescent, as all current systems have @code{vprintf}.
5587 New programs need not use this macro.
5588 @end defmac
5590 @defmac AC_REPLACE_FNMATCH
5591 @acindex{REPLACE_FNMATCH}
5592 @c @fuindex fnmatch
5593 @prindex @code{fnmatch}
5594 @hdrindex{fnmatch.h}
5595 @caindex func_fnmatch_works
5596 If the @code{fnmatch} function does not conform to Posix (see
5597 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5599 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5600 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5601 copy of the source code of GNU @code{fnmatch}.  If necessary,
5602 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5603 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5604 included in place of the system @code{<fnmatch.h>}.
5606 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5607 variable.
5609 This macro is obsolescent, as it assumes the use of particular source
5610 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5611 which provides this macro along with the source files.  @xref{Gnulib}.
5612 @end defmac
5616 @node Generic Functions
5617 @subsection Generic Function Checks
5619 These macros are used to find functions not covered by the ``particular''
5620 test macros.  If the functions might be in libraries other than the
5621 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5622 If you need to check the behavior of a function as well as find out
5623 whether it is present, you have to write your own test for
5624 it (@pxref{Writing Tests}).
5626 @anchor{AC_CHECK_FUNC}
5627 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5628   @ovar{action-if-not-found})
5629 @acindex{CHECK_FUNC}
5630 @caindex func_@var{function}
5631 If C function @var{function} is available, run shell commands
5632 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5633 want to define a symbol if the function is available, consider using
5634 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5635 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5636 standardized than C++.  (@pxref{Language Choice}, for more information
5637 about selecting the language for checks.)
5639 This macro caches its result in the @code{ac_cv_func_@var{function}}
5640 variable.
5641 @end defmac
5643 @anchor{AC_CHECK_FUNCS}
5644 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5645   @ovar{action-if-not-found})
5646 @acindex{CHECK_FUNCS}
5647 @cvindex HAVE_@var{function}
5648 For each @var{function} enumerated in the blank-or-newline-separated argument
5649 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5650 If @var{action-if-found} is given, it is additional shell code to
5651 execute when one of the functions is found.  You can give it a value of
5652 @samp{break} to break out of the loop on the first match.  If
5653 @var{action-if-not-found} is given, it is executed when one of the
5654 functions is not found.
5656 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5657 @end defmac
5659 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5660 @acindex{CHECK_FUNCS_ONCE}
5661 @cvindex HAVE_@var{function}
5662 For each @var{function} enumerated in the blank-or-newline-separated argument
5663 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5664 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5665 checking code at most once, so that @command{configure} is smaller and
5666 faster; but the checks cannot be conditionalized and are always done once,
5667 early during the @command{configure} run.
5668 @end defmac
5670 @sp 1
5672 Autoconf follows a philosophy that was formed over the years by those
5673 who have struggled for portability: isolate the portability issues in
5674 specific files, and then program as if you were in a Posix
5675 environment.  Some functions may be missing or unfixable, and your
5676 package must be ready to replace them.
5678 Suitable replacements for many such problem functions are available from
5679 Gnulib (@pxref{Gnulib}).
5681 @defmac AC_LIBOBJ (@var{function})
5682 @acindex{LIBOBJ}
5683 @ovindex LIBOBJS
5684 Specify that @samp{@var{function}.c} must be included in the executables
5685 to replace a missing or broken implementation of @var{function}.
5687 @vrindex ac_objext
5688 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5689 variable @code{LIBOBJS} if it is not already in, and calls
5690 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5691 directly change @code{LIBOBJS}, since this is not traceable.
5692 @end defmac
5694 @defmac AC_LIBSOURCE (@var{file})
5695 @acindex{LIBSOURCE}
5696 Specify that @var{file} might be needed to compile the project.  If you
5697 need to know what files might be needed by a @file{configure.ac}, you
5698 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5700 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5701 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5702 that case, since shell variables cannot be traced statically, you must
5703 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5704 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5705 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5706 @code{"foo"} or @code{"bar"}, you should do:
5708 @example
5709 AC_LIBSOURCE([foo.c])
5710 AC_LIBSOURCE([bar.c])
5711 AC_LIBOBJ([$foo_or_bar])
5712 @end example
5714 @noindent
5715 There is usually a way to avoid this, however, and you are encouraged to
5716 simply call @code{AC_LIBOBJ} with literal arguments.
5718 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5719 slightly different semantics: the old macro took the function name,
5720 e.g., @code{foo}, as its argument rather than the file name.
5721 @end defmac
5723 @defmac AC_LIBSOURCES (@var{files})
5724 @acindex{LIBSOURCES}
5725 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5726 comma-separated M4 list.  Thus, the above example might be rewritten:
5728 @example
5729 AC_LIBSOURCES([foo.c, bar.c])
5730 AC_LIBOBJ([$foo_or_bar])
5731 @end example
5732 @end defmac
5734 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5735 @acindex{CONFIG_LIBOBJ_DIR}
5736 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5737 @var{directory}, a name relative to the top level of the
5738 source tree.  The replacement directory defaults to @file{.}, the top
5739 level directory, and the most typical value is @file{lib}, corresponding
5740 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5742 @command{configure} might need to know the replacement directory for the
5743 following reasons: (i) some checks use the replacement files, (ii) some
5744 macros bypass broken system headers by installing links to the
5745 replacement headers (iii) when used in conjunction with Automake,
5746 within each makefile, @var{directory} is used as a relative path
5747 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5748 @code{LTLIBOBJS}, etc.
5749 @end defmac
5751 @sp 1
5753 It is common to merely check for the existence of a function, and ask
5754 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5755 a convenient shorthand.
5757 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5758 @acindex{REPLACE_FUNCS}
5759 @cvindex HAVE_@var{function}
5760 @ovindex LIBOBJS
5761 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5762 @var{action-if-not-found}.  You can declare your replacement function by
5763 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5764 system has the function, it probably declares it in a header file you
5765 should be including, so you shouldn't redeclare it lest your declaration
5766 conflict.
5767 @end defmac
5769 @node Header Files
5770 @section Header Files
5771 @cindex Header, checking
5773 The following macros check for the presence of certain C header files.
5774 If there is no macro specifically defined to check for a header file you need,
5775 and you don't need to check for any special properties of
5776 it, then you can use one of the general header-file check macros.
5778 @menu
5779 * Header Portability::          Collected knowledge on common headers
5780 * Particular Headers::          Special handling to find certain headers
5781 * Generic Headers::             How to find other headers
5782 @end menu
5784 @node Header Portability
5785 @subsection Portability of Headers
5786 @cindex Portability of headers
5787 @cindex Header portability
5789 This section documents some collected knowledge about common headers,
5790 and the problems they cause.  By definition, this list always requires
5791 additions.  A much more complete list is maintained by the Gnulib
5792 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5793 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5794 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5795 the gnulib list as complete as possible.
5797 When we say that a header ``may require'' some set of other headers, we
5798 mean that it may be necessary for you to manually include those other
5799 headers first, or the contents of the header under test will fail to
5800 compile.  When checking for these headers, you must provide the
5801 potentially-required headers in the @var{includes} argument to
5802 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5803 fail spuriously.  @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5804 arranges to include a number of common requirements and should normally
5805 come first in your @var{includes}.  For example, @file{net/if.h} may
5806 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5807 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5808 @file{sys/socket.h}, so you should check for it like this:
5810 @example
5811 AC_CHECK_HEADERS([sys/socket.h])
5812 AC_CHECK_HEADERS([net/if.h], [], [],
5813 [AC_INCLUDES_DEFAULT[
5814 #ifdef HAVE_SYS_SOCKET_H
5815 # include <sys/socket.h>
5816 #endif
5818 @end example
5820 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5821 so that it gets expanded) and double quoting (to ensure that each
5822 preprocessor @code{#} gets treated as a literal string rather than a
5823 comment).
5825 @table @asis
5827 @item @file{limits.h}
5828 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5829 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5830 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5831 define them.
5833 @item @file{memory.h}
5834 @hdrindex{memory.h}
5835 This header file is obsolete; use @file{string.h} instead.
5837 @item @file{strings.h}
5838 @hdrindex{strings.h}
5839 On some systems, this is the only header that declares
5840 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5842 This header may or may not include @file{string.h} for you.  However, on
5843 all recent systems it is safe to include both @file{string.h} and
5844 @file{strings.h}, in either order, in the same source file.
5846 @item @file{inttypes.h} vs.@: @file{stdint.h}
5847 @hdrindex{inttypes.h}
5848 @hdrindex{stdint.h}
5849 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5850 no need to include @file{stdint.h} separately in a standard environment.
5851 However, some implementations have @file{inttypes.h} but not @file{stdint.h}
5852 (e.g., Solaris 7), and some have @file{stdint.h} but not @file{inttypes.h}
5853 (e.g. MSVC 2012).  Therefore, it is necessary to check for each and include
5854 each only if available.
5856 @item @file{linux/irda.h}
5857 @hdrindex{linux/irda.h}
5858 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5860 @item @file{linux/random.h}
5861 @hdrindex{linux/random.h}
5862 This header may require @file{linux/types.h}.
5864 @item @file{net/if.h}
5865 @hdrindex{net/if.h}
5866 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5868 @item @file{netinet/if_ether.h}
5869 @hdrindex{netinet/if_ether.h}
5870 This header may require some combination of @file{sys/types.h},
5871 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5873 @item @file{sys/mount.h}
5874 @hdrindex{sys/mount.h}
5875 This header may require @file{sys/params.h}.
5877 @item @file{sys/ptem.h}
5878 @hdrindex{sys/ptem.h}
5879 This header may require @file{sys/stream.h}.
5881 @item @file{sys/socket.h}
5882 @hdrindex{sys/socket.h}
5883 This header may require @file{sys/types.h}.
5885 @item @file{sys/ucred.h}
5886 @hdrindex{sys/ucred.h}
5887 This header may require @file{sys/types.h}.
5889 @item @file{X11/extensions/scrnsaver.h}
5890 @hdrindex{X11/extensions/scrnsaver.h}
5891 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5892 so required that you might not even consider looking for it.
5894 @end table
5897 @node Particular Headers
5898 @subsection Particular Header Checks
5900 These macros check for particular system header files---whether they
5901 exist, and in some cases whether they declare certain symbols.
5903 @defmac AC_CHECK_HEADER_STDBOOL
5904 @acindex{CHECK_HEADER_STDBOOL}
5905 @cvindex HAVE__BOOL
5906 @hdrindex{stdbool.h}
5907 @caindex header_stdbool_h
5908 Check whether @file{stdbool.h} exists and conforms to C99 or later,
5909 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
5910 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5912 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5913 packages that supply a substitute @file{stdbool.h} on platforms lacking
5914 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5915 that explicitly checks for @file{stdbool.h}.
5916 @end defmac
5918 @defmac AC_HEADER_ASSERT
5919 @acindex{HEADER_ASSERT}
5920 @cvindex NDEBUG
5921 @hdrindex{assert.h}
5922 Check whether to enable assertions in the style of @file{assert.h}.
5923 Assertions are enabled by default, but the user can override this by
5924 invoking @command{configure} with the @option{--disable-assert} option.
5925 @end defmac
5927 @anchor{AC_HEADER_DIRENT}
5928 @defmac AC_HEADER_DIRENT
5929 @acindex{HEADER_DIRENT}
5930 @cvindex HAVE_DIRENT_H
5931 @cvindex HAVE_NDIR_H
5932 @cvindex HAVE_SYS_DIR_H
5933 @cvindex HAVE_SYS_NDIR_H
5934 @hdrindex{dirent.h}
5935 @hdrindex{sys/ndir.h}
5936 @hdrindex{sys/dir.h}
5937 @hdrindex{ndir.h}
5938 Check for the following header files.  For the first one that is
5939 found and defines @samp{DIR}, define the listed C preprocessor macro:
5941 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5942 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5943 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5944 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5945 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5946 @end multitable
5948 The directory-library declarations in your source code should look
5949 something like the following:
5951 @example
5952 @group
5953 #include <sys/types.h>
5954 #ifdef HAVE_DIRENT_H
5955 # include <dirent.h>
5956 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5957 #else
5958 # define dirent direct
5959 # define NAMLEN(dirent) ((dirent)->d_namlen)
5960 # ifdef HAVE_SYS_NDIR_H
5961 #  include <sys/ndir.h>
5962 # endif
5963 # ifdef HAVE_SYS_DIR_H
5964 #  include <sys/dir.h>
5965 # endif
5966 # ifdef HAVE_NDIR_H
5967 #  include <ndir.h>
5968 # endif
5969 #endif
5970 @end group
5971 @end example
5973 Using the above declarations, the program would declare variables to be
5974 of type @code{struct dirent}, not @code{struct direct}, and would access
5975 the length of a directory entry name by passing a pointer to a
5976 @code{struct dirent} to the @code{NAMLEN} macro.
5978 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5980 This macro is obsolescent, as all current systems with directory
5981 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5983 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5984 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5985 @end defmac
5987 @anchor{AC_HEADER_MAJOR}
5988 @defmac AC_HEADER_MAJOR
5989 @acindex{HEADER_MAJOR}
5990 @cvindex MAJOR_IN_MKDEV
5991 @cvindex MAJOR_IN_SYSMACROS
5992 @hdrindex{sys/mkdev.h}
5993 @hdrindex{sys/sysmacros.h}
5994 Detect the headers required to use @code{makedev}, @code{major}, and
5995 @code{minor}.  These functions may be defined by @file{sys/mkdev.h},
5996 @code{sys/sysmacros.h}, or @file{sys/types.h}.
5998 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
5999 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
6000 @file{sys/sysmacros.h}.  If neither macro is defined, they are either in
6001 @file{sys/types.h} or unavailable.
6003 To properly use these functions, your code should contain something
6004 like:
6006 @verbatim
6007 #include <sys/types.h>
6008 #ifdef MAJOR_IN_MKDEV
6009 # include <sys/mkdev.h>
6010 #elif defined MAJOR_IN_SYSMACROS
6011 # include <sys/sysmacros.h>
6012 #endif
6013 @end verbatim
6015 Note: Configure scripts built with Autoconf 2.69 or earlier will not
6016 detect a problem if @file{sys/types.h} contains definitions of
6017 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
6018 warnings upon use.  This is known to occur with GNU libc 2.25, where
6019 those definitions are being deprecated to reduce namespace pollution.
6020 If it is not practical to use Autoconf 2.70 to regenerate the configure
6021 script of affected software, you can work around the problem by setting
6022 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6023 @command{configure} or as part of a @file{config.site} site default file
6024 (@pxref{Site Defaults}).
6025 @end defmac
6027 @defmac AC_HEADER_RESOLV
6028 @acindex{HEADER_RESOLV}
6029 @cvindex HAVE_RESOLV_H
6030 @hdrindex{resolv.h}
6031 Checks for header @file{resolv.h}, checking for prerequisites first.
6032 To properly use @file{resolv.h}, your code should contain something like
6033 the following:
6035 @verbatim
6036 #ifdef HAVE_SYS_TYPES_H
6037 #  include <sys/types.h>
6038 #endif
6039 #ifdef HAVE_NETINET_IN_H
6040 #  include <netinet/in.h>   /* inet_ functions / structs */
6041 #endif
6042 #ifdef HAVE_ARPA_NAMESER_H
6043 #  include <arpa/nameser.h> /* DNS HEADER struct */
6044 #endif
6045 #ifdef HAVE_NETDB_H
6046 #  include <netdb.h>
6047 #endif
6048 #include <resolv.h>
6049 @end verbatim
6050 @end defmac
6052 @anchor{AC_HEADER_STAT}
6053 @defmac AC_HEADER_STAT
6054 @acindex{HEADER_STAT}
6055 @cvindex STAT_MACROS_BROKEN
6056 @hdrindex{sys/stat.h}
6057 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6058 @file{sys/stat.h} do not work properly (returning false positives),
6059 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
6060 Amdahl UTS and Motorola System V/88.
6062 This macro is obsolescent, as no current systems have the bug.
6063 New programs need not use this macro.
6064 @end defmac
6066 @defmac AC_HEADER_STDBOOL
6067 @acindex{HEADER_STDBOOL}
6068 @cvindex HAVE_STDBOOL_H
6069 @cvindex HAVE__BOOL
6070 @hdrindex{stdbool.h}
6071 @caindex header_stdbool_h
6072 If @file{stdbool.h} exists and conforms to C99 or later, define
6073 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6074 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
6075 program could contain the following code:
6077 @example
6078 @group
6079 #ifdef HAVE_STDBOOL_H
6080 # include <stdbool.h>
6081 #else
6082 # ifndef HAVE__BOOL
6083 #  ifdef __cplusplus
6084 typedef bool _Bool;
6085 #  else
6086 #   define _Bool signed char
6087 #  endif
6088 # endif
6089 # define bool _Bool
6090 # define false 0
6091 # define true 1
6092 # define __bool_true_false_are_defined 1
6093 #endif
6094 @end group
6095 @end example
6097 Alternatively you can use the @samp{stdbool} package of Gnulib
6098 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6099 @code{#include <stdbool.h>}, and it adds support for less-common
6100 platforms.
6102 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6103 variable.
6105 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6106 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6107 does not.
6108 @end defmac
6110 @anchor{AC_HEADER_STDC}
6111 @defmac AC_HEADER_STDC
6112 @acindex{HEADER_STDC}
6113 @cvindex STDC_HEADERS
6114 @caindex header_stdc
6116 This macro is obsolescent.  Its sole effect is to make sure that all the
6117 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6118 Includes}), but not part of ISO C90, have been checked for.
6120 All hosted environments that are still of interest for portable code
6121 provide all of the headers specified in ISO C90 (as amended in 1995).
6122 @end defmac
6124 @defmac AC_HEADER_SYS_WAIT
6125 @acindex{HEADER_SYS_WAIT}
6126 @cvindex HAVE_SYS_WAIT_H
6127 @hdrindex{sys/wait.h}
6128 @caindex header_sys_wait_h
6129 If @file{sys/wait.h} exists and is compatible with Posix, define
6130 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6131 does not exist, or if it uses the old BSD @code{union wait} instead
6132 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6133 Posix compatible, then instead of including it, define the
6134 Posix macros with their usual interpretations.  Here is an
6135 example:
6137 @example
6138 @group
6139 #include <sys/types.h>
6140 #ifdef HAVE_SYS_WAIT_H
6141 # include <sys/wait.h>
6142 #endif
6143 #ifndef WEXITSTATUS
6144 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6145 #endif
6146 #ifndef WIFEXITED
6147 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6148 #endif
6149 @end group
6150 @end example
6152 @noindent
6153 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6154 variable.
6156 This macro is obsolescent, as current systems are compatible with Posix.
6157 New programs need not use this macro.
6158 @end defmac
6160 @cvindex _POSIX_VERSION
6161 @hdrindex{unistd.h}
6162 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6163 Posix systems.  If there is no @file{unistd.h}, it is definitely
6164 not a Posix system.  However, some non-Posix systems do
6165 have @file{unistd.h}.
6167 The way to check whether the system supports Posix is:
6169 @example
6170 @group
6171 #ifdef HAVE_UNISTD_H
6172 # include <sys/types.h>
6173 # include <unistd.h>
6174 #endif
6176 #ifdef _POSIX_VERSION
6177 /* Code for Posix systems.  */
6178 #endif
6179 @end group
6180 @end example
6182 @defmac AC_HEADER_TIOCGWINSZ
6183 @acindex{HEADER_TIOCGWINSZ}
6184 @cvindex GWINSZ_IN_SYS_IOCTL
6185 @hdrindex{sys/ioctl.h}
6186 @hdrindex{termios.h}
6187 @c FIXME: I need clarifications from Jim.
6188 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6189 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6190 found in @file{<termios.h>}.
6192 Use:
6194 @example
6195 @group
6196 #ifdef HAVE_TERMIOS_H
6197 # include <termios.h>
6198 #endif
6200 #ifdef GWINSZ_IN_SYS_IOCTL
6201 # include <sys/ioctl.h>
6202 #endif
6203 @end group
6204 @end example
6205 @end defmac
6207 @node Generic Headers
6208 @subsection Generic Header Checks
6210 These macros are used to find system header files not covered by the
6211 ``particular'' test macros.  If you need to check the contents of a header
6212 as well as find out whether it is present, you have to write your own
6213 test for it (@pxref{Writing Tests}).
6215 @anchor{AC_CHECK_HEADER}
6216 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6217   @ovar{action-if-not-found}, @ovar{includes})
6218 @acindex{CHECK_HEADER}
6219 @caindex header_@var{header-file}
6220 If the system header file @var{header-file} is compilable, execute shell
6221 commands @var{action-if-found}, otherwise execute
6222 @var{action-if-not-found}.  If you just want to define a symbol if the
6223 header file is available, consider using @code{AC_CHECK_HEADERS}
6224 instead.
6226 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6227 whatever might be required to appear above
6228 @samp{#include <@var{header-file}>} for it to compile without error.
6229 This can be anything, but will normally be additional @samp{#include}
6230 directives. If @var{includes} is omitted or empty, @file{configure} will
6231 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6232 @xref{Default Includes}.
6234 This macro used to check only for the @emph{presence} of a header, not
6235 whether its contents were acceptable to the compiler.  Some older
6236 @command{configure} scripts rely on this behavior, so it is still
6237 available by specifying @samp{-} as @var{includes}.  This mechanism is
6238 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6239 check is required should use @code{AC_PREPROC_IFELSE}.
6240 @xref{Running the Preprocessor}.
6242 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6243 variable, with characters not suitable for a variable name mapped to
6244 underscores.
6245 @end defmac
6247 @anchor{AC_CHECK_HEADERS}
6248 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6249   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6250   @ovar{includes})
6251 @acindex{CHECK_HEADERS}
6252 @cvindex HAVE_@var{header}
6253 @caindex header_@var{header-file}
6254 For each given system header file @var{header-file} in the
6255 blank-separated argument list that exists, define
6256 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6257 is given, it is additional shell code to execute when one of the header
6258 files is found.  You can give it a value of @samp{break} to break out of
6259 the loop on the first match.  If @var{action-if-not-found} is given, it
6260 is executed when one of the header files is not found.
6262 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6263 choose the set of preprocessor directives supplied before the header
6264 under test.
6266 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6267 variable, with characters not suitable for a variable name mapped to
6268 underscores.
6269 @end defmac
6271 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6272 @acindex{CHECK_HEADERS_ONCE}
6273 @cvindex HAVE_@var{header}
6274 For each given system header file @var{header-file} in the
6275 blank-separated argument list that exists, define
6276 @code{HAVE_@var{header-file}} (in all capitals).
6278 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6279 variant generates smaller, faster @command{configure} files.  All
6280 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6281 pass, early during the @command{configure} run.  The checks cannot be
6282 conditionalized, you cannot specify an @var{action-if-found} or
6283 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6284 for the prerequisites.
6285 @end defmac
6287 In previous versions of Autoconf, these macros merely checked whether
6288 the header was accepted by the preprocessor.  This was changed because
6289 the old test was inappropriate for typical uses.  Headers are typically
6290 used to compile, not merely to preprocess, and the old behavior
6291 sometimes accepted headers that clashed at compile-time
6292 (@pxref{Present But Cannot Be Compiled}).  If for some reason it is
6293 inappropriate to check whether a header is compilable, you should use
6294 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6295 these macros.
6297 Requiring each header to compile improves the robustness of the test,
6298 but it also requires you to make sure that the @var{includes} are
6299 correct.  Most system headers nowadays make sure to @code{#include}
6300 whatever they require, or else have their dependencies satisfied by
6301 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6302 @pxref{Header Portability}, for known exceptions.  In general, if you
6303 are looking for @file{bar.h}, which requires that @file{foo.h} be
6304 included first if it exists, you should do something like this:
6306 @example
6307 AC_CHECK_HEADERS([foo.h])
6308 AC_CHECK_HEADERS([bar.h], [], [],
6309 [#ifdef HAVE_FOO_H
6310 # include <foo.h>
6311 #endif
6313 @end example
6315 @node Declarations
6316 @section Declarations
6317 @cindex Declaration, checking
6319 The following macros check for the declaration of variables and
6320 functions.  If there is no macro specifically defined to check for a
6321 symbol you need, then you can use the general macros (@pxref{Generic
6322 Declarations}) or, for more complex tests, you may use
6323 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6325 @menu
6326 * Particular Declarations::     Macros to check for certain declarations
6327 * Generic Declarations::        How to find other declarations
6328 @end menu
6330 @node Particular Declarations
6331 @subsection Particular Declaration Checks
6333 There are no specific macros for declarations.
6335 @node Generic Declarations
6336 @subsection Generic Declaration Checks
6338 These macros are used to find declarations not covered by the ``particular''
6339 test macros.
6341 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6342   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6343 @acindex{CHECK_DECL}
6344 @caindex have_decl_@var{symbol}
6345 If @var{symbol} (a function, variable, or constant) is not declared in
6346 @var{includes} and a declaration is needed, run the shell commands
6347 @var{action-if-not-found}, otherwise @var{action-if-found}.
6348 @var{includes} is a series of include directives, defaulting to
6349 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6350 prior to the declaration under test.
6352 This macro actually tests whether @var{symbol} is defined as a macro or
6353 can be used as an r-value, not whether it is really declared, because it
6354 is much safer to avoid introducing extra declarations when they are not
6355 needed.  In order to facilitate use of C++ and overloaded function
6356 declarations, it is possible to specify function argument types in
6357 parentheses for types which can be zero-initialized:
6359 @example
6360 AC_CHECK_DECL([basename(char *)])
6361 @end example
6363 Some compilers don't indicate every missing declaration by the error
6364 status.  This macro checks the standard error from such compilers and
6365 considers a declaration missing if any warnings have been reported.  For
6366 most compilers, though, warnings do not affect this macro's outcome
6367 unless @code{AC_LANG_WERROR} is also specified.
6369 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6370 variable, with characters not suitable for a variable name mapped to
6371 underscores.
6372 @end defmac
6374 @anchor{AC_CHECK_DECLS}
6375 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6376   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6377 @acindex{CHECK_DECLS}
6378 @cvindex HAVE_DECL_@var{symbol}
6379 @caindex have_decl_@var{symbol}
6380 For each of the @var{symbols} (@emph{comma}-separated list with optional
6381 function argument types for C++ overloads), define
6382 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6383 @var{symbol} is declared, otherwise to @samp{0}.  If
6384 @var{action-if-not-found} is given, it is additional shell code to
6385 execute when one of the function declarations is needed, otherwise
6386 @var{action-if-found} is executed.
6388 @var{includes} is a series of include directives, defaulting to
6389 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6390 prior to the declarations under test.
6392 This macro uses an M4 list as first argument:
6393 @example
6394 AC_CHECK_DECLS([strdup])
6395 AC_CHECK_DECLS([strlen])
6396 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6397 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6398 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6399 @end example
6401 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6402 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6403 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6404 @emph{sure} that the check was performed, use
6405 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6407 @example
6408 #if !HAVE_DECL_SYMBOL
6409 extern char *symbol;
6410 #endif
6411 @end example
6413 @noindent
6414 If the test may have not been performed, however, because it is safer
6415 @emph{not} to declare a symbol than to use a declaration that conflicts
6416 with the system's one, you should use:
6418 @example
6419 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6420 void *malloc (size_t *s);
6421 #endif
6422 @end example
6424 @noindent
6425 You fall into the second category only in extreme situations: either
6426 your files may be used without being configured, or they are used during
6427 the configuration.  In most cases the traditional approach is enough.
6429 Some compilers don't indicate every missing declaration by the error
6430 status.  This macro checks the standard error from such compilers and
6431 considers a declaration missing if any warnings have been reported.  For
6432 most compilers, though, warnings do not affect this macro's outcome
6433 unless @code{AC_LANG_WERROR} is also specified.
6435 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6436 variables, with characters not suitable for a variable name mapped to
6437 underscores.
6438 @end defmac
6440 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6441 @acindex{CHECK_DECLS_ONCE}
6442 @cvindex HAVE_DECL_@var{symbol}
6443 For each of the @var{symbols} (@emph{comma}-separated list), define
6444 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6445 @var{symbol} is declared in the default include files, otherwise to
6446 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6447 generates the checking code at most once, so that @command{configure} is
6448 smaller and faster; but the checks cannot be conditionalized and are
6449 always done once, early during the @command{configure} run.
6450 @end defmac
6453 @node Structures
6454 @section Structures
6455 @cindex Structure, checking
6457 The following macros check for the presence of certain members in C
6458 structures.  If there is no macro specifically defined to check for a
6459 member you need, then you can use the general structure-member macros
6460 (@pxref{Generic Structures}) or, for more complex tests, you may use
6461 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6463 @menu
6464 * Particular Structures::       Macros to check for certain structure members
6465 * Generic Structures::          How to find other structure members
6466 @end menu
6468 @node Particular Structures
6469 @subsection Particular Structure Checks
6471 The following macros check for certain structures or structure members.
6473 @defmac AC_STRUCT_DIRENT_D_INO
6474 @acindex{STRUCT_DIRENT_D_INO}
6475 @cvindex HAVE_STRUCT_DIRENT_D_INO
6476 @c @caindex header_dirent_dirent_h
6477 @c @caindex member_struct_dirent_d_ino
6478 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6479 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6480 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6482 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6483 @code{d_ino}, not whether its contents are always reliable.
6484 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6485 though current systems hide this detail from the user and never return
6486 zero @code{d_ino} values.
6487 Many current systems report an incorrect @code{d_ino} for a directory
6488 entry that is a mount point.
6489 @end defmac
6491 @defmac AC_STRUCT_DIRENT_D_TYPE
6492 @acindex{STRUCT_DIRENT_D_TYPE}
6493 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6494 @c @caindex header_dirent_dirent_h
6495 @c @caindex member_struct_dirent_d_type
6496 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6497 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6498 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6499 @end defmac
6501 @anchor{AC_STRUCT_ST_BLOCKS}
6502 @defmac AC_STRUCT_ST_BLOCKS
6503 @acindex{STRUCT_ST_BLOCKS}
6504 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6505 @cvindex HAVE_ST_BLOCKS
6506 @ovindex LIBOBJS
6507 @caindex member_struct_stat_st_blocks
6508 If @code{struct stat} contains an @code{st_blocks} member, define
6509 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6510 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6511 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6512 future.
6514 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6515 variable.
6516 @end defmac
6518 @defmac AC_STRUCT_TM
6519 @acindex{STRUCT_TM}
6520 @cvindex TM_IN_SYS_TIME
6521 @hdrindex{time.h}
6522 @hdrindex{sys/time.h}
6523 If @file{time.h} does not define @code{struct tm}, define
6524 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6525 had better define @code{struct tm}.
6527 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6528 current systems.  New programs need not use this macro.
6529 @end defmac
6531 @anchor{AC_STRUCT_TIMEZONE}
6532 @defmac AC_STRUCT_TIMEZONE
6533 @acindex{STRUCT_TIMEZONE}
6534 @cvindex HAVE_DECL_TZNAME
6535 @cvindex HAVE_STRUCT_TM_TM_ZONE
6536 @cvindex HAVE_TM_ZONE
6537 @cvindex HAVE_TZNAME
6538 @c @caindex member_struct_tm_tm_zone
6539 @c @caindex struct_tm
6540 Figure out how to get the current timezone.  If @code{struct tm} has a
6541 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6542 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6543 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6544 define @code{HAVE_DECL_TZNAME}.
6545 @end defmac
6547 @node Generic Structures
6548 @subsection Generic Structure Checks
6550 These macros are used to find structure members not covered by the
6551 ``particular'' test macros.
6553 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6554   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6555   @dvar{includes, AC_INCLUDES_DEFAULT})
6556 @acindex{CHECK_MEMBER}
6557 @caindex member_@var{aggregate}_@var{member}
6558 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6559 If no @var{includes} are specified, the default includes are used
6560 (@pxref{Default Includes}).
6562 @example
6563 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6564                 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6565                 [[#include <pwd.h>]])
6566 @end example
6568 You can use this macro for submembers:
6570 @example
6571 AC_CHECK_MEMBER(struct top.middle.bot)
6572 @end example
6574 This macro caches its result in the
6575 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6576 characters not suitable for a variable name mapped to underscores.
6577 @end defmac
6579 @anchor{AC_CHECK_MEMBERS}
6580 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6581   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6582 @acindex{CHECK_MEMBERS}
6583 @cvindex HAVE_@var{aggregate}_@var{member}
6584 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6585 @var{members} using the previous macro.  When @var{member} belongs to
6586 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6587 capitals, with spaces and dots replaced by underscores).  If
6588 @var{action-if-found} is given, it is executed for each of the found
6589 members.  If @var{action-if-not-found} is given, it is executed for each
6590 of the members that could not be found.
6592 @var{includes} is a series of include directives, defaulting to
6593 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6594 prior to the members under test.
6596 This macro uses M4 lists:
6597 @example
6598 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6599 @end example
6600 @end defmac
6603 @node Types
6604 @section Types
6605 @cindex Types
6606 @cindex C types
6608 The following macros check for C types, either builtin or typedefs.  If
6609 there is no macro specifically defined to check for a type you need, and
6610 you don't need to check for any special properties of it, then you can
6611 use a general type-check macro.
6613 @menu
6614 * Particular Types::            Special handling to find certain types
6615 * Generic Types::               How to find other types
6616 @end menu
6618 @node Particular Types
6619 @subsection Particular Type Checks
6621 @hdrindex{sys/types.h}
6622 @hdrindex{stdlib.h}
6623 @hdrindex{stdint.h}
6624 @hdrindex{inttypes.h}
6625 These macros check for particular C types in @file{sys/types.h},
6626 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6627 exist.
6629 The Gnulib @code{stdint} module is an alternate way to define many of
6630 these symbols; it is useful if you prefer your code to assume a
6631 C99-or-better environment.  @xref{Gnulib}.
6633 @anchor{AC_TYPE_GETGROUPS}
6634 @defmac AC_TYPE_GETGROUPS
6635 @acindex{TYPE_GETGROUPS}
6636 @cvindex GETGROUPS_T
6637 @caindex type_getgroups
6638 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6639 is the base type of the array argument to @code{getgroups}.
6641 This macro caches the base type in the @code{ac_cv_type_getgroups}
6642 variable.
6643 @end defmac
6645 @defmac AC_TYPE_INT8_T
6646 @acindex{TYPE_INT8_T}
6647 @cvindex HAVE_INT8_T
6648 @cvindex int8_t
6649 @caindex c_int8_t
6650 If @file{stdint.h} or @file{inttypes.h} does not define the type
6651 @code{int8_t}, define @code{int8_t} to a signed
6652 integer type that is exactly 8 bits wide and that uses two's complement
6653 representation, if such a type exists.
6654 If you are worried about porting to hosts that lack such a type, you can
6655 use the results of this macro in C89-or-later code as follows:
6657 @example
6658 #if HAVE_STDINT_H
6659 # include <stdint.h>
6660 #endif
6661 #if defined INT8_MAX || defined int8_t
6662  @emph{code using int8_t}
6663 #else
6664  @emph{complicated alternative using >8-bit 'signed char'}
6665 #endif
6666 @end example
6668 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6669 @end defmac
6671 @defmac AC_TYPE_INT16_T
6672 @acindex{TYPE_INT16_T}
6673 @cvindex HAVE_INT16_T
6674 @cvindex int16_t
6675 @caindex c_int16_t
6676 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6677 @end defmac
6679 @defmac AC_TYPE_INT32_T
6680 @acindex{TYPE_INT32_T}
6681 @cvindex HAVE_INT32_T
6682 @cvindex int32_t
6683 @caindex c_int32_t
6684 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6685 @end defmac
6687 @defmac AC_TYPE_INT64_T
6688 @acindex{TYPE_INT64_T}
6689 @cvindex HAVE_INT64_T
6690 @cvindex int64_t
6691 @caindex c_int64_t
6692 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6693 @end defmac
6695 @defmac AC_TYPE_INTMAX_T
6696 @acindex{TYPE_INTMAX_T}
6697 @cvindex HAVE_INTMAX_T
6698 @cvindex intmax_t
6699 @c @caindex type_intmax_t
6700 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6701 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6702 widest signed integer type.
6703 @end defmac
6705 @defmac AC_TYPE_INTPTR_T
6706 @acindex{TYPE_INTPTR_T}
6707 @cvindex HAVE_INTPTR_T
6708 @cvindex intptr_t
6709 @c @caindex type_intptr_t
6710 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6711 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6712 signed integer type wide enough to hold a pointer, if such a type
6713 exists.
6714 @end defmac
6716 @defmac AC_TYPE_LONG_DOUBLE
6717 @acindex{TYPE_LONG_DOUBLE}
6718 @cvindex HAVE_LONG_DOUBLE
6719 @caindex type_long_double
6720 If the C compiler supports a working @code{long double} type, define
6721 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6722 same range and precision as @code{double}.
6724 This macro caches its result in the @code{ac_cv_type_long_double}
6725 variable.
6727 This macro is obsolescent, as current C compilers support @code{long
6728 double}.  New programs need not use this macro.
6729 @end defmac
6731 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6732 @acindex{TYPE_LONG_DOUBLE_WIDER}
6733 @cvindex HAVE_LONG_DOUBLE_WIDER
6734 @caindex type_long_double_wider
6735 If the C compiler supports a working @code{long double} type with more
6736 range or precision than the @code{double} type, define
6737 @code{HAVE_LONG_DOUBLE_WIDER}.
6739 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6740 variable.
6741 @end defmac
6743 @defmac AC_TYPE_LONG_LONG_INT
6744 @acindex{TYPE_LONG_LONG_INT}
6745 @cvindex HAVE_LONG_LONG_INT
6746 @caindex type_long_long_int
6747 If the C compiler supports a working @code{long long int} type, define
6748 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6749 @code{long long int} values in preprocessor @code{#if} expressions,
6750 because too many compilers mishandle such expressions.
6751 @xref{Preprocessor Arithmetic}.
6753 This macro caches its result in the @code{ac_cv_type_long_long_int}
6754 variable.
6755 @end defmac
6757 @defmac AC_TYPE_MBSTATE_T
6758 @acindex{TYPE_MBSTATE_T}
6759 @cvindex mbstate_t
6760 @hdrindex{wchar.h}
6761 @caindex type_mbstate_t
6762 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6763 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6764 @code{<wchar.h>} does not declare it.
6766 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6767 variable.
6768 @end defmac
6770 @anchor{AC_TYPE_MODE_T}
6771 @defmac AC_TYPE_MODE_T
6772 @acindex{TYPE_MODE_T}
6773 @cvindex mode_t
6774 @caindex type_mode_t
6775 Define @code{mode_t} to a suitable type, if standard headers do not
6776 define it.
6778 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6779 @end defmac
6781 @anchor{AC_TYPE_OFF_T}
6782 @defmac AC_TYPE_OFF_T
6783 @acindex{TYPE_OFF_T}
6784 @cvindex off_t
6785 @caindex type_off_t
6786 Define @code{off_t} to a suitable type, if standard headers do not
6787 define it.
6789 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6790 @end defmac
6792 @anchor{AC_TYPE_PID_T}
6793 @defmac AC_TYPE_PID_T
6794 @acindex{TYPE_PID_T}
6795 @cvindex pid_t
6796 @caindex type_pid_t
6797 Define @code{pid_t} to a suitable type, if standard headers do not
6798 define it.
6800 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6801 @end defmac
6803 @anchor{AC_TYPE_SIZE_T}
6804 @defmac AC_TYPE_SIZE_T
6805 @acindex{TYPE_SIZE_T}
6806 @cvindex size_t
6807 @caindex type_size_t
6808 Define @code{size_t} to a suitable type, if standard headers do not
6809 define it.
6811 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6812 @end defmac
6814 @defmac AC_TYPE_SSIZE_T
6815 @acindex{TYPE_SSIZE_T}
6816 @cvindex ssize_t
6817 @caindex type_ssize_t
6818 Define @code{ssize_t} to a suitable type, if standard headers do not
6819 define it.
6821 This macro caches its result in the @code{ac_cv_type_ssize_t} variable.
6822 @end defmac
6824 @anchor{AC_TYPE_UID_T}
6825 @defmac AC_TYPE_UID_T
6826 @acindex{TYPE_UID_T}
6827 @cvindex uid_t
6828 @cvindex gid_t
6829 @caindex type_uid_t
6830 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6831 headers do not define them.
6833 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6834 @end defmac
6836 @defmac AC_TYPE_UINT8_T
6837 @acindex{TYPE_UINT8_T}
6838 @cvindex HAVE_UINT8_T
6839 @cvindex uint8_t
6840 @caindex c_uint8_t
6841 If @file{stdint.h} or @file{inttypes.h} does not define the type
6842 @code{uint8_t}, define @code{uint8_t} to an
6843 unsigned integer type that is exactly 8 bits wide, if such a type
6844 exists.
6845 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6846 @end defmac
6848 @defmac AC_TYPE_UINT16_T
6849 @acindex{TYPE_UINT16_T}
6850 @cvindex HAVE_UINT16_T
6851 @cvindex uint16_t
6852 @caindex c_uint16_t
6853 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6854 @end defmac
6856 @defmac AC_TYPE_UINT32_T
6857 @acindex{TYPE_UINT32_T}
6858 @cvindex HAVE_UINT32_T
6859 @cvindex uint32_t
6860 @caindex c_uint32_t
6861 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6862 @end defmac
6864 @defmac AC_TYPE_UINT64_T
6865 @acindex{TYPE_UINT64_T}
6866 @cvindex HAVE_UINT64_T
6867 @cvindex uint64_t
6868 @caindex c_uint64_t
6869 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6870 @end defmac
6872 @defmac AC_TYPE_UINTMAX_T
6873 @acindex{TYPE_UINTMAX_T}
6874 @cvindex HAVE_UINTMAX_T
6875 @cvindex uintmax_t
6876 @c @caindex type_uintmax_t
6877 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6878 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6879 widest unsigned integer type.
6880 @end defmac
6882 @defmac AC_TYPE_UINTPTR_T
6883 @acindex{TYPE_UINTPTR_T}
6884 @cvindex HAVE_UINTPTR_T
6885 @cvindex uintptr_t
6886 @c @caindex type_uintptr_t
6887 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6888 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6889 unsigned integer type wide enough to hold a pointer, if such a type
6890 exists.
6891 @end defmac
6893 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6894 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6895 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6896 @caindex type_unsigned_long_long_int
6897 If the C compiler supports a working @code{unsigned long long int} type,
6898 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6899 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6900 because too many compilers mishandle such expressions.
6901 @xref{Preprocessor Arithmetic}.
6903 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6904 variable.
6905 @end defmac
6907 @node Generic Types
6908 @subsection Generic Type Checks
6910 These macros are used to check for types not covered by the ``particular''
6911 test macros.
6913 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6914   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6915 @acindex{CHECK_TYPE}
6916 @caindex type_@var{type}
6917 Check whether @var{type} is defined.  It may be a compiler builtin type
6918 or defined by the @var{includes}.  @var{includes} is a series of include
6919 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6920 Includes}), which are used prior to the type under test.
6922 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6923 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6924 same test is applied when compiling for C++, which means that in C++
6925 @var{type} should be a type-id and should not be an anonymous
6926 @samp{struct} or @samp{union}.
6928 This macro caches its result in the @code{ac_cv_type_@var{type}}
6929 variable, with @samp{*} mapped to @samp{p} and other characters not
6930 suitable for a variable name mapped to underscores.
6931 @end defmac
6934 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6935   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6936 @acindex{CHECK_TYPES}
6937 @cvindex HAVE_@var{type}
6938 For each @var{type} of the @var{types} that is defined, define
6939 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6940 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6941 specified, the default includes are used (@pxref{Default Includes}).  If
6942 @var{action-if-found} is given, it is additional shell code to execute
6943 when one of the types is found.  If @var{action-if-not-found} is given,
6944 it is executed when one of the types is not found.
6946 This macro uses M4 lists:
6947 @example
6948 AC_CHECK_TYPES([ptrdiff_t])
6949 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6950 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6951 @end example
6953 @end defmac
6955 Autoconf, up to 2.13, used to provide to another version of
6956 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6957 compatibility, a simple heuristic, quite safe but not totally, is
6958 implemented.  In case of doubt, read the documentation of the former
6959 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6962 @node Compilers and Preprocessors
6963 @section Compilers and Preprocessors
6964 @cindex Compilers
6965 @cindex Preprocessors
6967 @ovindex EXEEXT
6968 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6969 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6970 the output of the compiler, typically to the empty string if
6971 Posix and @samp{.exe} if a DOS variant.
6973 @ovindex OBJEXT
6974 They also define the output variable @code{OBJEXT} based on the
6975 output of the compiler, after @file{.c} files have been excluded, typically
6976 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6978 If the compiler being used does not produce executables, the tests fail.  If
6979 the executables can't be run, and cross-compilation is not enabled, they
6980 fail too.  @xref{Manual Configuration}, for more on support for cross
6981 compiling.
6983 @menu
6984 * Specific Compiler Characteristics::  Some portability issues
6985 * Generic Compiler Characteristics::  Language independent tests and features
6986 * C Compiler::                  Checking its characteristics
6987 * C++ Compiler::                Likewise
6988 * Objective C Compiler::        Likewise
6989 * Objective C++ Compiler::      Likewise
6990 * Erlang Compiler and Interpreter::  Likewise
6991 * Fortran Compiler::            Likewise
6992 * Go Compiler::                 Likewise
6993 @end menu
6995 @node Specific Compiler Characteristics
6996 @subsection Specific Compiler Characteristics
6998 Some compilers exhibit different behaviors.
7000 @table @asis
7001 @item Static/Dynamic Expressions
7002 Autoconf relies on a trick to extract one bit of information from the C
7003 compiler: using negative array sizes.  For instance the following
7004 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
7005 bytes wide:
7007 @example
7008 static int test_array[sizeof (int) == 4 ? 1 : -1];
7009 @end example
7011 @noindent
7012 To our knowledge, there is a single compiler that does not support this
7013 trick: the HP C compilers (the real ones, not only the
7014 ``bundled'') on HP-UX 11.00.
7015 They incorrectly reject the above program with the diagnostic
7016 ``Variable-length arrays cannot have static storage.''
7017 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
7018 not from the @code{? 1 : -1}, and
7019 Autoconf works around this problem by casting @code{sizeof (int)} to
7020 @code{long int} before comparing it.
7021 @end table
7023 @node Generic Compiler Characteristics
7024 @subsection Generic Compiler Characteristics
7026 @anchor{AC_CHECK_SIZEOF}
7027 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7028   @dvar{includes, AC_INCLUDES_DEFAULT})
7029 @acindex{CHECK_SIZEOF}
7030 @cvindex SIZEOF_@var{type-or-expr}
7031 @caindex sizeof_@var{type-or-expr}
7032 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7033 the size in bytes of @var{type-or-expr}, which may be either a type or
7034 an expression returning a value that has a size.  If the expression
7035 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7036 @var{includes} is a series of include directives, defaulting to
7037 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7038 prior to the expression under test.
7040 This macro now works even when cross-compiling.  The @var{unused}
7041 argument was used when cross-compiling.
7043 For example, the call
7045 @example
7046 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7047 AC_CHECK_SIZEOF([int *])
7048 @end example
7050 @noindent
7051 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7053 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7054 variable, with @samp{*} mapped to @samp{p} and other characters not
7055 suitable for a variable name mapped to underscores.
7056 @end defmac
7058 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7059 @acindex{CHECK_ALIGNOF}
7060 @cvindex ALIGNOF_@var{type}
7061 @caindex alignof_@var{type-or-expr}
7062 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7063 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7064 a structure member declaration.  If @samp{type} is unknown, the result
7065 is 0.  If no @var{includes} are specified, the default includes are used
7066 (@pxref{Default Includes}).
7068 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7069 variable, with @samp{*} mapped to @samp{p} and other characters not
7070 suitable for a variable name mapped to underscores.
7071 @end defmac
7073 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7074   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7075 @acindex{COMPUTE_INT}
7076 Store into the shell variable @var{var} the value of the integer
7077 @var{expression}.  The
7078 value should fit in an initializer in a C variable of type @code{signed
7079 long}.  To support cross compilation (in which case, the macro only works on
7080 hosts that use twos-complement arithmetic), it should be possible to evaluate
7081 the expression at compile-time.  If no @var{includes} are specified, the
7082 default includes are used (@pxref{Default Includes}).
7084 Execute @var{action-if-fails} if the value cannot be determined correctly.
7085 @end defmac
7087 @defmac AC_LANG_WERROR
7088 @acindex{LANG_WERROR}
7089 Normally Autoconf ignores warnings generated by the compiler, linker, and
7090 preprocessor.  If this macro is used, warnings count as fatal
7091 errors for the current language.  This macro is useful when the
7092 results of configuration are used where warnings are unacceptable; for
7093 instance, if parts of a program are built with the GCC
7094 @option{-Werror}
7095 option.  If the whole program is built using @option{-Werror} it is
7096 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7097 etc.).
7098 @end defmac
7100 @defmac AC_OPENMP
7101 @acindex{OPENMP}
7102 @cvindex _OPENMP
7103 @ovindex OPENMP_CFLAGS
7104 @ovindex OPENMP_CXXFLAGS
7105 @ovindex OPENMP_FFLAGS
7106 @ovindex OPENMP_FCFLAGS
7107 @caindex prog_c_openmp
7108 @caindex prog_cxx_openmp
7109 @caindex prog_f77_openmp
7110 @caindex prog_fc_openmp
7111 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7112 and Fortran that simplify optimization of shared memory parallelism,
7113 which is a common problem on multicore CPUs.
7115 If the current language is C, the macro @code{AC_OPENMP} sets the
7116 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7117 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7118 compiler already supports OpenMP, if it has no way to activate OpenMP
7119 support, or if the user rejects OpenMP support by invoking
7120 @samp{configure} with the @samp{--disable-openmp} option.
7122 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7123 preprocessing program source, and when linking programs.  Therefore you
7124 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7125 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7126 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7127 OpenMP support is revealed at compile time by the preprocessor macro
7128 @code{_OPENMP}.
7130 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7131 shared library to the program's dependencies, so its use is recommended
7132 only on programs that actually require OpenMP.
7134 If the current language is C++, @code{AC_OPENMP} sets the variable
7135 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7136 hold as for C.
7138 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7139 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7140 respectively.  Similar remarks as for C hold, except that
7141 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7142 signals OpenMP support.
7144 For portability, it is best to avoid spaces between @samp{#} and
7145 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7146 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7147 latter.
7149 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7150 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7151 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7152 @end defmac
7154 @node C Compiler
7155 @subsection C Compiler Characteristics
7157 The following macros provide ways to find and exercise a C Compiler.
7158 There are a few constructs that ought to be avoided, but do not deserve
7159 being checked for, since they can easily be worked around.
7161 @table @asis
7162 @item Don't use lines containing solitary backslashes
7163 They tickle a bug in the HP-UX C compiler (checked on
7164 HP-UX 10.20,
7165 11.00, and 11i).  When given the following source:
7167 @example
7168 #ifdef __STDC__
7170 * A comment with backslash-newlines in it.  %@{ %@} *\
7173 char str[] = "\\
7174 " A string with backslash-newlines in it %@{ %@} \\
7176 char apostrophe = '\\
7180 #endif
7181 @end example
7183 @noindent
7184 the compiler incorrectly fails with the diagnostics ``Non-terminating
7185 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7186 Removing the lines with solitary backslashes solves the problem.
7188 @item Don't compile several files at once if output matters to you
7189 Some compilers, such as HP's, report names of files being
7190 compiled when given more than one file operand.  For instance:
7192 @example
7193 $ @kbd{cc a.c b.c}
7194 a.c:
7195 b.c:
7196 @end example
7198 @noindent
7199 This can cause problems if you observe the output of the compiler to
7200 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7201 b.o} solves the issue.
7203 @item Don't rely on @code{#error} failing
7204 The IRIX C compiler does not fail when #error is preprocessed; it
7205 simply emits a diagnostic and continues, exiting successfully.  So,
7206 instead of an error directive like @code{#error "Unsupported word size"}
7207 it is more portable to use an invalid directive like @code{#Unsupported
7208 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7209 OK, since installers with inadequate compilers like IRIX can simply
7210 examine these compilers' diagnostic output.
7212 @item Don't rely on correct @code{#line} support
7213 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7214 diagnoses @code{#line} directives whose line
7215 numbers are greater than 32767.  Nothing in Posix
7216 makes this invalid.  That is why Autoconf stopped issuing
7217 @code{#line} directives.
7218 @end table
7220 @anchor{AC_PROG_CC}
7221 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7222 @acindex{PROG_CC}
7223 @evindex CC
7224 @evindex CFLAGS
7225 @ovindex CC
7226 @ovindex CFLAGS
7227 @caindex prog_cc_stdc
7228 Determine a C compiler to use.  If @code{CC} is not already set in the
7229 environment, check for @code{gcc} and @code{cc}, then for other C
7230 compilers.  Set output variable @code{CC} to the name of the compiler
7231 found.
7233 This macro may, however, be invoked with an optional first argument
7234 which, if specified, must be a blank-separated list of C compilers to
7235 search for.  This just gives the user an opportunity to specify an
7236 alternative search list for the C compiler.  For example, if you didn't
7237 like the default order, then you could invoke @code{AC_PROG_CC} like
7238 this:
7240 @example
7241 AC_PROG_CC([gcc cl cc])
7242 @end example
7244 If necessary, add an option to output variable @code{CC} to enable
7245 support for ISO Standard C features with extensions.  Prefer the newest
7246 C standard that is supported.  Currently the newest standard is ISO C11,
7247 with ISO C99 and ANSI C89 (ISO C90) being the older versions.
7248 After calling this macro you can check whether the C compiler has been
7249 set to accept Standard C; if not, the shell variable
7250 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7252 When attempting to add compiler options, prefer extended functionality
7253 to strict conformance: the goal is to enable whatever standard features
7254 that are available, not to check for full conformance to the standard or
7255 to prohibit incompatible extensions.  Test for C11 support by checking
7256 for @code{_Alignas}, @code{_Alignof}, @code{_Noreturn},
7257 @code{_Static_assert}, UTF-8 string literals, duplicate @code{typedef}s,
7258 and anonymous structures and unions.  Test for C99 support by checking
7259 for @code{_Bool}, @code{//} comments, flexible array members,
7260 @code{inline}, signed and unsigned @code{long long int}, mixed code and
7261 declarations, named initialization of structs, @code{restrict},
7262 @code{va_copy}, varargs macros, variable declarations in @code{for}
7263 loops, and variable length arrays.  Test for C89 support by checking for
7264 function prototypes.
7266 If using a compiler that supports GNU C, set shell variable @code{GCC} to
7267 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7268 it to @option{-g -O2} for a GNU C compiler (@option{-O2} on systems
7269 where the compiler does not accept @option{-g}), or @option{-g} for
7270 other compilers.  If your package does not like this default, then it is
7271 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7272 and before @code{AC_PROG_CC} to select an empty default instead.
7274 Many Autoconf macros use a compiler, and thus call
7275 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7276 determined before the body of the outermost @code{AC_DEFUN} macro.
7277 @code{AC_PROG_CC} is therefore defined via @code{AC_DEFUN_ONCE} to avoid
7278 needless reexpansion (@pxref{One-Shot Macros}).
7279 @end defmac
7281 @anchor{AC_PROG_CC_C_O}
7282 @defmac AC_PROG_CC_C_O
7283 @acindex{PROG_CC_C_O}
7284 @cvindex NO_MINUS_C_MINUS_O
7285 @caindex prog_cc_@var{compiler}_c_o
7286 If the C compiler does not accept the @option{-c} and @option{-o} options
7287 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7288 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7289 the first @code{cc} in the path.  The test fails if one fails.  This
7290 macro was created for GNU Make to choose the default C compilation
7291 rule.
7293 For the compiler @var{compiler}, this macro caches its result in the
7294 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7295 @end defmac
7298 @defmac AC_PROG_CPP
7299 @acindex{PROG_CPP}
7300 @evindex CPP
7301 @ovindex CPP
7302 Set output variable @code{CPP} to a command that runs the
7303 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7304 It is only portable to run @code{CPP} on files with a @file{.c}
7305 extension.
7307 Some preprocessors don't indicate missing include files by the error
7308 status.  For such preprocessors an internal variable is set that causes
7309 other macros to check the standard error from the preprocessor and
7310 consider the test failed if any warnings have been reported.
7311 For most preprocessors, though, warnings do not cause include-file
7312 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7313 @end defmac
7315 @defmac AC_PROG_CPP_WERROR
7316 @acindex{PROG_CPP_WERROR}
7317 @ovindex CPP
7318 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7319 preprocessor as errors even if the preprocessor exit status indicates
7320 success.  This is useful for avoiding headers that generate mandatory
7321 warnings, such as deprecation notices.
7322 @end defmac
7325 The following macros check for C compiler or machine architecture
7326 features.  To check for characteristics not listed here, use
7327 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7328 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7330 @defmac AC_C_BACKSLASH_A
7331 @acindex{C_BACKSLASH_A}
7332 @cvindex HAVE_C_BACKSLASH_A
7333 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7334 @samp{\a}.
7336 This macro is obsolescent, as current C compilers understand @samp{\a}.
7337 New programs need not use this macro.
7338 @end defmac
7340 @anchor{AC_C_BIGENDIAN}
7341 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7342   @ovar{action-if-unknown}, @ovar{action-if-universal})
7343 @acindex{C_BIGENDIAN}
7344 @cvindex WORDS_BIGENDIAN
7345 @cindex Endianness
7346 If words are stored with the most significant byte first (like Motorola
7347 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7348 the least significant byte first (like Intel and VAX CPUs), execute
7349 @var{action-if-false}.
7351 This macro runs a test-case if endianness cannot be determined from the
7352 system header files.  When cross-compiling, the test-case is not run but
7353 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7354 the latter case fails to determine the byte sex of the host system.
7356 In some cases a single run of a compiler can generate code for multiple
7357 architectures.  This can happen, for example, when generating Mac OS X
7358 universal binary files, which work on both PowerPC and Intel
7359 architectures.  In this case, the different variants might be for
7360 different architectures whose endiannesses differ.  If
7361 @command{configure} detects this, it executes @var{action-if-universal}
7362 instead of @var{action-if-unknown}.
7364 The default for @var{action-if-true} is to define
7365 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7366 nothing.  The default for @var{action-if-unknown} is to
7367 abort configure and tell the installer how to bypass this test.
7368 And finally, the default for @var{action-if-universal} is to ensure that
7369 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7370 detected and the current code is big-endian; this default works only if
7371 @command{autoheader} is used (@pxref{autoheader Invocation}).
7373 If you use this macro without specifying @var{action-if-universal}, you
7374 should also use @code{AC_CONFIG_HEADERS}; otherwise
7375 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7376 binary files.
7377 @end defmac
7379 @anchor{AC_C_CONST}
7380 @defmac AC_C_CONST
7381 @acindex{C_CONST}
7382 @cvindex const
7383 @caindex c_const
7384 If the C compiler does not fully support the @code{const} keyword,
7385 define @code{const} to be empty.  Some C compilers that do
7386 not define @code{__STDC__} do support @code{const}; some compilers that
7387 define @code{__STDC__} do not completely support @code{const}.  Programs
7388 can simply use @code{const} as if every C compiler supported it; for
7389 those that don't, the makefile or configuration header file
7390 defines it as empty.
7392 Occasionally installers use a C++ compiler to compile C code, typically
7393 because they lack a C compiler.  This causes problems with @code{const},
7394 because C and C++ treat @code{const} differently.  For example:
7396 @example
7397 const int foo;
7398 @end example
7400 @noindent
7401 is valid in C but not in C++.  These differences unfortunately cannot be
7402 papered over by defining @code{const} to be empty.
7404 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7405 as this generally yields better results in practice.  However, using a
7406 C++ compiler to compile C code is not recommended or supported, and
7407 installers who run into trouble in this area should get a C compiler
7408 like GCC to compile their C code.
7410 This macro caches its result in the @code{ac_cv_c_const} variable.
7412 This macro is obsolescent, as current C compilers support @code{const}.
7413 New programs need not use this macro.
7414 @end defmac
7416 @defmac AC_C__GENERIC
7417 @acindex{C__GENERIC}
7418 @cvindex _Generic
7419 If the C compiler supports C11-style generic selection using the
7420 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7421 @end defmac
7423 @defmac AC_C_RESTRICT
7424 @acindex{C_RESTRICT}
7425 @cvindex restrict
7426 @caindex c_restrict
7427 If the C compiler recognizes a variant spelling for the @code{restrict}
7428 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7429 then define @code{restrict} to that; this is more likely to do the right
7430 thing with compilers that support language variants where plain
7431 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7432 recognizes the @code{restrict} keyword, don't do anything.
7433 Otherwise, define @code{restrict} to be empty.
7434 Thus, programs may simply use @code{restrict} as if every C compiler
7435 supported it; for those that do not, the makefile
7436 or configuration header defines it away.
7438 Although support in C++ for the @code{restrict} keyword is not
7439 required, several C++ compilers do accept the keyword.
7440 This macro works for them, too.
7442 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7443 if @code{restrict} is not supported, and a supported spelling otherwise.
7444 @end defmac
7446 @defmac AC_C_VOLATILE
7447 @acindex{C_VOLATILE}
7448 @cvindex volatile
7449 If the C compiler does not understand the keyword @code{volatile},
7450 define @code{volatile} to be empty.  Programs can simply use
7451 @code{volatile} as if every C compiler supported it; for those that do
7452 not, the makefile or configuration header defines it as
7453 empty.
7455 If the correctness of your program depends on the semantics of
7456 @code{volatile}, simply defining it to be empty does, in a sense, break
7457 your code.  However, given that the compiler does not support
7458 @code{volatile}, you are at its mercy anyway.  At least your
7459 program compiles, when it wouldn't before.
7460 @xref{Volatile Objects}, for more about @code{volatile}.
7462 In general, the @code{volatile} keyword is a standard C feature, so
7463 you might expect that @code{volatile} is available only when
7464 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7465 support volatile, but does not define @code{__STDC__}.
7467 This macro is obsolescent, as current C compilers support @code{volatile}.
7468 New programs need not use this macro.
7469 @end defmac
7471 @anchor{AC_C_INLINE}
7472 @defmac AC_C_INLINE
7473 @acindex{C_INLINE}
7474 @cvindex inline
7475 If the C compiler supports the keyword @code{inline}, do nothing.
7476 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7477 if it accepts one of those, otherwise define @code{inline} to be empty.
7478 @end defmac
7480 @anchor{AC_C_CHAR_UNSIGNED}
7481 @defmac AC_C_CHAR_UNSIGNED
7482 @acindex{C_CHAR_UNSIGNED}
7483 @cvindex __CHAR_UNSIGNED__
7484 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7485 unless the C compiler predefines it.
7487 These days, using this macro is not necessary.  The same information can
7488 be determined by this portable alternative, thus avoiding the use of
7489 preprocessor macros in the namespace reserved for the implementation.
7491 @example
7492 #include <limits.h>
7493 #if CHAR_MIN == 0
7494 # define CHAR_UNSIGNED 1
7495 #endif
7496 @end example
7497 @end defmac
7499 @defmac AC_C_STRINGIZE
7500 @acindex{C_STRINGIZE}
7501 @cvindex HAVE_STRINGIZE
7502 If the C preprocessor supports the stringizing operator, define
7503 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7504 found in macros such as this:
7506 @example
7507 #define x(y) #y
7508 @end example
7510 This macro is obsolescent, as current C compilers support the
7511 stringizing operator.  New programs need not use this macro.
7512 @end defmac
7514 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7515 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7516 @cvindex FLEXIBLE_ARRAY_MEMBER
7517 If the C compiler supports flexible array members, define
7518 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7519 That way, a declaration like this:
7521 @example
7522 struct s
7523   @{
7524     size_t n_vals;
7525     double val[FLEXIBLE_ARRAY_MEMBER];
7526   @};
7527 @end example
7529 @noindent
7530 will let applications use the ``struct hack'' even with compilers that
7531 do not support flexible array members.  To allocate and use such an
7532 object, you can use code like this:
7534 @example
7535 size_t i;
7536 size_t n = compute_value_count ();
7537 struct s *p =
7538    malloc (offsetof (struct s, val)
7539            + n * sizeof (double));
7540 p->n_vals = n;
7541 for (i = 0; i < n; i++)
7542   p->val[i] = compute_value (i);
7543 @end example
7544 @end defmac
7546 @defmac AC_C_VARARRAYS
7547 @acindex{C_VARARRAYS}
7548 @cvindex __STDC_NO_VLA__
7549 @cvindex HAVE_C_VARARRAYS
7550 If the C compiler does not support variable-length arrays, define the
7551 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined.  A
7552 variable-length array is an array of automatic storage duration whose
7553 length is determined at run time, when the array is declared.  For
7554 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7555 if the C compiler supports variable-length arrays, but this usage is
7556 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7557 @end defmac
7559 @defmac AC_C_TYPEOF
7560 @acindex{C_TYPEOF}
7561 @cvindex HAVE_TYPEOF
7562 @cvindex typeof
7563 If the C compiler supports GNU C's @code{typeof} syntax either
7564 directly or
7565 through a different spelling of the keyword (e.g., @code{__typeof__}),
7566 define @code{HAVE_TYPEOF}.  If the support is available only through a
7567 different spelling, define @code{typeof} to that spelling.
7568 @end defmac
7570 @defmac AC_C_PROTOTYPES
7571 @acindex{C_PROTOTYPES}
7572 @cvindex PROTOTYPES
7573 @cvindex __PROTOTYPES
7574 @cvindex PARAMS
7575 If function prototypes are understood by the compiler (as determined by
7576 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7577 Defining @code{__PROTOTYPES} is for the benefit of
7578 header files that cannot use macros that infringe on user name space.
7580 This macro is obsolescent, as current C compilers support prototypes.
7581 New programs need not use this macro.
7582 @end defmac
7584 @anchor{AC_PROG_GCC_TRADITIONAL}
7585 @defmac AC_PROG_GCC_TRADITIONAL
7586 @acindex{PROG_GCC_TRADITIONAL}
7587 @ovindex CC
7588 Add @option{-traditional} to output variable @code{CC} if using a
7589 GNU C compiler and @code{ioctl} does not work properly without
7590 @option{-traditional}.  That usually happens when the fixed header files
7591 have not been installed on an old system.
7593 This macro is obsolescent, since current versions of the GNU C
7594 compiler fix the header files automatically when installed.
7595 @end defmac
7598 @node C++ Compiler
7599 @subsection C++ Compiler Characteristics
7602 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7603 @acindex{PROG_CXX}
7604 @evindex CXX
7605 @evindex CXXFLAGS
7606 @ovindex CXX
7607 @ovindex CXXFLAGS
7608 Determine a C++ compiler to use.  Check whether the environment variable
7609 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7610 variable @code{CXX} to its value.
7612 Otherwise, if the macro is invoked without an argument, then search for
7613 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7614 then other names).  If none of those checks succeed, then as a last
7615 resort set @code{CXX} to @code{g++}.
7617 This macro may, however, be invoked with an optional first argument
7618 which, if specified, must be a blank-separated list of C++ compilers to
7619 search for.  This just gives the user an opportunity to specify an
7620 alternative search list for the C++ compiler.  For example, if you
7621 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7622 like this:
7624 @example
7625 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7626 @end example
7628 If necessary, add an option to output variable @code{CXX} to enable
7629 support for ISO Standard C++ features with extensions.  Prefer the
7630 newest C++ standard that is supported.  Currently the newest standard is
7631 ISO C++11, with ISO C++98 being the previous standard.  After calling
7632 this macro you can check whether the C++ compiler has been set to accept
7633 Standard C++; if not, the shell variable @code{ac_cv_prog_cxx_stdcxx} is
7634 set to @samp{no}.  If the C++ compiler will not accept C++11, the shell
7635 variable @code{ac_cv_prog_cxx_cxx11} is set to @samp{no}, and if it will
7636 not accept C++98, the shell variable @code{ac_cv_prog_cxx_cxx98} is set
7637 to @samp{no}.
7639 When attempting to add compiler options, prefer extended functionality
7640 to strict conformance: the goal is to enable whatever standard features
7641 that are available, not to check for full conformance to the standard or
7642 to prohibit incompatible extensions.  Test for C++11 support by checking
7643 for the language features @code{auto}, @code{constexpr},
7644 @code{decltype}, @code{default}ed and @code{delete}ed constructors,
7645 delegate constructors, @code{final}, initializer lists, lambda
7646 functions, @code{nullptr}, @code{override}, range-based for loops,
7647 template brackets without spaces and unicode literals, and library
7648 features @code{std::array}, @code{std::shared_ptr},
7649 @code{std::weak_ptr}, @code{std::regex} and @code{std::tuple}.  Test for
7650 C++98 support using basic features of the @code{std} namespace including
7651 @code{std::string}, containers (@code{std::list}, @code{std::map},
7652 @code{std::set}, @code{std::vector}), streams (fstreams, iostreams,
7653 stringstreams, iomanip), @code{std::pair}, exceptions (@code{try},
7654 @code{catch} and @code{std::runtime_error}) and algorithms.  Tests for
7655 more recent standards include all the tests for older standards.
7657 If using the GNU C++ compiler, set shell variable @code{GXX} to
7658 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7659 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7660 systems where G++ does not accept @option{-g}), or @option{-g} for other
7661 compilers.  If your package does not like this default, then it is
7662 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7663 and before @code{AC_PROG_CXX} to select an empty default instead.
7664 @end defmac
7666 @defmac AC_PROG_CXXCPP
7667 @acindex{PROG_CXXCPP}
7668 @evindex CXXCPP
7669 @ovindex CXXCPP
7670 Set output variable @code{CXXCPP} to a command that runs the C++
7671 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7672 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7673 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7675 Some preprocessors don't indicate missing include files by the error
7676 status.  For such preprocessors an internal variable is set that causes
7677 other macros to check the standard error from the preprocessor and
7678 consider the test failed if any warnings have been reported.  However,
7679 it is not known whether such broken preprocessors exist for C++.
7680 @end defmac
7682 @defmac AC_PROG_CXX_C_O
7683 @acindex{PROG_CXX_C_O}
7684 @cvindex CXX_NO_MINUS_C_MINUS_O
7685 Test whether the C++ compiler accepts the options @option{-c} and
7686 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7687 if it does not.
7688 @end defmac
7691 @node Objective C Compiler
7692 @subsection Objective C Compiler Characteristics
7695 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7696 @acindex{PROG_OBJC}
7697 @evindex OBJC
7698 @evindex OBJCFLAGS
7699 @ovindex OBJC
7700 @ovindex OBJCFLAGS
7701 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7702 set in the environment, check for Objective C compilers.  Set output
7703 variable @code{OBJC} to the name of the compiler found.
7705 This macro may, however, be invoked with an optional first argument
7706 which, if specified, must be a blank-separated list of Objective C compilers to
7707 search for.  This just gives the user an opportunity to specify an
7708 alternative search list for the Objective C compiler.  For example, if you
7709 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7710 like this:
7712 @example
7713 AC_PROG_OBJC([gcc objcc objc])
7714 @end example
7716 If using a compiler that supports GNU Objective C, set shell variable
7717 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7718 already set, set it to @option{-g -O2} for a GNU Objective C
7719 compiler (@option{-O2} on systems where the compiler does not accept
7720 @option{-g}), or @option{-g} for other compilers.
7721 @end defmac
7723 @defmac AC_PROG_OBJCPP
7724 @acindex{PROG_OBJCPP}
7725 @evindex OBJCPP
7726 @ovindex OBJCPP
7727 Set output variable @code{OBJCPP} to a command that runs the Objective C
7728 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7729 @end defmac
7732 @node Objective C++ Compiler
7733 @subsection Objective C++ Compiler Characteristics
7736 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7737 @acindex{PROG_OBJCXX}
7738 @evindex OBJCXX
7739 @evindex OBJCXXFLAGS
7740 @ovindex OBJCXX
7741 @ovindex OBJCXXFLAGS
7742 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7743 set in the environment, check for Objective C++ compilers.  Set output
7744 variable @code{OBJCXX} to the name of the compiler found.
7746 This macro may, however, be invoked with an optional first argument
7747 which, if specified, must be a blank-separated list of Objective C++ compilers
7748 to search for.  This just gives the user an opportunity to specify an
7749 alternative search list for the Objective C++ compiler.  For example, if you
7750 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7751 like this:
7753 @example
7754 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7755 @end example
7757 If using a compiler that supports GNU Objective C++, set shell variable
7758 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7759 already set, set it to @option{-g -O2} for a GNU Objective C++
7760 compiler (@option{-O2} on systems where the compiler does not accept
7761 @option{-g}), or @option{-g} for other compilers.
7762 @end defmac
7764 @defmac AC_PROG_OBJCXXCPP
7765 @acindex{PROG_OBJCXXCPP}
7766 @evindex OBJCXXCPP
7767 @ovindex OBJCXXCPP
7768 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7769 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7770 @end defmac
7773 @node Erlang Compiler and Interpreter
7774 @subsection Erlang Compiler and Interpreter Characteristics
7775 @cindex Erlang
7777 Autoconf defines the following macros for determining paths to the essential
7778 Erlang/OTP programs:
7780 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7781 @acindex{ERLANG_PATH_ERLC}
7782 @evindex ERLC
7783 @evindex ERLCFLAGS
7784 @ovindex ERLC
7785 @ovindex ERLCFLAGS
7786 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7787 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7788 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7789 is not set in the environment, set it to an empty value.
7791 The two optional arguments have the same meaning as the two last arguments of
7792 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7793 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7794 directory:
7796 @example
7797 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7798 @end example
7799 @end defmac
7801 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7802 @acindex{ERLANG_NEED_ERLC}
7803 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7804 error message and exits the @command{configure} script if the @command{erlc}
7805 program is not found.
7806 @end defmac
7808 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7809 @acindex{ERLANG_PATH_ERL}
7810 @evindex ERL
7811 @ovindex ERL
7812 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7813 set in the
7814 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7815 complete path of the interpreter command found.
7817 The two optional arguments have the same meaning as the two last arguments of
7818 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7819 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7820 directory:
7822 @example
7823 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7824 @end example
7825 @end defmac
7827 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7828 @acindex{ERLANG_NEED_ERL}
7829 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7830 error message and exits the @command{configure} script if the @command{erl}
7831 program is not found.
7832 @end defmac
7835 @node Fortran Compiler
7836 @subsection Fortran Compiler Characteristics
7837 @cindex Fortran
7838 @cindex F77
7840 The Autoconf Fortran support is divided into two categories: legacy
7841 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7842 The former are intended for traditional Fortran 77 code, and have output
7843 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7844 are for newer programs that can (or must) compile under the newer
7845 Fortran standards, and have output variables like @code{FC},
7846 @code{FCFLAGS}, and @code{FCLIBS}.
7848 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7849 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7850 @code{FC} and @code{F77} macros behave almost identically, and so they
7851 are documented together in this section.
7854 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7855 @acindex{PROG_F77}
7856 @evindex F77
7857 @evindex FFLAGS
7858 @ovindex F77
7859 @ovindex FFLAGS
7860 @caindex f77_compiler_gnu
7861 @caindex prog_f77_g
7862 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7863 set in the environment, then check for @code{g77} and @code{f77}, and
7864 then some other names.  Set the output variable @code{F77} to the name
7865 of the compiler found.
7867 This macro may, however, be invoked with an optional first argument
7868 which, if specified, must be a blank-separated list of Fortran 77
7869 compilers to search for.  This just gives the user an opportunity to
7870 specify an alternative search list for the Fortran 77 compiler.  For
7871 example, if you didn't like the default order, then you could invoke
7872 @code{AC_PROG_F77} like this:
7874 @example
7875 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7876 @end example
7878 If using a compiler that supports GNU Fortran 77,
7879 set the shell variable @code{G77} to @samp{yes}.
7880 If the output variable @code{FFLAGS} was not already set in the
7881 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
7882 where the GNU Fortran 77 compiler does not accept @option{-g}), or
7883 @option{-g} for other compilers.
7885 The result of the GNU test is cached in the
7886 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7887 @code{ac_cv_prog_f77_g} variable.
7888 @end defmac
7890 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7891 @acindex{PROG_FC}
7892 @evindex FC
7893 @evindex FCFLAGS
7894 @ovindex FC
7895 @ovindex FCFLAGS
7896 @caindex fc_compiler_gnu
7897 @caindex prog_fc_g
7898 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7899 the environment, then @code{dialect} is a hint to indicate what Fortran
7900 dialect to search for; the default is to search for the newest available
7901 dialect.  Set the output variable @code{FC} to the name of the compiler
7902 found.
7904 By default, newer dialects are preferred over older dialects, but if
7905 @code{dialect} is specified then older dialects are preferred starting
7906 with the specified dialect.  @code{dialect} can currently be one of
7907 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7908 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7909 and no attempt is made to guarantee that a particular language standard
7910 is actually supported.  Thus, it is preferable that you avoid the
7911 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7912 the latest Fortran standard.
7914 This macro may, alternatively, be invoked with an optional first argument
7915 which, if specified, must be a blank-separated list of Fortran
7916 compilers to search for, just as in @code{AC_PROG_F77}.
7918 If using a compiler that supports GNU Fortran,
7919 set the shell variable @code{GFC} to @samp{yes}.
7920 If the output variable @code{FCFLAGS} was not already set in the
7921 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
7922 @option{-O2} where the compiler does not accept @option{-g}), or
7923 @option{-g} for other compilers.
7925 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7926 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7927 variable.
7928 @end defmac
7930 @defmac AC_PROG_F77_C_O
7931 @defmacx AC_PROG_FC_C_O
7932 @acindex{PROG_F77_C_O}
7933 @acindex{PROG_FC_C_O}
7934 @cvindex F77_NO_MINUS_C_MINUS_O
7935 @cvindex FC_NO_MINUS_C_MINUS_O
7936 @caindex prog_f77_c_o
7937 @caindex prog_fc_c_o
7938 Test whether the Fortran compiler accepts the options @option{-c} and
7939 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7940 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7942 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7943 @code{ac_cv_prog_fc_c_o} variable, respectively.
7944 @end defmac
7946 The following macros check for Fortran compiler characteristics.
7947 To check for characteristics not listed here, use
7948 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7949 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7950 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7951 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7954 @defmac AC_F77_LIBRARY_LDFLAGS
7955 @defmacx AC_FC_LIBRARY_LDFLAGS
7956 @acindex{F77_LIBRARY_LDFLAGS}
7957 @ovindex FLIBS
7958 @acindex{FC_LIBRARY_LDFLAGS}
7959 @ovindex FCLIBS
7960 @caindex prog_f77_v
7961 @caindex prog_fc_v
7962 @caindex f77_libs
7963 @caindex fc_libs
7964 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7965 @dfn{Fortran intrinsic and runtime libraries} that are required to
7966 successfully link a Fortran program or shared library.  The output
7967 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7968 should be included after @code{LIBS} when linking).
7970 This macro is intended to be used in those situations when it is
7971 necessary to mix, e.g., C++ and Fortran source code in a single
7972 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7973 automake, GNU Automake}).
7975 For example, if object files from a C++ and Fortran compiler must be
7976 linked together, then the C++ compiler/linker must be used for linking
7977 (since special C++-ish things need to happen at link time like calling
7978 global constructors, instantiating templates, enabling exception
7979 support, etc.).
7981 However, the Fortran intrinsic and runtime libraries must be linked in
7982 as well, but the C++ compiler/linker doesn't know by default how to add
7983 these Fortran 77 libraries.  Hence, this macro was created to determine
7984 these Fortran libraries.
7986 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7987 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7988 link C/C++ with Fortran; see below.  Further, it is highly recommended
7989 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7990 because the complex defines that the function wrapper macros create
7991 may not work with C/C++ compiler drivers.
7993 These macros internally compute the flag needed to verbose linking
7994 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
7995 variables, respectively.  The computed linker flags are cached in
7996 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
7997 @end defmac
7999 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
8000   @dvar{action-if-not-found, AC_MSG_FAILURE})
8001 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
8002   @dvar{action-if-not-found, AC_MSG_FAILURE})
8003 @acindex{F77_DUMMY_MAIN}
8004 @cvindex F77_DUMMY_MAIN
8005 @acindex{FC_DUMMY_MAIN}
8006 @cvindex FC_DUMMY_MAIN
8007 @caindex f77_dummy_main
8008 @caindex fc_dummy_main
8009 With many compilers, the Fortran libraries detected by
8010 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
8011 their own @code{main} entry function that initializes things like
8012 Fortran I/O, and which then calls a user-provided entry function named
8013 (say) @code{MAIN__} to run the user's program.  The
8014 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
8015 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
8016 this interaction.
8018 When using Fortran for purely numerical functions (no I/O, etc.)@: often
8019 one prefers to provide one's own @code{main} and skip the Fortran
8020 library initializations.  In this case, however, one may still need to
8021 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8022 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8023 detects whether any such routine is @emph{required} for linking, and
8024 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8025 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8026 was found, and @code{none} when no such dummy main is needed.
8028 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8029 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8030 @emph{if} it is required.  @var{action-if-not-found} defaults to
8031 exiting with an error.
8033 In order to link with Fortran routines, the user's C/C++ program should
8034 then include the following code to define the dummy main if it is
8035 needed:
8037 @example
8038 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8039 #ifdef F77_DUMMY_MAIN
8040 #  ifdef __cplusplus
8041      extern "C"
8042 #  endif
8043    int F77_DUMMY_MAIN () @{ return 1; @}
8044 #endif
8045 @end example
8047 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8049 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8050 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8051 explicitly unless one wants to change the default actions.
8053 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8054 @code{ac_cv_fc_dummy_main} variable, respectively.
8055 @end defmac
8057 @defmac AC_F77_MAIN
8058 @defmacx AC_FC_MAIN
8059 @acindex{F77_MAIN}
8060 @cvindex F77_MAIN
8061 @acindex{FC_MAIN}
8062 @cvindex FC_MAIN
8063 @caindex f77_main
8064 @caindex fc_main
8065 As discussed above, many Fortran libraries allow you to provide an entry
8066 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8067 is then called by a @code{main} function in the Fortran libraries that
8068 initializes things like Fortran I/O@.  The
8069 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8070 @emph{possible} to utilize such an alternate main function, and defines
8071 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8072 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8073 simply defined to @code{main}.)
8075 Thus, when calling Fortran routines from C that perform things like I/O,
8076 one should use this macro and declare the "main" function like so:
8078 @example
8079 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8080 #ifdef __cplusplus
8081   extern "C"
8082 #endif
8083 int F77_MAIN (int argc, char *argv[]);
8084 @end example
8086 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8088 The result of this macro is cached in the @code{ac_cv_f77_main} or
8089 @code{ac_cv_fc_main} variable, respectively.
8090 @end defmac
8092 @defmac AC_F77_WRAPPERS
8093 @defmacx AC_FC_WRAPPERS
8094 @acindex{F77_WRAPPERS}
8095 @cvindex F77_FUNC
8096 @cvindex F77_FUNC_
8097 @acindex{FC_WRAPPERS}
8098 @cvindex FC_FUNC
8099 @cvindex FC_FUNC_
8100 @caindex f77_mangling
8101 @caindex fc_mangling
8102 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8103 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8104 mangle the names of C/C++ identifiers, and identifiers with underscores,
8105 respectively, so that they match the name-mangling scheme used by the
8106 Fortran compiler.
8108 Fortran is case-insensitive, and in order to achieve this the Fortran
8109 compiler converts all identifiers into a canonical case and format.  To
8110 call a Fortran subroutine from C or to write a C function that is
8111 callable from Fortran, the C program must explicitly use identifiers in
8112 the format expected by the Fortran compiler.  In order to do this, one
8113 simply wraps all C identifiers in one of the macros provided by
8114 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8115 you have the following Fortran 77 subroutine:
8117 @example
8118 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8119       subroutine foobar (x, y)
8120       double precision x, y
8121       y = 3.14159 * x
8122       return
8123       end
8124 @end example
8126 You would then declare its prototype in C or C++ as:
8128 @example
8129 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8130 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8131 #ifdef __cplusplus
8132 extern "C"  /* prevent C++ name mangling */
8133 #endif
8134 void FOOBAR_F77 (double *x, double *y);
8135 @end example
8137 Note that we pass both the lowercase and uppercase versions of the
8138 function name to @code{F77_FUNC} so that it can select the right one.
8139 Note also that all parameters to Fortran 77 routines are passed as
8140 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8141 Automake}).
8143 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8145 Although Autoconf tries to be intelligent about detecting the
8146 name-mangling scheme of the Fortran compiler, there may be Fortran
8147 compilers that it doesn't support yet.  In this case, the above code
8148 generates a compile-time error, but some other behavior
8149 (e.g., disabling Fortran-related features) can be induced by checking
8150 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8152 Now, to call that routine from a C program, we would do something like:
8154 @example
8155 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8157     double x = 2.7183, y;
8158     FOOBAR_F77 (&x, &y);
8160 @end example
8162 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8163 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8164 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8165 because some Fortran compilers mangle names differently if they contain
8166 an underscore.
8168 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8169 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8170 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8171 @end defmac
8173 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8174 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8175 @acindex{F77_FUNC}
8176 @acindex{FC_FUNC}
8177 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8178 hold the mangled version @var{name} according to the rules of the
8179 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8180 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8181 supplied, the shell variable is simply @var{name}.  The purpose of
8182 this macro is to give the caller a way to access the name-mangling
8183 information other than through the C preprocessor as above, for example,
8184 to call Fortran routines from some language other than C/C++.
8185 @end defmac
8187 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8188   @dvar{action-if-failure, AC_MSG_FAILURE})
8189 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8190   @dvar{action-if-failure, AC_MSG_FAILURE})
8191 @acindex{FC_SRCEXT}
8192 @acindex{FC_PP_SRCEXT}
8193 @caindex fc_srcext_@var{ext}
8194 @caindex fc_pp_srcext_@var{ext}
8195 By default, the @code{FC} macros perform their tests using a @file{.f}
8196 extension for source-code files.  Some compilers, however, only enable
8197 newer language features for appropriately named files, e.g., Fortran 90
8198 features only for @file{.f90} files, or preprocessing only with
8199 @file{.F} files or maybe other upper-case extensions.  On the other
8200 hand, some other compilers expect all source files to end in @file{.f}
8201 and require special flags to support other file name extensions.  The
8202 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8203 issues.
8205 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8206 accept files ending with the extension @file{.@var{ext}} (i.e.,
8207 @var{ext} does @emph{not} contain the dot).  If any special compiler
8208 flags are needed for this, it stores them in the output variable
8209 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8210 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8211 @code{AC_FC_PP_SRCEXT} is called another time).
8213 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8214 @file{.f90} extension in future tests, and it would set the
8215 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8216 to compile such files.
8218 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8219 compiler to preprocess and compile files with the extension
8220 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8221 preprocessing are provided, the former is preferred, as the latter may
8222 treat continuation lines, @code{//} tokens, and white space differently
8223 from what some Fortran dialects expect.  Conversely, if you do not want
8224 files to be preprocessed, use only lower-case characters in the file
8225 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8226 are stored in the @code{FCFLAGS_@var{ext}} variable.
8228 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8229 into @code{FCFLAGS}, for two reasons based on the limitations of some
8230 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8231 time, so files with different extensions must be compiled separately.
8232 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8233 the source-code file name when compiling.  So, continuing the example
8234 above, you might compile a @file{foo.f90} file in your makefile with the
8235 command:
8237 @example
8238 foo.o: foo.f90
8239        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8240 @end example
8242 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8243 files with the @var{ext} extension, it calls @var{action-if-success}
8244 (defaults to nothing).  If it fails, and cannot find a way to make the
8245 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8246 (defaults to exiting with an error message).
8248 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8249 results in @code{ac_cv_fc_srcext_@var{ext}} and
8250 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8251 @end defmac
8253 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8254   @dvar{action-if-failure, AC_MSG_FAILURE})
8255 @acindex{FC_PP_DEFINE}
8256 @caindex fc_pp_define
8258 Find a flag to specify defines for preprocessed Fortran.  Not all
8259 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8260 the result and call @var{action-if-success} (defaults to nothing) if
8261 successful, and @var{action-if-failure} (defaults to failing with an
8262 error message) if not.
8264 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8265 preprocess a @file{conftest.F} file, but restores a previously used
8266 Fortran source file extension afterwards again.
8268 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8269 variable.
8270 @end defmac
8272 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8273   @dvar{action-if-failure, AC_MSG_FAILURE})
8274 @acindex{FC_FREEFORM}
8275 @caindex fc_freeform
8277 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8278 source code (as opposed to the older fixed-format style from Fortran
8279 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8281 This macro is most important if you are using the default @file{.f}
8282 extension, since many compilers interpret this extension as indicating
8283 fixed-format source unless an additional flag is supplied.  If you
8284 specify a different extension with @code{AC_FC_SRCEXT}, such as
8285 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8286 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8287 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8288 the compiler assume Fortran 77 by default, however.
8290 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8291 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8292 calls @var{action-if-failure} (defaults to exiting with an error
8293 message).
8295 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8296 the @code{ac_cv_fc_freeform} variable.
8297 @end defmac
8299 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8300   @dvar{action-if-failure, AC_MSG_FAILURE})
8301 @acindex{FC_FIXEDFORM}
8302 @caindex fc_fixedform
8304 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8305 fixed-format source code (as opposed to free-format style).  If
8306 necessary, it may add some additional flags to @code{FCFLAGS}.
8308 This macro is needed for some compilers alias names like @command{xlf95}
8309 which assume free-form source code by default, and in case you want to
8310 use fixed-form source with an extension like @file{.f90} which many
8311 compilers interpret as free-form by default.  If you specify a different
8312 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8313 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8314 @code{FCFLAGS}.
8316 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8317 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8318 calls @var{action-if-failure} (defaults to exiting with an error
8319 message).
8321 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8322 the @code{ac_cv_fc_fixedform} variable.
8323 @end defmac
8325 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8326   @dvar{action-if-failure, AC_MSG_FAILURE})
8327 @acindex{FC_LINE_LENGTH}
8328 @caindex fc_line_length
8330 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8331 code lines.  The @var{length} argument may be given as 80, 132, or
8332 unlimited, and defaults to 132.  Note that line lengths above 254
8333 columns are not portable, and some compilers do not accept more than 132
8334 columns at least for fixed format source.  If necessary, it may add some
8335 additional flags to @code{FCFLAGS}.
8337 If @code{AC_FC_LINE_LENGTH} succeeds in compiling fixed-form source, it
8338 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8339 calls @var{action-if-failure} (defaults to exiting with an error
8340 message).
8342 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8343 the @code{ac_cv_fc_line_length} variable.
8344 @end defmac
8346 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8347   @dvar{action-if-failure, AC_MSG_FAILURE})
8348 @acindex{FC_CHECK_BOUNDS}
8349 @caindex fc_check_bounds
8351 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8352 in the Fortran compiler.  If successful, the @var{action-if-success}
8353 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8354 @var{action-if-failure} is called, which defaults to failing with an error
8355 message.  The macro currently requires Fortran 90 or a newer dialect.
8357 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8358 variable.
8359 @end defmac
8361 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8362   @dvar{action-if-failure, AC_MSG_FAILURE})
8363 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8364   @dvar{action-if-failure, AC_MSG_FAILURE})
8365 @acindex{F77_IMPLICIT_NONE}
8366 @acindex{FC_IMPLICIT_NONE}
8367 @caindex f77_implicit_none
8368 @caindex fc_implicit_none
8370 Try to disallow implicit declarations in the Fortran compiler.  If
8371 successful, @var{action-if-success} is called and any needed flags
8372 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8373 @var{action-if-failure} is called, which defaults to failing with an error
8374 message.
8376 The result of these macros are cached in the
8377 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8378 variables, respectively.
8379 @end defmac
8381 @defmac AC_FC_MODULE_EXTENSION
8382 @acindex{FC_MODULE_EXTENSION}
8383 @caindex fc_module_ext
8384 @ovindex FC_MODEXT
8386 Find the Fortran 90 module file name extension.  Most Fortran 90
8387 compilers store module information in files separate from the object
8388 files.  The module files are usually named after the name of the module
8389 rather than the source file name, with characters possibly turned to
8390 upper case, plus an extension, often @file{.mod}.
8392 Not all compilers use module files at all, or by default.  The Cray
8393 Fortran compiler requires @option{-e m} in order to store and search
8394 module information in @file{.mod} files rather than in object files.
8395 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8396 indicate how module information is stored.
8398 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8399 without the leading dot, and stores that in the @code{FC_MODEXT}
8400 variable.  If the compiler does not produce module files, or the
8401 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8402 the result of this macro may be used in cleanup @command{make} rules as
8403 follows:
8405 @example
8406 clean-modules:
8407         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8408 @end example
8410 The extension, or @samp{unknown}, is cached in the
8411 @code{ac_cv_fc_module_ext} variable.
8412 @end defmac
8414 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8415   @dvar{action-if-failure, AC_MSG_FAILURE})
8416 @acindex{FC_MODULE_FLAG}
8417 @caindex fc_module_flag
8418 @ovindex FC_MODINC
8419 @ovindex ac_empty
8421 Find the compiler flag to include Fortran 90 module information from
8422 another directory, and store that in the @code{FC_MODINC} variable.
8423 Call @var{action-if-success} (defaults to nothing) if successful, and
8424 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8425 to exiting with an error message) if not.
8427 Most Fortran 90 compilers provide a way to specify module directories.
8428 Some have separate flags for the directory to write module files to,
8429 and directories to search them in, whereas others only allow writing to
8430 the current directory or to the first directory specified in the include
8431 path.  Further, with some compilers, the module search path and the
8432 preprocessor search path can only be modified with the same flag.  Thus,
8433 for portability, write module files to the current directory only and
8434 list that as first directory in the search path.
8436 There may be no whitespace between @code{FC_MODINC} and the following
8437 directory name, but @code{FC_MODINC} may contain trailing white space.
8438 For example, if you use Automake and would like to search @file{../lib}
8439 for module files, you can use the following:
8441 @example
8442 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8443 @end example
8445 Inside @command{configure} tests, you can use:
8447 @example
8448 if test -n "$FC_MODINC"; then
8449   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8451 @end example
8453 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8454 The substituted value of @code{FC_MODINC} may refer to the
8455 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8456 the significant trailing whitespace in a @file{Makefile}.
8457 @end defmac
8459 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8460   @dvar{action-if-failure, AC_MSG_FAILURE})
8461 @acindex{FC_MODULE_OUTPUT_FLAG}
8462 @caindex fc_module_output_flag
8463 @ovindex FC_MODOUT
8465 Find the compiler flag to write Fortran 90 module information to
8466 another directory, and store that in the @code{FC_MODOUT} variable.
8467 Call @var{action-if-success} (defaults to nothing) if successful, and
8468 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8469 to exiting with an error message) if not.
8471 Not all Fortran 90 compilers write module files, and of those that do,
8472 not all allow writing to a directory other than the current one, nor
8473 do all have separate flags for writing and reading; see the description
8474 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8475 another directory, for maximum portability use @code{FC_MODOUT} before
8476 any @code{FC_MODINC} and include both the current directory and the one
8477 you write to in the search path:
8479 @example
8480 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8481 @end example
8483 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8484 The substituted value of @code{FC_MODOUT} may refer to the
8485 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8486 the significant trailing whitespace in a @file{Makefile}.
8487 @end defmac
8490 @node Go Compiler
8491 @subsection Go Compiler Characteristics
8492 @cindex Go
8494 Autoconf provides basic support for the Go programming language when
8495 using the @code{gccgo} compiler (there is currently no support for the
8496 @code{6g} and @code{8g} compilers).
8498 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8499 Find the Go compiler to use.  Check whether the environment variable
8500 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8501 value.
8503 Otherwise, if the macro is invoked without an argument, then search for
8504 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8505 resort set @code{GOC} to @code{gccgo}.
8507 This macro may be invoked with an optional first argument which, if
8508 specified, must be a blank-separated list of Go compilers to search for.
8510 If output variable @code{GOFLAGS} was not already set, set it to
8511 @option{-g -O2}.  If your package does not like this default,
8512 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8513 @end defmac
8516 @node System Services
8517 @section System Services
8519 The following macros check for operating system services or capabilities.
8521 @anchor{AC_PATH_X}
8522 @defmac AC_PATH_X
8523 @acindex{PATH_X}
8524 @evindex XMKMF
8525 @cindex X Window System
8526 Try to locate the X Window System include files and libraries.  If the
8527 user gave the command line options @option{--x-includes=@var{dir}} and
8528 @option{--x-libraries=@var{dir}}, use those directories.
8530 If either or both were not given, get the missing values by running
8531 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8532 environment variable) on a trivial @file{Imakefile} and examining the
8533 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8534 disables this method.
8536 If this method fails to find the X Window System, @command{configure}
8537 looks for the files in several directories where they often reside.
8538 If either method is successful, set the shell variables
8539 @code{x_includes} and @code{x_libraries} to their locations, unless they
8540 are in directories the compiler searches by default.
8542 If both methods fail, or the user gave the command line option
8543 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8544 otherwise set it to the empty string.
8545 @end defmac
8547 @anchor{AC_PATH_XTRA}
8548 @defmac AC_PATH_XTRA
8549 @acindex{PATH_XTRA}
8550 @ovindex X_CFLAGS
8551 @ovindex X_LIBS
8552 @ovindex X_EXTRA_LIBS
8553 @ovindex X_PRE_LIBS
8554 @cvindex X_DISPLAY_MISSING
8555 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8556 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8557 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8558 available.
8560 This macro also checks for special libraries that some systems need in
8561 order to compile X programs.  It adds any that the system needs to
8562 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8563 libraries that need to be linked with before @option{-lX11}, and adds
8564 any found to the output variable @code{X_PRE_LIBS}.
8566 @c This is an incomplete kludge.  Make a real way to do it.
8567 @c If you need to check for other X functions or libraries yourself, then
8568 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8569 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8570 @end defmac
8572 @anchor{AC_SYS_INTERPRETER}
8573 @defmac AC_SYS_INTERPRETER
8574 @acindex{SYS_INTERPRETER}
8575 Check whether the system supports starting scripts with a line of the
8576 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8577 After running this macro, shell code in @file{configure.ac} can check
8578 the shell variable @code{interpval}; it is set to @samp{yes}
8579 if the system supports @samp{#!}, @samp{no} if not.
8580 @end defmac
8582 @defmac AC_SYS_LARGEFILE
8583 @acindex{SYS_LARGEFILE}
8584 @cvindex _FILE_OFFSET_BITS
8585 @cvindex _LARGE_FILES
8586 @ovindex CC
8587 @cindex Large file support
8588 @cindex LFS
8589 Arrange for 64-bit file offsets, known as
8590 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8591 large-file support}.  On some hosts, one must use special compiler
8592 options to build programs that can access large files.  Append any such
8593 options to the output variable @code{CC}.  Define
8594 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8596 Large-file support can be disabled by configuring with the
8597 @option{--disable-largefile} option.
8599 If you use this macro, check that your program works even when
8600 @code{off_t} is wider than @code{long int}, since this is common when
8601 large-file support is enabled.  For example, it is not correct to print
8602 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8603 (long int) X)}.  Also, when using this macro in concert with
8604 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8605 before any system header.
8607 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8608 replace their C counterparts @code{fseek} and @code{ftell} that do not
8609 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8610 prototypes available when using them and large-file support is
8611 enabled.
8612 @end defmac
8614 @anchor{AC_SYS_LONG_FILE_NAMES}
8615 @defmac AC_SYS_LONG_FILE_NAMES
8616 @acindex{SYS_LONG_FILE_NAMES}
8617 @cvindex HAVE_LONG_FILE_NAMES
8618 If the system supports file names longer than 14 characters, define
8619 @code{HAVE_LONG_FILE_NAMES}.
8620 @end defmac
8622 @defmac AC_SYS_POSIX_TERMIOS
8623 @acindex{SYS_POSIX_TERMIOS}
8624 @cindex Posix termios headers
8625 @cindex termios Posix headers
8626 @caindex sys_posix_termios
8627 Check to see if the Posix termios headers and functions are available on the
8628 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8629 @samp{yes}.  If not, set the variable to @samp{no}.
8630 @end defmac
8632 @node C and Posix Variants
8633 @section C and Posix Variants
8635 The following macro makes it possible to use C language and library
8636 extensions defined by the C standards committee, features of Posix that
8637 are extensions to C, and platform extensions not defined by Posix.
8639 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8640 @defmac AC_USE_SYSTEM_EXTENSIONS
8641 @acindex{USE_SYSTEM_EXTENSIONS}
8642 If possible, enable extensions to C or Posix on hosts that normally
8643 disable the extensions, typically due to standards-conformance namespace
8644 issues.  This should be called before any macros that run the C
8645 compiler.  Also, when using this macro in concert with
8646 @code{AC_CONFIG_HEADERS}, be sure that @file{config.h} is included
8647 before any system header.  The following preprocessor macros are defined
8648 where appropriate:
8650 @table @code
8651 @item _GNU_SOURCE
8652 @cvindex _GNU_SOURCE
8653 Enable extensions on GNU/Linux.
8654 @item _ALL_SOURCE
8655 @cvindex _ALL_SOURCE
8656 Enable extensions for AIX 3, and for Interix.
8657 @item _DARWIN_C_SOURCE
8658 @cvindex _DARWIN_C_SOURCE
8659 Enable extensions for macOS.
8660 @item _MINIX
8661 @cvindex _MINIX
8662 Identify Minix platform.  This particular preprocessor macro is
8663 obsolescent, and may be removed in a future release of Autoconf.
8664 @item _NETBSD_SOURCE
8665 @cvindex _NETBSD_SOURCE
8666 Enable NetBSD-related extensions for Minix.
8667 @item _POSIX_1_SOURCE
8668 @cvindex _POSIX_1_SOURCE
8669 Enable additional Posix functions for Minix.
8670 @item _POSIX_PTHREAD_SEMANTICS
8671 @cvindex _POSIX_PTHREAD_SEMANTICS
8672 Enable threading extensions on Solaris.
8673 @item _POSIX_SOURCE
8674 @cvindex _POSIX_SOURCE
8675 Enable Posix functions for Minix.
8676 @item _TANDEM_SOURCE
8677 @cvindex _TANDEM_SOURCE
8678 Enable extensions for the HP NonStop platform.
8679 @item _XOPEN_SOURCE
8680 @cvindex _XOPEN_SOURCE
8681 Enable X/Open extensions for HP-UX.
8682 @item __EXTENSIONS__
8683 @cvindex __EXTENSIONS__
8684 Enable general extensions on Solaris.
8685 @item __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8686 @cvindex __STDC_WANT_IEC_60559_ATTRIBS_EXT__
8687 Enable extensions specified by ISO/IEC TS 18661-5:2014.
8688 @item __STDC_WANT_IEC_60559_BFP_EXT__
8689 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8690 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8691 @item __STDC_WANT_IEC_60559_DFP_EXT__
8692 @cvindex __STDC_WANT_IEC_60559_DFP_EXT__
8693 Enable extensions specified by ISO/IEC TS 18661-2:2015.
8694 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8695 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8696 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8697 @item __STDC_WANT_IEC_60559_TYPES_EXT__
8698 @cvindex __STDC_WANT_IEC_60559_TYPES_EXT__
8699 Enable extensions specified by ISO/IEC TS 18661-3:2015.
8700 @item __STDC_WANT_LIB_EXT2__
8701 @cvindex __STDC_WANT_LIB_EXT2__
8702 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8703 @item __STDC_WANT_MATH_SPEC_FUNCS__
8704 @cvindex __STDC_WANT_MATH_SPEC_FUNCS__
8705 Enable extensions specified by ISO/IEC 24747:2009.
8706 @end table
8708 @cvindex __STDC_WANT_DEC_FP__
8709 The C preprocessor macro @code{__STDC_WANT_DEC_FP__} is not defined.
8710 ISO/IEC TR 24732:2009 was superseded by ISO/IEC TS 18661-2:2015.
8712 @cvindex __STDC_WANT_LIB_EXT1__
8713 The C preprocessor macro @code{__STDC_WANT_LIB_EXT1__} is not defined,
8714 as C11 Annex K is problematic.  See: O'Donell C, Sebor M.
8715 @uref{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8716 Experience With Annex K---Bounds Checking Interfaces}.
8718 The Autoconf macro @code{AC_USE_SYSTEM_EXTENSIONS} was introduced in
8719 Autoconf 2.60.
8720 @end defmac
8723 @node Erlang Libraries
8724 @section Erlang Libraries
8725 @cindex Erlang, Library, checking
8727 The following macros check for an installation of Erlang/OTP, and for the
8728 presence of certain Erlang libraries.  All those macros require the
8729 configuration of an Erlang interpreter and an Erlang compiler
8730 (@pxref{Erlang Compiler and Interpreter}).
8732 @defmac AC_ERLANG_SUBST_ERTS_VER
8733 @acindex{ERLANG_SUBST_ERTS_VER}
8734 @ovindex ERLANG_ERTS_VER
8735 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8736 Erlang runtime system (as returned by Erlang's
8737 @code{erlang:system_info(version)} function).  The result of this test
8738 is cached if caching is enabled when running @command{configure}.  The
8739 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8740 for features of specific ERTS versions, but to be used for substituting
8741 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8742 files), as shown below.
8743 @end defmac
8745 @defmac AC_ERLANG_SUBST_ROOT_DIR
8746 @acindex{ERLANG_SUBST_ROOT_DIR}
8747 @ovindex ERLANG_ROOT_DIR
8748 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8749 directory in which Erlang/OTP is installed (as returned by Erlang's
8750 @code{code:root_dir/0} function).  The result of this test is cached if
8751 caching is enabled when running @command{configure}.
8752 @end defmac
8754 @defmac AC_ERLANG_SUBST_LIB_DIR
8755 @acindex{ERLANG_SUBST_LIB_DIR}
8756 @ovindex ERLANG_LIB_DIR
8757 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8758 directory of Erlang/OTP (as returned by Erlang's
8759 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8760 Erlang/OTP library.  The result of this test is cached if caching is enabled
8761 when running @command{configure}.
8762 @end defmac
8764 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8765   @ovar{action-if-not-found})
8766 @acindex{ERLANG_CHECK_LIB}
8767 @ovindex ERLANG_LIB_DIR_@var{library}
8768 @ovindex ERLANG_LIB_VER_@var{library}
8769 Test whether the Erlang/OTP library @var{library} is installed by
8770 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8771 test is cached if caching is enabled when running @command{configure}.
8772 @var{action-if-found} is a list of shell commands to run if the library
8773 is installed; @var{action-if-not-found} is a list of shell commands to
8774 run if it is not.  Additionally, if the library is installed, the output
8775 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8776 library installation directory, and the output variable
8777 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8778 part of the subdirectory name, if it is in the standard form
8779 (@code{@var{library}-@var{version}}).  If the directory name does not
8780 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8781 empty string.  If the library is not installed,
8782 @samp{ERLANG_LIB_DIR_@var{library}} and
8783 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8784 example, to check if library @code{stdlib} is installed:
8786 @example
8787 AC_ERLANG_CHECK_LIB([stdlib],
8788   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8789    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8790   [AC_MSG_ERROR([stdlib was not found!])])
8791 @end example
8793 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8794 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8795 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8796 testing for features of specific versions of libraries or of the Erlang
8797 runtime system.  Those variables are intended to be substituted in
8798 Erlang release resource files (@code{.rel} files).  For instance, to
8799 generate a @file{example.rel} file for an application depending on the
8800 @code{stdlib} library, @file{configure.ac} could contain:
8802 @example
8803 AC_ERLANG_SUBST_ERTS_VER
8804 AC_ERLANG_CHECK_LIB([stdlib],
8805   [],
8806   [AC_MSG_ERROR([stdlib was not found!])])
8807 AC_CONFIG_FILES([example.rel])
8808 @end example
8810 @noindent
8811 The @file{example.rel.in} file used to generate @file{example.rel}
8812 should contain:
8814 @example
8815 @{release,
8816     @{"@@PACKAGE@@", "@@VERSION@@"@},
8817     @{erts, "@@ERLANG_ERTS_VER@@"@},
8818     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8819      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8820 @end example
8821 @end defmac
8823 In addition to the above macros, which test installed Erlang libraries, the
8824 following macros determine the paths to the directories into which newly built
8825 Erlang libraries are to be installed:
8827 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8828 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8829 @ovindex ERLANG_INSTALL_LIB_DIR
8831 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8832 which every built Erlang library should be installed in a separate
8833 subdirectory.
8834 If this variable is not set in the environment when @command{configure} runs,
8835 its default value is @code{$@{libdir@}/erlang/lib}.
8836 @end defmac
8838 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8839 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8840 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8842 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8843 directory into which the built Erlang library @var{library} version
8844 @var{version} should be installed.  If this variable is not set in the
8845 environment when @command{configure} runs, its default value is
8846 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8847 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8848 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8849 @end defmac
8855 @c ========================================================= Writing Tests
8857 @node Writing Tests
8858 @chapter Writing Tests
8860 If the existing feature tests don't do something you need, you have to
8861 write new ones.  These macros are the building blocks.  They provide
8862 ways for other macros to check whether various kinds of features are
8863 available and report the results.
8865 This chapter contains some suggestions and some of the reasons why the
8866 existing tests are written the way they are.  You can also learn a lot
8867 about how to write Autoconf tests by looking at the existing ones.  If
8868 something goes wrong in one or more of the Autoconf tests, this
8869 information can help you understand the assumptions behind them, which
8870 might help you figure out how to best solve the problem.
8872 These macros check the output of the compiler system of the current
8873 language (@pxref{Language Choice}).  They do not cache the results of
8874 their tests for future use (@pxref{Caching Results}), because they don't
8875 know enough about the information they are checking for to generate a
8876 cache variable name.  They also do not print any messages, for the same
8877 reason.  The checks for particular kinds of features call these macros
8878 and do cache their results and print messages about what they're
8879 checking for.
8881 When you write a feature test that could be applicable to more than one
8882 software package, the best thing to do is encapsulate it in a new macro.
8883 @xref{Writing Autoconf Macros}, for how to do that.
8885 @menu
8886 * Language Choice::             Selecting which language to use for testing
8887 * Writing Test Programs::       Forging source files for compilers
8888 * Running the Preprocessor::    Detecting preprocessor symbols
8889 * Running the Compiler::        Detecting language or header features
8890 * Running the Linker::          Detecting library features
8891 * Runtime::                     Testing for runtime features
8892 * Systemology::                 A zoology of operating systems
8893 * Multiple Cases::              Tests for several possible values
8894 @end menu
8896 @node Language Choice
8897 @section Language Choice
8898 @cindex Language
8900 Autoconf-generated @command{configure} scripts check for the C compiler and
8901 its features by default.  Packages that use other programming languages
8902 (maybe more than one, e.g., C and C++) need to test features of the
8903 compilers for the respective languages.  The following macros determine
8904 which programming language is used in the subsequent tests in
8905 @file{configure.ac}.
8907 @anchor{AC_LANG}
8908 @defmac AC_LANG (@var{language})
8909 @acindex{LANG}
8910 Do compilation tests using the compiler, preprocessor, and file
8911 extensions for the specified @var{language}.
8913 Supported languages are:
8915 @table @samp
8916 @item C
8917 Do compilation tests using @code{CC} and @code{CPP} and use extension
8918 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8919 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8921 @item C++
8922 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8923 extension @file{.C} for test programs.  Use compilation flags:
8924 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8925 @code{CXXFLAGS} with @code{CXX}.
8927 @item Fortran 77
8928 Do compilation tests using @code{F77} and use extension @file{.f} for
8929 test programs.  Use compilation flags: @code{FFLAGS}.
8931 @item Fortran
8932 Do compilation tests using @code{FC} and use extension @file{.f} (or
8933 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8934 compilation flags: @code{FCFLAGS}.
8936 @item Erlang
8937 @ovindex ERLC
8938 @ovindex ERL
8939 @ovindex ERLCFLAGS
8940 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8941 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8943 @item Objective C
8944 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8945 extension @file{.m} for test programs.  Use compilation flags:
8946 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8947 @code{OBJCFLAGS} with @code{OBJC}.
8949 @item Objective C++
8950 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8951 extension @file{.mm} for test programs.  Use compilation flags:
8952 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8953 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8955 @item Go
8956 Do compilation tests using @code{GOC} and use extension @file{.go} for
8957 test programs.  Use compilation flags @code{GOFLAGS}.
8958 @end table
8959 @end defmac
8961 @anchor{AC_LANG_PUSH}
8962 @defmac AC_LANG_PUSH (@var{language})
8963 @acindex{LANG_PUSH}
8964 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8965 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8966 in macros that need to temporarily switch to a particular language.
8967 @end defmac
8969 @defmac AC_LANG_POP (@ovar{language})
8970 @acindex{LANG_POP}
8971 Select the language that is saved on the top of the stack, as set by
8972 @code{AC_LANG_PUSH}, and remove it from the stack.
8974 If given, @var{language} specifies the language we just @emph{quit}.  It
8975 is a good idea to specify it when it's known (which should be the
8976 case@dots{}), since Autoconf detects inconsistencies.
8978 @example
8979 AC_LANG_PUSH([Fortran 77])
8980 # Perform some tests on Fortran 77.
8981 # @dots{}
8982 AC_LANG_POP([Fortran 77])
8983 @end example
8984 @end defmac
8986 @defmac AC_LANG_ASSERT (@var{language})
8987 @acindex{LANG_ASSERT}
8988 Check statically that the current language is @var{language}.
8989 You should use this in your language specific macros
8990 to avoid that they be called with an inappropriate language.
8992 This macro runs only at @command{autoconf} time, and incurs no cost at
8993 @command{configure} time.  Sadly enough and because Autoconf is a two
8994 layer language @footnote{Because M4 is not aware of Sh code,
8995 especially conditionals, some optimizations that look nice statically
8996 may produce incorrect results at runtime.}, the macros
8997 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8998 therefore as much as possible you ought to avoid using them to wrap
8999 your code, rather, require from the user to run the macro with a
9000 correct current language, and check it with @code{AC_LANG_ASSERT}.
9001 And anyway, that may help the user understand she is running a Fortran
9002 macro while expecting a result about her Fortran 77 compiler@enddots{}
9003 @end defmac
9006 @defmac AC_REQUIRE_CPP
9007 @acindex{REQUIRE_CPP}
9008 Ensure that whichever preprocessor would currently be used for tests has
9009 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
9010 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
9011 depending on which language is current.
9012 @end defmac
9015 @node Writing Test Programs
9016 @section Writing Test Programs
9018 Autoconf tests follow a common scheme: feed some program with some
9019 input, and most of the time, feed a compiler with some source file.
9020 This section is dedicated to these source samples.
9022 @menu
9023 * Guidelines::                  General rules for writing test programs
9024 * Test Functions::              Avoiding pitfalls in test programs
9025 * Generating Sources::          Source program boilerplate
9026 @end menu
9028 @node Guidelines
9029 @subsection Guidelines for Test Programs
9031 The most important rule to follow when writing testing samples is:
9033 @center @emph{Look for realism.}
9035 This motto means that testing samples must be written with the same
9036 strictness as real programs are written.  In particular, you should
9037 avoid ``shortcuts'' and simplifications.
9039 Don't just play with the preprocessor if you want to prepare a
9040 compilation.  For instance, using @command{cpp} to check whether a header is
9041 functional might let your @command{configure} accept a header which
9042 causes some @emph{compiler} error.  Do not hesitate to check a header with
9043 other headers included before, especially required headers.
9045 Make sure the symbols you use are properly defined, i.e., refrain from
9046 simply declaring a function yourself instead of including the proper
9047 header.
9049 Test programs should not write to standard output.  They
9050 should exit with status 0 if the test succeeds, and with status 1
9051 otherwise, so that success
9052 can be distinguished easily from a core dump or other failure;
9053 segmentation violations and other failures produce a nonzero exit
9054 status.  Unless you arrange for @code{exit} to be declared, test
9055 programs should @code{return}, not @code{exit}, from @code{main},
9056 because on many systems @code{exit} is not declared by default.
9058 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9059 preprocessor macros defined by tests that have already run.  For
9060 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9061 @file{configure.ac} you can have a test program that includes
9062 @file{stdbool.h} conditionally:
9064 @example
9065 @group
9066 #ifdef HAVE_STDBOOL_H
9067 # include <stdbool.h>
9068 #endif
9069 @end group
9070 @end example
9072 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9073 work with any standard C compiler.  Some developers prefer @code{#if}
9074 because it is easier to read, while others prefer @code{#ifdef} because
9075 it avoids diagnostics with picky compilers like GCC with the
9076 @option{-Wundef} option.
9078 If a test program needs to use or create a data file, give it a name
9079 that starts with @file{conftest}, such as @file{conftest.data}.  The
9080 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9081 after running test programs and if the script is interrupted.
9083 @node Test Functions
9084 @subsection Test Functions
9086 These days it's safe to assume support for function prototypes
9087 (introduced in C89).
9089 Functions that test programs declare should also be conditionalized for
9090 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9091 include any header files containing clashing prototypes.
9093 @example
9094 #ifdef __cplusplus
9095 extern "C"
9096 #endif
9097 void *valloc (size_t);
9098 @end example
9100 If a test program calls a function with invalid parameters (just to see
9101 whether it exists), organize the program to ensure that it never invokes
9102 that function.  You can do this by calling it in another function that is
9103 never invoked.  You can't do it by putting it after a call to
9104 @code{exit}, because GCC version 2 knows that @code{exit}
9105 never returns
9106 and optimizes out any code that follows it in the same block.
9108 If you include any header files, be sure to call the functions
9109 relevant to them with the correct number of arguments, even if they are
9110 just 0, to avoid compilation errors due to prototypes.  GCC
9111 version 2
9112 has internal prototypes for several functions that it automatically
9113 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9114 them, either pass them the correct number of arguments or redeclare them
9115 with a different return type (such as @code{char}).
9118 @node Generating Sources
9119 @subsection Generating Sources
9121 Autoconf provides a set of macros that can be used to generate test
9122 source files.  They are written to be language generic, i.e., they
9123 actually depend on the current language (@pxref{Language Choice}) to
9124 ``format'' the output properly.
9127 @defmac AC_LANG_CONFTEST (@var{source})
9128 @acindex{LANG_CONFTEST}
9129 Save the @var{source} text in the current test source file:
9130 @file{conftest.@var{extension}} where the @var{extension} depends on the
9131 current language.  As of Autoconf 2.63b, the source file also contains
9132 the results of all of the @code{AC_DEFINE} performed so far.
9134 Note that the @var{source} is evaluated exactly once, like regular
9135 Autoconf macro arguments, and therefore (i) you may pass a macro
9136 invocation, (ii) if not, be sure to double quote if needed.
9138 This macro issues a warning during @command{autoconf} processing if
9139 @var{source} does not include an expansion of the macro
9140 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9141 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9143 This macro is seldom called directly, but is used under the hood by more
9144 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9145 @end defmac
9147 @defmac AC_LANG_DEFINES_PROVIDED
9148 @acindex{LANG_DEFINES_PROVIDED}
9149 This macro is called as a witness that the file
9150 @file{conftest.@var{extension}} appropriate for the current language is
9151 complete, including all previously determined results from
9152 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9153 you have a compelling reason to write a conftest file without using
9154 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9155 @code{AC_LANG_CONFTEST}.
9156 @end defmac
9158 @defmac AC_LANG_SOURCE (@var{source})
9159 @acindex{LANG_SOURCE}
9160 Expands into the @var{source}, with the definition of
9161 all the @code{AC_DEFINE} performed so far.  This macro includes an
9162 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9164 In many cases, you may find it more convenient to use the wrapper
9165 @code{AC_LANG_PROGRAM}.
9166 @end defmac
9168 For instance, executing (observe the double quotation!):
9170 @example
9171 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9172 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9173         [http://www.example.org/])
9174 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9175   [Greetings string.])
9176 AC_LANG([C])
9177 AC_LANG_CONFTEST(
9178    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9179 gcc -E -dD conftest.c
9180 @end example
9182 @noindent
9183 on a system with @command{gcc} installed, results in:
9185 @example
9186 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9187 @dots{}
9188 @asis{#} 1 "conftest.c"
9190 #define PACKAGE_NAME "Hello"
9191 #define PACKAGE_TARNAME "hello"
9192 #define PACKAGE_VERSION "1.0"
9193 #define PACKAGE_STRING "Hello 1.0"
9194 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9195 #define PACKAGE_URL "http://www.example.org/"
9196 #define HELLO_WORLD "Hello, World\n"
9198 const char hw[] = "Hello, World\n";
9199 @end example
9201 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9202 definitions are not automatically translated into constants in the
9203 source code by this macro.
9205 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9206 @acindex{LANG_PROGRAM}
9207 Expands into a source file which consists of the @var{prologue}, and
9208 then @var{body} as body of the main function (e.g., @code{main} in
9209 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9210 available.
9211 @end defmac
9213 For instance:
9215 @example
9216 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9217 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9218         [http://www.example.org/])
9219 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9220   [Greetings string.])
9221 AC_LANG_CONFTEST(
9222 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9223                  [[fputs (hw, stdout);]])])
9224 gcc -E -dD conftest.c
9225 @end example
9227 @noindent
9228 on a system with @command{gcc} installed, results in:
9230 @example
9231 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9232 @dots{}
9233 @asis{#} 1 "conftest.c"
9235 #define PACKAGE_NAME "Hello"
9236 #define PACKAGE_TARNAME "hello"
9237 #define PACKAGE_VERSION "1.0"
9238 #define PACKAGE_STRING "Hello 1.0"
9239 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9240 #define PACKAGE_URL "http://www.example.org/"
9241 #define HELLO_WORLD "Hello, World\n"
9243 const char hw[] = "Hello, World\n";
9245 main (void)
9247 fputs (hw, stdout);
9248   ;
9249   return 0;
9251 @end example
9253 In Erlang tests, the created source file is that of an Erlang module called
9254 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9255 at least
9256 one @code{start/0} function, which is called to perform the test.  The
9257 @var{prologue} is optional code that is inserted between the module header and
9258 the @code{start/0} function definition.  @var{body} is the body of the
9259 @code{start/0} function without the final period (@pxref{Runtime}, about
9260 constraints on this function's behavior).
9262 For instance:
9264 @example
9265 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9266 AC_LANG(Erlang)
9267 AC_LANG_CONFTEST(
9268 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9269                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9270 cat conftest.erl
9271 @end example
9273 @noindent
9274 results in:
9276 @example
9277 -module(conftest).
9278 -export([start/0]).
9279 -define(HELLO_WORLD, "Hello, world!").
9280 start() ->
9281 io:format("~s~n", [?HELLO_WORLD])
9283 @end example
9285 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9286 @acindex{LANG_CALL}
9287 Expands into a source file which consists of the @var{prologue}, and
9288 then a call to the @var{function} as body of the main function (e.g.,
9289 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9290 of the latter are available.
9292 This function will probably be replaced in the future by a version
9293 which would enable specifying the arguments.  The use of this macro is
9294 not encouraged, as it violates strongly the typing system.
9296 This macro cannot be used for Erlang tests.
9297 @end defmac
9299 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9300 @acindex{LANG_FUNC_LINK_TRY}
9301 Expands into a source file which uses the @var{function} in the body of
9302 the main function (e.g., @code{main} in C).  Since it uses
9303 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9305 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9306 It is considered to be severely broken, and in the future will be
9307 removed in favor of actual function calls (with properly typed
9308 arguments).
9310 This macro cannot be used for Erlang tests.
9311 @end defmac
9313 @node Running the Preprocessor
9314 @section Running the Preprocessor
9316 Sometimes one might need to run the preprocessor on some source file.
9317 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9318 your project, not merely run the preprocessor on it; therefore you
9319 certainly want to run the compiler, not the preprocessor.  Resist the
9320 temptation of following the easiest path.
9322 Nevertheless, if you need to run the preprocessor, then use
9323 @code{AC_PREPROC_IFELSE}.
9325 The macros described in this section cannot be used for tests in Erlang,
9326 Fortran, or Go, since those languages require no preprocessor.
9328 @anchor{AC_PREPROC_IFELSE}
9329 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9330   @ovar{action-if-false})
9331 @acindex{PREPROC_IFELSE}
9332 Run the preprocessor of the current language (@pxref{Language Choice})
9333 on the @var{input}, run the shell commands @var{action-if-true} on
9334 success, @var{action-if-false} otherwise.  The @var{input} can be made
9335 by @code{AC_LANG_PROGRAM} and friends.
9337 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9338 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9339 preprocessors.
9341 It is customary to report unexpected failures with
9342 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9343 the preprocessed output in the file @file{conftest.i}.
9344 @end defmac
9346 For instance:
9348 @example
9349 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9350 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9351   [Greetings string.])
9352 AC_PREPROC_IFELSE(
9353    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9354                     [[fputs (hw, stdout);]])],
9355    [AC_MSG_RESULT([OK])],
9356    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9357 @end example
9359 @noindent
9360 might result in:
9362 @example
9363 checking for gcc... gcc
9364 checking whether the C compiler works... yes
9365 checking for C compiler default output file name... a.out
9366 checking for suffix of executables...
9367 checking whether we are cross compiling... no
9368 checking for suffix of object files... o
9369 checking whether the compiler supports GNU C... yes
9370 checking whether gcc accepts -g... yes
9371 checking for gcc option to enable C11 features... -std=gnu11
9372 checking how to run the C preprocessor... gcc -std=gnu11 -E
9374 @end example
9376 @sp 1
9378 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9379 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9380 it impossible to use it to elaborate sources.  You are encouraged to
9381 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9382 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9383 to run the @emph{preprocessor} and not the compiler?
9385 @anchor{AC_EGREP_HEADER}
9386 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9387   @var{action-if-found}, @ovar{action-if-not-found})
9388 @acindex{EGREP_HEADER}
9389 If the output of running the preprocessor on the system header file
9390 @var{header-file} matches the extended regular expression
9391 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9392 execute @var{action-if-not-found}.
9393 @end defmac
9395 @anchor{AC_EGREP_CPP}
9396 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9397   @ovar{action-if-found}, @ovar{action-if-not-found})
9398 @acindex{EGREP_CPP}
9399 @var{program} is the text of a C or C++ program, on which shell
9400 variable, back quote, and backslash substitutions are performed.  If the
9401 output of running the preprocessor on @var{program} matches the
9402 extended regular expression @var{pattern}, execute shell commands
9403 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9404 @end defmac
9408 @node Running the Compiler
9409 @section Running the Compiler
9411 To check for a syntax feature of the current language's (@pxref{Language
9412 Choice}) compiler, such as whether it recognizes a certain keyword, or
9413 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9414 to compile a small program that uses that feature.
9416 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9417   @ovar{action-if-false})
9418 @acindex{COMPILE_IFELSE}
9419 Run the compiler and compilation flags of the current language
9420 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9421 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9422 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9424 It is customary to report unexpected failures with
9425 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9426 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9427 Linker}).  If needed, @var{action-if-true} can further access the
9428 just-compiled object file @file{conftest.$OBJEXT}.
9430 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9431 current language, which means that if the compiler has not yet been
9432 determined, the compiler determination will be made prior to the body of
9433 the outermost @code{AC_DEFUN} macro that triggered this macro to
9434 expand (@pxref{Expanded Before Required}).
9435 @end defmac
9437 @ovindex ERL
9438 For tests in Erlang, the @var{input} must be the source code of a module named
9439 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9440 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9441 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9442 to ensure that the Erlang module has the right name.
9444 @node Running the Linker
9445 @section Running the Linker
9447 To check for a library, a function, or a global variable, Autoconf
9448 @command{configure} scripts try to compile and link a small program that
9449 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9450 @code{ar} on the C library to try to figure out which functions are
9451 available.  Trying to link with the function is usually a more reliable
9452 approach because it avoids dealing with the variations in the options
9453 and output formats of @code{nm} and @code{ar} and in the location of the
9454 standard libraries.  It also allows configuring for cross-compilation or
9455 checking a function's runtime behavior if needed.  On the other hand,
9456 it can be slower than scanning the libraries once, but accuracy is more
9457 important than speed.
9459 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9460 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9461 to check for libraries (@pxref{Libraries}), by adding the library being
9462 checked for to @code{LIBS} temporarily and trying to link a small
9463 program.
9465 @anchor{AC_LINK_IFELSE}
9466 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9467   @ovar{action-if-false})
9468 @acindex{LINK_IFELSE}
9469 Run the compiler (and compilation flags) and the linker of the current
9470 language (@pxref{Language Choice}) on the @var{input}, run the shell
9471 commands @var{action-if-true} on success, @var{action-if-false}
9472 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9473 friends.  If needed, @var{action-if-true} can further access the
9474 just-linked program file @file{conftest$EXEEXT}.
9476 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9477 current compilation flags.
9479 It is customary to report unexpected failures with
9480 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9481 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9482 @end defmac
9484 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9485 programs are interpreted and do not require linking.
9489 @node Runtime
9490 @section Checking Runtime Behavior
9492 Sometimes you need to find out how a system performs at runtime, such
9493 as whether a given function has a certain capability or bug.  If you
9494 can, make such checks when your program runs instead of when it is
9495 configured.  You can check for things like the machine's endianness when
9496 your program initializes itself.
9498 If you really need to test for a runtime behavior while configuring,
9499 you can write a test program to determine the result, and compile and
9500 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9501 possible, because this prevents people from configuring your package for
9502 cross-compiling.
9504 @anchor{AC_RUN_IFELSE}
9505 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9506   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9507 @acindex{RUN_IFELSE}
9508 Run the compiler (and compilation flags) and the linker of the current
9509 language (@pxref{Language Choice}) on the @var{input}, then execute the
9510 resulting program.  If the program returns an exit
9511 status of 0 when executed, run shell commands @var{action-if-true}.
9512 Otherwise, run shell commands @var{action-if-false}.
9514 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9515 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9516 compilation flags of the current language (@pxref{Language Choice}).
9517 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9518 for further testing.
9520 In the @var{action-if-false} section, the failing exit status is
9521 available in the shell variable @samp{$?}.  This exit status might be
9522 that of a failed compilation, or it might be that of a failed program
9523 execution.
9525 If cross-compilation mode is enabled (this is the case if either the
9526 compiler being used does not produce executables that run on the system
9527 where @command{configure} is being run, or if the options @code{--build}
9528 and @code{--host} were both specified and their values are different),
9529 then the test program is
9530 not run.  If the optional shell commands @var{action-if-cross-compiling}
9531 are given, those commands are run instead; typically these commands
9532 provide pessimistic defaults that allow cross-compilation to work even
9533 if the guess was wrong.  If the fourth argument is empty or omitted, but
9534 cross-compilation is detected, then @command{configure} prints an error
9535 message and exits.  If you want your package to be useful in a
9536 cross-compilation scenario, you @emph{should} provide a non-empty
9537 @var{action-if-cross-compiling} clause, as well as wrap the
9538 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9539 (@pxref{Caching Results}) which allows the user to override the
9540 pessimistic default if needed.
9542 It is customary to report unexpected failures with
9543 @code{AC_MSG_FAILURE}.
9544 @end defmac
9546 @command{autoconf} prints a warning message when creating
9547 @command{configure} each time it encounters a call to
9548 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9549 given.  If you are not concerned about users configuring your package
9550 for cross-compilation, you may ignore the warning.  A few of the macros
9551 distributed with Autoconf produce this warning message; but if this is a
9552 problem for you, please report it as a bug, along with an appropriate
9553 pessimistic guess to use instead.
9555 To configure for cross-compiling you can also choose a value for those
9556 parameters based on the canonical system name (@pxref{Manual
9557 Configuration}).  Alternatively, set up a test results cache file with
9558 the correct values for the host system (@pxref{Caching Results}).
9560 @ovindex cross_compiling
9561 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9562 in other macros, including a few of the ones that come with Autoconf,
9563 you can test whether the shell variable @code{cross_compiling} is set to
9564 @samp{yes}, and then use an alternate method to get the results instead
9565 of calling the macros.
9567 It is also permissible to temporarily assign to @code{cross_compiling}
9568 in order to force tests to behave as though they are in a
9569 cross-compilation environment, particularly since this provides a way to
9570 test your @var{action-if-cross-compiling} even when you are not using a
9571 cross-compiler.
9573 @example
9574 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9575 # to use the slow link-only method
9576 save_cross_compiling=$cross_compiling
9577 cross_compiling=yes
9578 AC_COMPUTE_INT([@dots{}])
9579 cross_compiling=$save_cross_compiling
9580 @end example
9582 A C or C++ runtime test should be portable.
9583 @xref{Portable C and C++}.
9585 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9586 function: the given status code is used to determine the success of the test
9587 (status is @code{0}) or its failure (status is different than @code{0}), as
9588 explained above.  It must be noted that data output through the standard output
9589 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9590 Therefore, if a test must output configuration information, it is recommended
9591 to create and to output data into the temporary file named @file{conftest.out},
9592 using the functions of module @code{file}.  The @code{conftest.out} file is
9593 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9594 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9595 macro is:
9597 @example
9598 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9599 AC_ERLANG_NEED_ERL
9600 AC_LANG(Erlang)
9601 AC_RUN_IFELSE(
9602   [AC_LANG_PROGRAM([], [dnl
9603     file:write_file("conftest.out", code:lib_dir()),
9604     halt(0)])],
9605   [echo "code:lib_dir() returned: `cat conftest.out`"],
9606   [AC_MSG_FAILURE([test Erlang program execution failed])])
9607 @end example
9610 @node Systemology
9611 @section Systemology
9612 @cindex Systemology
9614 This section aims at presenting some systems and pointers to
9615 documentation.  It may help you addressing particular problems reported
9616 by users.
9618 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9619 derived from the
9620 @uref{http://@/www.bell-labs.com/@/usr/@/dmr/@/www/@/hist.html, Unix
9621 operating system}.
9623 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9624 contains a table correlating the features of various Posix-conforming
9625 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9626 simplified diagram of how many Unix systems were derived from each
9627 other.
9629 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9630 provides some variants of traditional implementations of Unix utilities.
9632 @table @asis
9633 @item Darwin
9634 @cindex Darwin
9635 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9636 case-preserving, but case insensitive.  This can cause nasty problems,
9637 since for instance the installation attempt for a package having an
9638 @file{INSTALL} file can result in @samp{make install} report that
9639 nothing was to be done!
9641 That's all dependent on whether the file system is a UFS (case
9642 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9643 install the OS on HFS+.  Unfortunately, there are some pieces of
9644 software which really need to be built on UFS@.  We may want to rebuild
9645 Darwin to have both UFS and HFS+ available (and put the /local/build
9646 tree on the UFS).
9648 @item QNX 4.25
9649 @cindex QNX 4.25
9650 @c FIXME: Please, if you feel like writing something more precise,
9651 @c it'd be great.  In particular, I can't understand the difference with
9652 @c QNX Neutrino.
9653 QNX is a realtime operating system running on Intel architecture
9654 meant to be scalable from the small embedded systems to the hundred
9655 processor super-computer.  It claims to be Posix certified.  More
9656 information is available on the
9657 @uref{http://@/www.qnx.com/, QNX home page}.
9659 @item Tru64
9660 @cindex Tru64
9661 @uref{http://@/h30097.www3.hp.com/@/docs/,
9662 Documentation of several versions of Tru64} is available in different
9663 formats.
9665 @item Unix version 7
9666 @cindex Unix version 7
9667 @cindex V7
9668 Officially this was called the ``Seventh Edition'' of ``the UNIX
9669 time-sharing system'' but we use the more-common name ``Unix version 7''.
9670 Documentation is available in the
9671 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9672 Previous versions of Unix are called ``Unix version 6'', etc., but
9673 they were not as widely used.
9674 @end table
9677 @node Multiple Cases
9678 @section Multiple Cases
9680 Some operations are accomplished in several possible ways, depending on
9681 the OS variant.  Checking for them essentially requires a ``case
9682 statement''.  Autoconf does not directly provide one; however, it is
9683 easy to simulate by using a shell variable to keep track of whether a
9684 way to perform the operation has been found yet.
9686 Here is an example that uses the shell variable @code{fstype} to keep
9687 track of whether the remaining cases need to be checked.  Note that
9688 since the value of @code{fstype} is under our control, we don't have to
9689 use the longer @samp{test "x$fstype" = xno}.
9691 @example
9692 @group
9693 AC_MSG_CHECKING([how to get file system type])
9694 fstype=no
9695 # The order of these tests is important.
9696 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9697 #include <sys/fstyp.h>]])],
9698                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9699                      [Define if statvfs exists.])
9700                    fstype=SVR4])
9701 if test $fstype = no; then
9702   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9703 #include <sys/fstyp.h>]])],
9704                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9705                      [Define if USG statfs.])
9706                    fstype=SVR3])
9708 if test $fstype = no; then
9709   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9710 #include <sys/vmount.h>]])]),
9711                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9712                      [Define if AIX statfs.])
9713                    fstype=AIX])
9715 # (more cases omitted here)
9716 AC_MSG_RESULT([$fstype])
9717 @end group
9718 @end example
9720 @c ====================================================== Results of Tests.
9722 @node Results
9723 @chapter Results of Tests
9725 Once @command{configure} has determined whether a feature exists, what can
9726 it do to record that information?  There are four sorts of things it can
9727 do: define a C preprocessor symbol, set a variable in the output files,
9728 save the result in a cache file for future @command{configure} runs, and
9729 print a message letting the user know the result of the test.
9731 @menu
9732 * Defining Symbols::            Defining C preprocessor symbols
9733 * Setting Output Variables::    Replacing variables in output files
9734 * Special Chars in Variables::  Characters to beware of in variables
9735 * Caching Results::             Speeding up subsequent @command{configure} runs
9736 * Printing Messages::           Notifying @command{configure} users
9737 @end menu
9739 @node Defining Symbols
9740 @section Defining C Preprocessor Symbols
9742 A common action to take in response to a feature test is to define a C
9743 preprocessor symbol indicating the results of the test.  That is done by
9744 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9746 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9747 into the output variable @code{DEFS}, which contains an option
9748 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9749 Autoconf version 1, there is no variable @code{DEFS} defined while
9750 @command{configure} is running.  To check whether Autoconf macros have
9751 already defined a certain C preprocessor symbol, test the value of the
9752 appropriate cache variable, as in this example:
9754 @example
9755 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9756                           [Define if vprintf exists.])])
9757 if test "x$ac_cv_func_vprintf" != xyes; then
9758   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9759                             [Define if _doprnt exists.])])
9761 @end example
9763 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9764 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9765 correct values into @code{#define} statements in a template file.
9766 @xref{Configuration Headers}, for more information about this kind of
9767 output.
9769 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9770 @defmacx AC_DEFINE (@var{variable})
9771 @cvindex @var{variable}
9772 @acindex{DEFINE}
9773 Define @var{variable} to @var{value} (verbatim), by defining a C
9774 preprocessor macro for @var{variable}.  @var{variable} should be a C
9775 identifier, optionally suffixed by a parenthesized argument list to
9776 define a C preprocessor macro with arguments.  The macro argument list,
9777 if present, should be a comma-separated list of C identifiers, possibly
9778 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
9779 @var{variable} should not contain comments, white space, trigraphs,
9780 backslash-newlines, universal character names, or non-ASCII
9781 characters.
9783 @var{value} may contain backslash-escaped newlines, which will be
9784 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9785 via @code{@@DEFS@@} (with no effect on the compilation, since the
9786 preprocessor sees only one line in the first place).  @var{value} should
9787 not contain raw newlines.  If you are not using
9788 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9789 characters, as @command{make} tends to eat them.  To use a shell
9790 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9792 @var{description} is only useful if you are using
9793 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9794 the generated @file{config.h.in} as the comment before the macro define.
9795 The following example defines the C preprocessor variable
9796 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9798 @example
9799 AC_DEFINE([EQUATION], ["$a > $b"],
9800   [Equation string.])
9801 @end example
9803 If neither @var{value} nor @var{description} are given, then
9804 @var{value} defaults to 1 instead of to the empty string.  This is for
9805 backwards compatibility with older versions of Autoconf, but this usage
9806 is obsolescent and may be withdrawn in future versions of Autoconf.
9808 If the @var{variable} is a literal string, it is passed to
9809 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9811 If multiple @code{AC_DEFINE} statements are executed for the same
9812 @var{variable} name (not counting any parenthesized argument list),
9813 the last one wins.
9814 @end defmac
9816 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9817 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9818 @acindex{DEFINE_UNQUOTED}
9819 @cvindex @var{variable}
9820 Like @code{AC_DEFINE}, but three shell expansions are
9821 performed---once---on @var{variable} and @var{value}: variable expansion
9822 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9823 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9824 characters in the value have no
9825 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9826 @var{variable} or @var{value} is a shell variable.  Examples:
9828 @example
9829 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9830   [Configuration machine file.])
9831 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9832   [getgroups return type.])
9833 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9834   [Translated header name.])
9835 @end example
9836 @end defmac
9838 Due to a syntactical bizarreness of the Bourne shell, do not use
9839 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9840 calls from other macro calls or shell code; that can cause syntax errors
9841 in the resulting @command{configure} script.  Use either blanks or
9842 newlines.  That is, do this:
9844 @example
9845 AC_CHECK_HEADER([elf.h],
9846   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9847 @end example
9849 @noindent
9850 or this:
9852 @example
9853 AC_CHECK_HEADER([elf.h],
9854   [AC_DEFINE([SVR4], [1], [System V Release 4])
9855    LIBS="-lelf $LIBS"])
9856 @end example
9858 @noindent
9859 instead of this:
9861 @example
9862 AC_CHECK_HEADER([elf.h],
9863   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9864 @end example
9866 @node Setting Output Variables
9867 @section Setting Output Variables
9868 @cindex Output variables
9870 Another way to record the results of tests is to set @dfn{output
9871 variables}, which are shell variables whose values are substituted into
9872 files that @command{configure} outputs.  The two macros below create new
9873 output variables.  @xref{Preset Output Variables}, for a list of output
9874 variables that are always available.
9876 @defmac AC_SUBST (@var{variable}, @ovar{value})
9877 @acindex{SUBST}
9878 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9879 substitute the variable @var{variable} into output files (typically one
9880 or more makefiles).  This means that @code{AC_OUTPUT}
9881 replaces instances of @samp{@@@var{variable}@@} in input files with the
9882 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9883 is called.  The value can contain any non-@code{NUL} character, including
9884 newline.  If you are using Automake 1.11 or newer, for newlines in values
9885 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9886 @command{automake} from adding a line @code{@var{variable} =
9887 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9888 Automake, automake, Other things Automake recognizes}).
9890 Variable occurrences should not overlap: e.g., an input file should
9891 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9892 are variable names.
9893 The substituted value is not rescanned for more output variables;
9894 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9895 literally into the output file.  (The algorithm uses the special marker
9896 @code{|#_!!_#|} internally, so neither the substituted value nor the
9897 output file may contain @code{|#_!!_#|}.)
9899 If @var{value} is given, in addition assign it to @var{variable}.
9901 The string @var{variable} is passed to @code{m4_pattern_allow}
9902 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
9903 even if there is another macro by the same name.
9904 @end defmac
9906 @defmac AC_SUBST_FILE (@var{variable})
9907 @acindex{SUBST_FILE}
9908 Another way to create an output variable from a shell variable.  Make
9909 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9910 named by shell variable @var{variable} into output files.  This means
9911 that @code{AC_OUTPUT} replaces instances of
9912 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9913 with the contents of the file that the shell variable @var{variable}
9914 names when @code{AC_OUTPUT} is called.  Set the variable to
9915 @file{/dev/null} for cases that do not have a file to insert.
9916 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9917 line by itself, optionally surrounded by spaces and tabs.  The
9918 substitution replaces the whole line, including the spaces, tabs, and
9919 the terminating newline.
9921 This macro is useful for inserting makefile fragments containing
9922 special dependencies or other @command{make} directives for particular host
9923 or target types into makefiles.  For example, @file{configure.ac}
9924 could contain:
9926 @example
9927 AC_SUBST_FILE([host_frag])
9928 host_frag=$srcdir/conf/sun4.mh
9929 @end example
9931 @noindent
9932 and then a @file{Makefile.in} could contain:
9934 @example
9935 @@host_frag@@
9936 @end example
9938 The string @var{variable} is passed to @code{m4_pattern_allow}
9939 (@pxref{Forbidden Patterns}).
9940 @end defmac
9942 @cindex Precious Variable
9943 @cindex Variable, Precious
9944 Running @command{configure} in varying environments can be extremely
9945 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9946 ./configure}, then the cache, @file{config.h}, and many other output
9947 files depend upon @command{bizarre-cc} being the C compiler.  If
9948 for some reason the user runs @command{./configure} again, or if it is
9949 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9950 and @pxref{config.status Invocation}), then the configuration can be
9951 inconsistent, composed of results depending upon two different
9952 compilers.
9954 Environment variables that affect this situation, such as @samp{CC}
9955 above, are called @dfn{precious variables}, and can be declared as such
9956 by @code{AC_ARG_VAR}.
9958 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9959 @acindex{ARG_VAR}
9960 Declare @var{variable} is a precious variable, and include its
9961 @var{description} in the variable section of @samp{./configure --help}.
9963 Being precious means that
9964 @itemize @minus
9965 @item
9966 @var{variable} is substituted via @code{AC_SUBST}.
9968 @item
9969 The value of @var{variable} when @command{configure} was launched is
9970 saved in the cache, including if it was not specified on the command
9971 line but via the environment.  Indeed, while @command{configure} can
9972 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9973 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9974 which, unfortunately, is what most users do.
9976 We emphasize that it is the @emph{initial} value of @var{variable} which
9977 is saved, not that found during the execution of @command{configure}.
9978 Indeed, specifying @samp{./configure FOO=foo} and letting
9979 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9980 different things.
9982 @item
9983 @var{variable} is checked for consistency between two
9984 @command{configure} runs.  For instance:
9986 @example
9987 $ @kbd{./configure --silent --config-cache}
9988 $ @kbd{CC=cc ./configure --silent --config-cache}
9989 configure: error: 'CC' was not set in the previous run
9990 configure: error: changes in the environment can compromise \
9991 the build
9992 configure: error: run 'make distclean' and/or \
9993 'rm config.cache' and start over
9994 @end example
9996 @noindent
9997 and similarly if the variable is unset, or if its content is changed.
9998 If the content has white space changes only, then the error is degraded
9999 to a warning only, but the old value is reused.
10001 @item
10002 @var{variable} is kept during automatic reconfiguration
10003 (@pxref{config.status Invocation}) as if it had been passed as a command
10004 line argument, including when no cache is used:
10006 @example
10007 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
10008 $ @kbd{./config.status --recheck}
10009 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
10010   CC=/usr/bin/cc  --no-create --no-recursion
10011 @end example
10012 @end itemize
10013 @end defmac
10015 @node Special Chars in Variables
10016 @section Special Characters in Output Variables
10017 @cindex Output variables, special characters in
10019 Many output variables are intended to be evaluated both by
10020 @command{make} and by the shell.  Some characters are expanded
10021 differently in these two contexts, so to avoid confusion these
10022 variables' values should not contain any of the following characters:
10024 @example
10025 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
10026 @end example
10028 Also, these variables' values should neither contain newlines, nor start
10029 with @samp{~}, nor contain white space or @samp{:} immediately followed
10030 by @samp{~}.  The values can contain nonempty sequences of white space
10031 characters like tabs and spaces, but each such sequence might
10032 arbitrarily be replaced by a single space during substitution.
10034 These restrictions apply both to the values that @command{configure}
10035 computes, and to the values set directly by the user.  For example, the
10036 following invocations of @command{configure} are problematic, since they
10037 attempt to use special characters within @code{CPPFLAGS} and white space
10038 within @code{$(srcdir)}:
10040 @example
10041 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
10043 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10044 @end example
10046 @node Caching Results
10047 @section Caching Results
10048 @cindex Cache
10050 To avoid checking for the same features repeatedly in various
10051 @command{configure} scripts (or in repeated runs of one script),
10052 @command{configure} can optionally save the results of many checks in a
10053 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10054 runs with caching enabled and finds a cache file, it reads the results
10055 of previous runs from the cache and avoids rerunning those checks.  As a
10056 result, @command{configure} can then run much faster than if it had to
10057 perform all of the checks every time.
10059 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10060 @acindex{CACHE_VAL}
10061 Ensure that the results of the check identified by @var{cache-id} are
10062 available.  If the results of the check were in the cache file that was
10063 read, and @command{configure} was not given the @option{--quiet} or
10064 @option{--silent} option, print a message saying that the result was
10065 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10066 the shell commands are run to determine the value, the value is
10067 saved in the cache file just before @command{configure} creates its output
10068 files.  @xref{Cache Variable Names}, for how to choose the name of the
10069 @var{cache-id} variable.
10071 The @var{commands-to-set-it} @emph{must have no side effects} except for
10072 setting the variable @var{cache-id}, see below.
10073 @end defmac
10075 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10076   @var{commands-to-set-it})
10077 @acindex{CACHE_CHECK}
10078 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10079 messages.  This macro provides a convenient shorthand for the most
10080 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10081 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10082 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10084 The @var{commands-to-set-it} @emph{must have no side effects} except for
10085 setting the variable @var{cache-id}, see below.
10086 @end defmac
10088 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10089 @code{AC_CACHE_CHECK}, because people are tempted to call
10090 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10091 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10092 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10093 instance, the following macro is broken:
10095 @example
10096 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10097 @group
10098 AC_DEFUN([AC_SHELL_TRUE],
10099 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10100                 [my_cv_shell_true_works=no
10101                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10102                  if test "x$my_cv_shell_true_works" = xyes; then
10103                    AC_DEFINE([TRUE_WORKS], [1],
10104                              [Define if 'true(1)' works properly.])
10105                  fi])
10107 @end group
10108 @end example
10110 @noindent
10111 This fails if the cache is enabled: the second time this macro is run,
10112 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10115 @example
10116 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10117 @group
10118 AC_DEFUN([AC_SHELL_TRUE],
10119 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10120                 [my_cv_shell_true_works=no
10121                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10122  if test "x$my_cv_shell_true_works" = xyes; then
10123    AC_DEFINE([TRUE_WORKS], [1],
10124              [Define if 'true(1)' works properly.])
10125  fi
10127 @end group
10128 @end example
10130 Also, @var{commands-to-set-it} should not print any messages, for
10131 example with @code{AC_MSG_CHECKING}; do that before calling
10132 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10133 the results of the check are retrieved from the cache or determined by
10134 running the shell commands.
10136 @menu
10137 * Cache Variable Names::        Shell variables used in caches
10138 * Cache Files::                 Files @command{configure} uses for caching
10139 * Cache Checkpointing::         Loading and saving the cache file
10140 @end menu
10142 @node Cache Variable Names
10143 @subsection Cache Variable Names
10144 @cindex Cache variable
10146 The names of cache variables should have the following format:
10148 @example
10149 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10150 @end example
10152 @noindent
10153 for example, @samp{ac_cv_header_stat_broken} or
10154 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10156 @table @asis
10157 @item @var{package-prefix}
10158 An abbreviation for your package or organization; the same prefix you
10159 begin local Autoconf macros with, except lowercase by convention.
10160 For cache values used by the distributed Autoconf macros, this value is
10161 @samp{ac}.
10163 @item @code{_cv_}
10164 Indicates that this shell variable is a cache value.  This string
10165 @emph{must} be present in the variable name, including the leading
10166 underscore.
10168 @item @var{value-type}
10169 A convention for classifying cache values, to produce a rational naming
10170 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10172 @item @var{specific-value}
10173 Which member of the class of cache values this test applies to.
10174 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10175 output variable (@samp{INSTALL}).
10177 @item @var{additional-options}
10178 Any particular behavior of the specific member that this test applies to.
10179 For example, @samp{broken} or @samp{set}.  This part of the name may
10180 be omitted if it does not apply.
10181 @end table
10183 The values assigned to cache variables may not contain newlines.
10184 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10185 names of files or functions; so this is not an important restriction.
10186 @ref{Cache Variable Index} for an index of cache variables with
10187 documented semantics.
10190 @node Cache Files
10191 @subsection Cache Files
10193 A cache file is a shell script that caches the results of configure
10194 tests run on one system so they can be shared between configure scripts
10195 and configure runs.  It is not useful on other systems.  If its contents
10196 are invalid for some reason, the user may delete or edit it, or override
10197 documented cache variables on the @command{configure} command line.
10199 By default, @command{configure} uses no cache file,
10200 to avoid problems caused by accidental
10201 use of stale cache files.
10203 To enable caching, @command{configure} accepts @option{--config-cache} (or
10204 @option{-C}) to cache results in the file @file{config.cache}.
10205 Alternatively, @option{--cache-file=@var{file}} specifies that
10206 @var{file} be the cache file.  The cache file is created if it does not
10207 exist already.  When @command{configure} calls @command{configure} scripts in
10208 subdirectories, it uses the @option{--cache-file} argument so that they
10209 share the same cache.  @xref{Subdirectories}, for information on
10210 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10212 @file{config.status} only pays attention to the cache file if it is
10213 given the @option{--recheck} option, which makes it rerun
10214 @command{configure}.
10216 It is wrong to try to distribute cache files for particular system types.
10217 There is too much room for error in doing that, and too much
10218 administrative overhead in maintaining them.  For any features that
10219 can't be guessed automatically, use the standard method of the canonical
10220 system type and linking files (@pxref{Manual Configuration}).
10222 The site initialization script can specify a site-wide cache file to
10223 use, instead of the usual per-program cache.  In this case, the cache
10224 file gradually accumulates information whenever someone runs a new
10225 @command{configure} script.  (Running @command{configure} merges the new cache
10226 results with the existing cache file.)  This may cause problems,
10227 however, if the system configuration (e.g., the installed libraries or
10228 compilers) changes and the stale cache file is not deleted.
10230 If @command{configure} is interrupted at the right time when it updates
10231 a cache file outside of the build directory where the @command{configure}
10232 script is run, it may leave behind a temporary file named after the
10233 cache file with digits following it.  You may safely delete such a file.
10236 @node Cache Checkpointing
10237 @subsection Cache Checkpointing
10239 If your configure script, or a macro called from @file{configure.ac}, happens
10240 to abort the configure process, it may be useful to checkpoint the cache
10241 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10242 reduces the amount of time it takes to rerun the configure script with
10243 (hopefully) the error that caused the previous abort corrected.
10245 @c FIXME: Do we really want to document this guy?
10246 @defmac AC_CACHE_LOAD
10247 @acindex{CACHE_LOAD}
10248 Loads values from existing cache file, or creates a new cache file if a
10249 cache file is not found.  Called automatically from @code{AC_INIT}.
10250 @end defmac
10252 @defmac AC_CACHE_SAVE
10253 @acindex{CACHE_SAVE}
10254 Flushes all cached values to the cache file.  Called automatically from
10255 @code{AC_OUTPUT}, but it can be quite useful to call
10256 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10257 @end defmac
10259 For instance:
10261 @example
10262 @r{ @dots{} AC_INIT, etc. @dots{}}
10263 @group
10264 # Checks for programs.
10265 AC_PROG_CC
10266 AC_PROG_AWK
10267 @r{ @dots{} more program checks @dots{}}
10268 AC_CACHE_SAVE
10269 @end group
10271 @group
10272 # Checks for libraries.
10273 AC_CHECK_LIB([nsl], [gethostbyname])
10274 AC_CHECK_LIB([socket], [connect])
10275 @r{ @dots{} more lib checks @dots{}}
10276 AC_CACHE_SAVE
10277 @end group
10279 @group
10280 # Might abort@dots{}
10281 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10282 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10283 @end group
10284 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10285 @end example
10287 @node Printing Messages
10288 @section Printing Messages
10289 @cindex Messages, from @command{configure}
10291 @command{configure} scripts need to give users running them several kinds
10292 of information.  The following macros print messages in ways appropriate
10293 for each kind.  The arguments to all of them get enclosed in shell
10294 double quotes, so the shell performs variable and back-quote
10295 substitution on them.
10297 These macros are all wrappers around the @command{echo} shell command.
10298 They direct output to the appropriate file descriptor (@pxref{File
10299 Descriptor Macros}).
10300 @command{configure} scripts should rarely need to run @command{echo} directly
10301 to print messages for the user.  Using these macros makes it easy to
10302 change how and when each kind of message is printed; such changes need
10303 only be made to the macro definitions and all the callers change
10304 automatically.
10306 To diagnose static issues, i.e., when @command{autoconf} is run, see
10307 @ref{Diagnostic Macros}.
10309 @defmac AC_MSG_CHECKING (@var{feature-description})
10310 @acindex{MSG_CHECKING}
10311 Notify the user that @command{configure} is checking for a particular
10312 feature.  This macro prints a message that starts with @samp{checking }
10313 and ends with @samp{...} and no newline.  It must be followed by a call
10314 to @code{AC_MSG_RESULT} to print the result of the check and the
10315 newline.  The @var{feature-description} should be something like
10316 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10317 _Alignof}.
10319 This macro prints nothing if @command{configure} is run with the
10320 @option{--quiet} or @option{--silent} option.
10321 @end defmac
10323 @anchor{AC_MSG_RESULT}
10324 @defmac AC_MSG_RESULT (@var{result-description})
10325 @acindex{MSG_RESULT}
10326 Notify the user of the results of a check.  @var{result-description} is
10327 almost always the value of the cache variable for the check, typically
10328 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10329 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10330 the completion of the message printed by the call to
10331 @code{AC_MSG_CHECKING}.
10333 This macro prints nothing if @command{configure} is run with the
10334 @option{--quiet} or @option{--silent} option.
10335 @end defmac
10337 @anchor{AC_MSG_NOTICE}
10338 @defmac AC_MSG_NOTICE (@var{message})
10339 @acindex{MSG_NOTICE}
10340 Deliver the @var{message} to the user.  It is useful mainly to print a
10341 general description of the overall purpose of a group of feature checks,
10342 e.g.,
10344 @example
10345 AC_MSG_NOTICE([checking if stack overflow is detectable])
10346 @end example
10348 This macro prints nothing if @command{configure} is run with the
10349 @option{--quiet} or @option{--silent} option.
10350 @end defmac
10352 @anchor{AC_MSG_ERROR}
10353 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10354 @acindex{MSG_ERROR}
10355 Notify the user of an error that prevents @command{configure} from
10356 completing.  This macro prints an error message to the standard error
10357 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10358 by default, except that @samp{0} is converted to @samp{1}).
10359 @var{error-description} should be something like @samp{invalid value
10360 $HOME for \$HOME}.
10362 The @var{error-description} should start with a lower-case letter, and
10363 ``cannot'' is preferred to ``can't''.
10364 @end defmac
10366 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10367 @acindex{MSG_FAILURE}
10368 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10369 prevents @command{configure} from completing @emph{and} that additional
10370 details are provided in @file{config.log}.  This is typically used when
10371 abnormal results are found during a compilation.
10372 @end defmac
10374 @anchor{AC_MSG_WARN}
10375 @defmac AC_MSG_WARN (@var{problem-description})
10376 @acindex{MSG_WARN}
10377 Notify the @command{configure} user of a possible problem.  This macro
10378 prints the message to the standard error output; @command{configure}
10379 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10380 provide a default (back-up) behavior for the situations they warn about.
10381 @var{problem-description} should be something like @samp{ln -s seems to
10382 make hard links}.
10383 @end defmac
10387 @c ====================================================== Programming in M4.
10389 @node Programming in M4
10390 @chapter Programming in M4
10391 @cindex M4
10393 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10394 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10395 provides macros dedicated to shell script generation.
10397 As of this version of Autoconf, these two layers still contain
10398 experimental macros, whose interface might change in the future.  As a
10399 matter of fact, @emph{anything that is not documented must not be used}.
10401 @menu
10402 * M4 Quotation::                Protecting macros from unwanted expansion
10403 * Using autom4te::              The Autoconf executables backbone
10404 * Programming in M4sugar::      Convenient pure M4 macros
10405 * Debugging via autom4te::      Figuring out what M4 was doing
10406 @end menu
10408 @node M4 Quotation
10409 @section M4 Quotation
10410 @cindex M4 quotation
10411 @cindex quotation
10413 The most common problem with existing macros is an improper quotation.
10414 This section, which users of Autoconf can skip, but which macro writers
10415 @emph{must} read, first justifies the quotation scheme that was chosen
10416 for Autoconf and then ends with a rule of thumb.  Understanding the
10417 former helps one to follow the latter.
10419 @menu
10420 * Active Characters::           Characters that change the behavior of M4
10421 * One Macro Call::              Quotation and one macro call
10422 * Quoting and Parameters::      M4 vs. shell parameters
10423 * Quotation and Nested Macros::  Macros calling macros
10424 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10425 * Quadrigraphs::                Another way to escape special characters
10426 * Balancing Parentheses::       Dealing with unbalanced parentheses
10427 * Quotation Rule Of Thumb::     One parenthesis, one quote
10428 @end menu
10430 @node Active Characters
10431 @subsection Active Characters
10433 To fully understand where proper quotation is important, you first need
10434 to know what the special characters are in Autoconf: @samp{#} introduces
10435 a comment inside which no macro expansion is performed, @samp{,}
10436 separates arguments, @samp{[} and @samp{]} are the quotes
10437 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10438 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10439 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10440 @samp{$} inside a macro definition.
10442 In order to understand the delicate case of macro calls, we first have
10443 to present some obvious failures.  Below they are ``obvious-ified'',
10444 but when you find them in real life, they are usually in disguise.
10446 Comments, introduced by a hash and running up to the newline, are opaque
10447 tokens to the top level: active characters are turned off, and there is
10448 no macro expansion:
10450 @example
10451 # define([def], ine)
10452 @result{}# define([def], ine)
10453 @end example
10455 Each time there can be a macro expansion, there is a quotation
10456 expansion, i.e., one level of quotes is stripped:
10458 @example
10459 int tab[10];
10460 @result{}int tab10;
10461 [int tab[10];]
10462 @result{}int tab[10];
10463 @end example
10465 Without this in mind, the reader might try hopelessly to use her macro
10466 @code{array}:
10468 @example
10469 define([array], [int tab[10];])
10470 array
10471 @result{}int tab10;
10472 [array]
10473 @result{}array
10474 @end example
10476 @noindent
10477 How can you correctly output the intended results@footnote{Using
10478 @code{defn}.}?
10481 @node One Macro Call
10482 @subsection One Macro Call
10484 Let's proceed on the interaction between active characters and macros
10485 with this small macro, which just returns its first argument:
10487 @example
10488 define([car], [$1])
10489 @end example
10491 @noindent
10492 The two pairs of quotes above are not part of the arguments of
10493 @code{define}; rather, they are understood by the top level when it
10494 tries to find the arguments of @code{define}.  Therefore, assuming
10495 @code{car} is not already defined, it is equivalent to write:
10497 @example
10498 define(car, $1)
10499 @end example
10501 @noindent
10502 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10503 quotes, it is bad practice for Autoconf macros which must both be more
10504 robust and also advocate perfect style.
10506 At the top level, there are only two possibilities: either you
10507 quote or you don't:
10509 @example
10510 car(foo, bar, baz)
10511 @result{}foo
10512 [car(foo, bar, baz)]
10513 @result{}car(foo, bar, baz)
10514 @end example
10516 Let's pay attention to the special characters:
10518 @example
10519 car(#)
10520 @error{}EOF in argument list
10521 @end example
10523 The closing parenthesis is hidden in the comment; with a hypothetical
10524 quoting, the top level understood it this way:
10526 @example
10527 car([#)]
10528 @end example
10530 @noindent
10531 Proper quotation, of course, fixes the problem:
10533 @example
10534 car([#])
10535 @result{}#
10536 @end example
10538 Here are more examples:
10540 @example
10541 car(foo, bar)
10542 @result{}foo
10543 car([foo, bar])
10544 @result{}foo, bar
10545 car((foo, bar))
10546 @result{}(foo, bar)
10547 car([(foo], [bar)])
10548 @result{}(foo
10549 define([a], [b])
10550 @result{}
10551 car(a)
10552 @result{}b
10553 car([a])
10554 @result{}b
10555 car([[a]])
10556 @result{}a
10557 car([[[a]]])
10558 @result{}[a]
10559 @end example
10561 @node Quoting and Parameters
10562 @subsection Quoting and Parameters
10564 When M4 encounters @samp{$} within a macro definition, followed
10565 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10566 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10567 expansion.  This happens regardless of how many layers of quotes the
10568 parameter expansion is nested within, or even if it occurs in text that
10569 will be rescanned as a comment.
10571 @example
10572 define([none], [$1])
10573 @result{}
10574 define([one], [[$1]])
10575 @result{}
10576 define([two], [[[$1]]])
10577 @result{}
10578 define([comment], [# $1])
10579 @result{}
10580 define([active], [ACTIVE])
10581 @result{}
10582 none([active])
10583 @result{}ACTIVE
10584 one([active])
10585 @result{}active
10586 two([active])
10587 @result{}[active]
10588 comment([active])
10589 @result{}# active
10590 @end example
10592 On the other hand, since autoconf generates shell code, you often want
10593 to output shell variable expansion, rather than performing M4 parameter
10594 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10595 from the next character in the definition of your macro.  If the macro
10596 definition occurs in single-quoted text, then insert another level of
10597 quoting; if the usage is already inside a double-quoted string, then
10598 split it into concatenated strings.
10600 @example
10601 define([foo], [a single-quoted $[]1 definition])
10602 @result{}
10603 define([bar], [[a double-quoted $][1 definition]])
10604 @result{}
10606 @result{}a single-quoted $1 definition
10608 @result{}a double-quoted $1 definition
10609 @end example
10611 Posix states that M4 implementations are free to provide implementation
10612 extensions when @samp{$@{} is encountered in a macro definition.
10613 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10614 extensions that will be available in the future GNU M4 2.0,
10615 but guarantees that all other instances of @samp{$@{} will be output
10616 literally.  Therefore, this idiom can also be used to output shell code
10617 parameter references:
10619 @example
10620 define([first], [$@{1@}])first
10621 @result{}$@{1@}
10622 @end example
10624 Posix also states that @samp{$11} should expand to the first parameter
10625 concatenated with a literal @samp{1}, although some versions of
10626 GNU M4 expand the eleventh parameter instead.  For
10627 portability, you should only use single-digit M4 parameter expansion.
10629 With this in mind, we can explore the cases where macros invoke
10630 macros@enddots{}
10632 @node Quotation and Nested Macros
10633 @subsection Quotation and Nested Macros
10635 The examples below use the following macros:
10637 @example
10638 define([car], [$1])
10639 define([active], [ACT, IVE])
10640 define([array], [int tab[10]])
10641 @end example
10643 Each additional embedded macro call introduces other possible
10644 interesting quotations:
10646 @example
10647 car(active)
10648 @result{}ACT
10649 car([active])
10650 @result{}ACT, IVE
10651 car([[active]])
10652 @result{}active
10653 @end example
10655 In the first case, the top level looks for the arguments of @code{car},
10656 and finds @samp{active}.  Because M4 evaluates its arguments
10657 before applying the macro, @samp{active} is expanded, which results in:
10659 @example
10660 car(ACT, IVE)
10661 @result{}ACT
10662 @end example
10664 @noindent
10665 In the second case, the top level gives @samp{active} as first and only
10666 argument of @code{car}, which results in:
10668 @example
10669 active
10670 @result{}ACT, IVE
10671 @end example
10673 @noindent
10674 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10675 In the third case, @code{car} receives @samp{[active]}, which results in:
10677 @example
10678 [active]
10679 @result{}active
10680 @end example
10682 @noindent
10683 exactly as we already saw above.
10685 The example above, applied to a more realistic example, gives:
10687 @example
10688 car(int tab[10];)
10689 @result{}int tab10;
10690 car([int tab[10];])
10691 @result{}int tab10;
10692 car([[int tab[10];]])
10693 @result{}int tab[10];
10694 @end example
10696 @noindent
10697 Huh?  The first case is easily understood, but why is the second wrong,
10698 and the third right?  To understand that, you must know that after
10699 M4 expands a macro, the resulting text is immediately subjected
10700 to macro expansion and quote removal.  This means that the quote removal
10701 occurs twice---first before the argument is passed to the @code{car}
10702 macro, and second after the @code{car} macro expands to the first
10703 argument.
10705 As the author of the Autoconf macro @code{car}, you then consider it to
10706 be incorrect that your users have to double-quote the arguments of
10707 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10708 quoted car:
10710 @example
10711 define([qar], [[$1]])
10712 @end example
10714 @noindent
10715 and check that @code{qar} is properly fixed:
10717 @example
10718 qar([int tab[10];])
10719 @result{}int tab[10];
10720 @end example
10722 @noindent
10723 Ahhh!  That's much better.
10725 But note what you've done: now that the result of @code{qar} is always
10726 a literal string, the only time a user can use nested macros is if she
10727 relies on an @emph{unquoted} macro call:
10729 @example
10730 qar(active)
10731 @result{}ACT
10732 qar([active])
10733 @result{}active
10734 @end example
10736 @noindent
10737 leaving no way for her to reproduce what she used to do with @code{car}:
10739 @example
10740 car([active])
10741 @result{}ACT, IVE
10742 @end example
10744 @noindent
10745 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10746 macros:
10748 @example
10749 define([my_includes], [#include <stdio.h>])
10750 car([my_includes])
10751 @result{}#include <stdio.h>
10752 qar(my_includes)
10753 @error{}EOF in argument list
10754 @end example
10756 This macro, @code{qar}, because it double quotes its arguments, forces
10757 its users to leave their macro calls unquoted, which is dangerous.
10758 Commas and other active symbols are interpreted by M4 before
10759 they are given to the macro, often not in the way the users expect.
10760 Also, because @code{qar} behaves differently from the other macros,
10761 it's an exception that should be avoided in Autoconf.
10763 @node Changequote is Evil
10764 @subsection @code{changequote} is Evil
10765 @cindex @code{changequote}
10767 The temptation is often high to bypass proper quotation, in particular
10768 when it's late at night.  Then, many experienced Autoconf hackers
10769 finally surrender to the dark side of the force and use the ultimate
10770 weapon: @code{changequote}.
10772 The M4 builtin @code{changequote} belongs to a set of primitives that
10773 allow one to adjust the syntax of the language to adjust it to one's
10774 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10775 quotes, but in the context of shell programming (and actually of most
10776 programming languages), that's about the worst choice one can make:
10777 because of strings and back-quoted expressions in shell code (such as
10778 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10779 programming languages (as in @samp{'0'}), there are many unbalanced
10780 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10781 not impossible.  In order to make M4 useful in such a context, its
10782 designers have equipped it with @code{changequote}, which makes it
10783 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10784 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10785 because they are unlikely characters, but @emph{because they are
10786 characters unlikely to be unbalanced}.
10788 There are other magic primitives, such as @code{changecom} to specify
10789 what syntactic forms are comments (it is common to see
10790 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10791 @code{changeword} and @code{changesyntax} to change other syntactic
10792 details (such as the character to denote the @var{n}th argument, @samp{$} by
10793 default, the parentheses around arguments, etc.).
10795 These primitives are really meant to make M4 more useful for specific
10796 domains: they should be considered like command line options:
10797 @option{--quotes}, @option{--comments}, @option{--words}, and
10798 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10799 it makes M4 libraries self contained (no need for additional options).
10801 There lies the problem@enddots{}
10803 @sp 1
10805 The problem is that it is then tempting to use them in the middle of an
10806 M4 script, as opposed to its initialization.  This, if not carefully
10807 thought out, can lead to disastrous effects: @emph{you are changing the
10808 language in the middle of the execution}.  Changing and restoring the
10809 syntax is often not enough: if you happened to invoke macros in between,
10810 these macros are lost, as the current syntax is probably not
10811 the one they were implemented with.
10813 @c FIXME: I've been looking for a short, real case example, but I
10814 @c lost them all :(
10817 @node Quadrigraphs
10818 @subsection Quadrigraphs
10819 @cindex quadrigraphs
10820 @cindex @samp{@@S|@@}
10821 @cindex @samp{@@&t@@}
10822 @c Info cannot handle ':' in index entries.
10823 @ifnotinfo
10824 @cindex @samp{@@<:@@}
10825 @cindex @samp{@@:>@@}
10826 @cindex @samp{@@%:@@}
10827 @cindex @samp{@@@{:@@}
10828 @cindex @samp{@@:@}@@}
10829 @end ifnotinfo
10831 When writing an Autoconf macro you may occasionally need to generate
10832 special characters that are difficult to express with the standard
10833 Autoconf quoting rules.  For example, you may need to output the regular
10834 expression @samp{[^[]}, which matches any character other than @samp{[}.
10835 This expression contains unbalanced brackets so it cannot be put easily
10836 into an M4 macro.
10838 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10839 and @code{m4_expand}) which internally use special markers in addition
10840 to the regular quoting characters.  If the arguments to these macros
10841 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10842 might behave incorrectly.
10844 You can work around these problems by using one of the following
10845 @dfn{quadrigraphs}:
10847 @table @samp
10848 @item @@<:@@
10849 @samp{[}
10850 @item @@:>@@
10851 @samp{]}
10852 @item @@S|@@
10853 @samp{$}
10854 @item @@%:@@
10855 @samp{#}
10856 @item @@@{:@@
10857 @samp{(}
10858 @item @@:@}@@
10859 @samp{)}
10860 @item @@&t@@
10861 Expands to nothing.
10862 @end table
10864 Quadrigraphs are replaced at a late stage of the translation process,
10865 after @command{m4} is run, so they do not get in the way of M4 quoting.
10866 For example, the string @samp{^@@<:@@}, independently of its quotation,
10867 appears as @samp{^[} in the output.
10869 The empty quadrigraph can be used:
10871 @itemize @minus
10872 @item to mark trailing spaces explicitly
10874 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10876 @item to produce quadrigraphs and other strings reserved by m4sugar
10878 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10879 contrived example:
10881 @example
10882 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10883 m4_split([a )@}>=- b -=<@{( c])
10884 @result{}[a], [], [B], [], [c]
10885 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10886 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10887 @end example
10889 @item to escape @emph{occurrences} of forbidden patterns
10891 For instance you might want to mention @code{AC_FOO} in a comment, while
10892 still being sure that @command{autom4te} still catches unexpanded
10893 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10894 @end itemize
10896 The name @samp{@@&t@@} was suggested by Paul Eggert:
10898 @quotation
10899 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10900 own invention, but the @samp{t} came from the source code of the
10901 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10902 and which used @samp{mt} to denote the empty string.  In C, it would
10903 have looked like something like:
10905 @example
10906 char const mt[] = "";
10907 @end example
10909 @noindent
10910 but of course the source code was written in Algol 68.
10912 I don't know where he got @samp{mt} from: it could have been his own
10913 invention, and I suppose it could have been a common pun around the
10914 Cambridge University computer lab at the time.
10915 @end quotation
10918 @node Balancing Parentheses
10919 @subsection Dealing with unbalanced parentheses
10920 @cindex balancing parentheses
10921 @cindex parentheses, balancing
10922 @cindex unbalanced parentheses, managing
10924 One of the pitfalls of portable shell programming is that @command{case}
10925 statements require unbalanced parentheses (@pxref{case, , Limitations of
10926 Shell Builtins}).  With syntax highlighting
10927 editors, the presence of unbalanced @samp{)} can interfere with editors
10928 that perform syntax highlighting of macro contents based on finding the
10929 matching @samp{(}.  Another concern is how much editing must be done
10930 when transferring code snippets between shell scripts and macro
10931 definitions.  But most importantly, the presence of unbalanced
10932 parentheses can introduce expansion bugs.
10934 For an example, here is an underquoted attempt to use the macro
10935 @code{my_case}, which happens to expand to a portable @command{case}
10936 statement:
10938 @example
10939 AC_DEFUN([my_case],
10940 [case $file_name in
10941   *.c) echo "C source code";;
10942 esac])
10943 AS_IF(:, my_case)
10944 @end example
10946 @noindent
10947 In the above example, the @code{AS_IF} call underquotes its arguments.
10948 As a result, the unbalanced @samp{)} generated by the premature
10949 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10950 truncated parameter, and the expansion is syntactically invalid:
10952 @example
10953 if :; then
10954   case $file_name in
10955   *.c
10956 fi echo "C source code";;
10957 esac)
10958 @end example
10960 If nothing else, this should emphasize the importance of the quoting
10961 arguments to macro calls.  On the other hand, there are several
10962 variations for defining @code{my_case} to be more robust, even when used
10963 without proper quoting, each with some benefits and some drawbacks.
10965 @itemize @w{}
10966 @item Creative literal shell comment
10967 @example
10968 AC_DEFUN([my_case],
10969 [case $file_name in #(
10970   *.c) echo "C source code";;
10971 esac])
10972 @end example
10973 @noindent
10974 This version provides balanced parentheses to several editors, and can
10975 be copied and pasted into a terminal as is.  Unfortunately, it is still
10976 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10977 that masks the normal properties of @samp{(}.
10979 @item Quadrigraph shell comment
10980 @example
10981 AC_DEFUN([my_case],
10982 [case $file_name in @@%:@@(
10983   *.c) echo "C source code";;
10984 esac])
10985 @end example
10986 @noindent
10987 This version provides balanced parentheses to even more editors, and can
10988 be used as a balanced Autoconf argument.  Unfortunately, it requires
10989 some editing before it can be copied and pasted into a terminal, and the
10990 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10992 @item Quoting just the parenthesis
10993 @example
10994 AC_DEFUN([my_case],
10995 [case $file_name in
10996   *.c[)] echo "C source code";;
10997 esac])
10998 @end example
10999 @noindent
11000 This version quotes the @samp{)}, so that it can be used as a balanced
11001 Autoconf argument.  As written, this is not balanced to an editor, but
11002 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
11003 still requires some edits before it can be copied and pasted into a
11004 terminal.
11006 @item Double-quoting the entire statement
11007 @example
11008 AC_DEFUN([my_case],
11009 [[case $file_name in #(
11010   *.c) echo "C source code";;
11011 esac]])
11012 @end example
11013 @noindent
11014 Since the entire macro is double-quoted, there is no problem with using
11015 this as an Autoconf argument; and since the double-quoting is over the
11016 entire statement, this code can be easily copied and pasted into a
11017 terminal.  However, the double quoting prevents the expansion of any
11018 macros inside the case statement, which may cause its own set of
11019 problems.
11021 @item Using @code{AS_CASE}
11022 @example
11023 AC_DEFUN([my_case],
11024 [AS_CASE([$file_name],
11025   [*.c], [echo "C source code"])])
11026 @end example
11027 @noindent
11028 This version avoids the balancing issue altogether, by relying on
11029 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
11030 expansion of @code{AC_REQUIRE} to occur prior to the entire case
11031 statement, rather than within a branch of the case statement that might
11032 not be taken.  However, the abstraction comes with a penalty that it is
11033 no longer a quick copy, paste, and edit to get back to shell code.
11034 @end itemize
11037 @node Quotation Rule Of Thumb
11038 @subsection Quotation Rule Of Thumb
11040 To conclude, the quotation rule of thumb is:
11042 @center @emph{One pair of quotes per pair of parentheses.}
11044 Never over-quote, never under-quote, in particular in the definition of
11045 macros.  In the few places where the macros need to use brackets
11046 (usually in C program text or regular expressions), properly quote
11047 @emph{the arguments}!
11049 It is common to read Autoconf programs with snippets like:
11051 @example
11052 AC_TRY_LINK(
11053 changequote(<<, >>)dnl
11054 <<#include <time.h>
11055 #ifndef tzname /* For SGI.  */
11056 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11057 #endif>>,
11058 changequote([, ])dnl
11059 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11060 @end example
11062 @noindent
11063 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11064 double quoting, so you just need:
11066 @example
11067 AC_TRY_LINK(
11068 [#include <time.h>
11069 #ifndef tzname /* For SGI.  */
11070 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11071 #endif],
11072             [atoi (*tzname);],
11073             [ac_cv_var_tzname=yes],
11074             [ac_cv_var_tzname=no])
11075 @end example
11077 @noindent
11078 The M4-fluent reader might note that these two examples are rigorously
11079 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11080 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11081 quotes are not part of the arguments!
11083 Simplified, the example above is just doing this:
11085 @example
11086 changequote(<<, >>)dnl
11087 <<[]>>
11088 changequote([, ])dnl
11089 @end example
11091 @noindent
11092 instead of simply:
11094 @example
11095 [[]]
11096 @end example
11098 With macros that do not double quote their arguments (which is the
11099 rule), double-quote the (risky) literals:
11101 @example
11102 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11103 [[#include <time.h>
11104 #ifndef tzname /* For SGI.  */
11105 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11106 #endif]],
11107                                 [atoi (*tzname);])],
11108                [ac_cv_var_tzname=yes],
11109                [ac_cv_var_tzname=no])
11110 @end example
11112 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11113 should be using @code{AC_LINK_IFELSE} instead.
11115 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11116 where quoting does not suffice.
11118 When you create a @command{configure} script using newly written macros,
11119 examine it carefully to check whether you need to add more quotes in
11120 your macros.  If one or more words have disappeared in the M4
11121 output, you need more quotes.  When in doubt, quote.
11123 However, it's also possible to put on too many layers of quotes.  If
11124 this happens, the resulting @command{configure} script may contain
11125 unexpanded macros.  The @command{autoconf} program checks for this problem
11126 by looking for the string @samp{AC_} in @file{configure}.  However, this
11127 heuristic does not work in general: for example, it does not catch
11128 overquoting in @code{AC_DEFINE} descriptions.
11131 @c ---------------------------------------- Using autom4te
11133 @node Using autom4te
11134 @section Using @command{autom4te}
11136 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11137 to Autoconf per se, heavily rely on M4.  All these different uses
11138 revealed common needs factored into a layer over M4:
11139 @command{autom4te}@footnote{
11141 Yet another great name from Lars J. Aas.
11145 @command{autom4te} is a preprocessor that is like @command{m4}.
11146 It supports M4 extensions designed for use in tools like Autoconf.
11148 @menu
11149 * autom4te Invocation::         A GNU M4 wrapper
11150 * Customizing autom4te::        Customizing the Autoconf package
11151 @end menu
11153 @node autom4te Invocation
11154 @subsection Invoking @command{autom4te}
11156 The command line arguments are modeled after M4's:
11158 @example
11159 autom4te @var{options} @var{files}
11160 @end example
11162 @noindent
11163 @evindex M4
11164 where the @var{files} are directly passed to @command{m4}.  By default,
11165 GNU M4 is found during configuration, but the environment
11166 variable
11167 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11168 to the regular expansion, it handles the replacement of the quadrigraphs
11169 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11170 output.  It supports an extended syntax for the @var{files}:
11172 @table @file
11173 @item @var{file}.m4f
11174 This file is an M4 frozen file.  Note that @emph{all the previous files
11175 are ignored}.  See the option @option{--melt} for the rationale.
11177 @item @var{file}?
11178 If found in the library path, the @var{file} is included for expansion,
11179 otherwise it is ignored instead of triggering a failure.
11180 @end table
11182 @sp 1
11184 Of course, it supports the Autoconf common subset of options:
11186 @table @option
11187 @item --help
11188 @itemx -h
11189 Print a summary of the command line options and exit.
11191 @item --version
11192 @itemx -V
11193 Print the version number of Autoconf and exit.
11195 @item --verbose
11196 @itemx -v
11197 Report processing steps.
11199 @item --debug
11200 @itemx -d
11201 Don't remove the temporary files and be even more verbose.
11203 @item --include=@var{dir}
11204 @itemx -I @var{dir}
11205 Also look for input files in @var{dir}.  Multiple invocations
11206 accumulate.
11208 @item --output=@var{file}
11209 @itemx -o @var{file}
11210 Save output (script or trace) to @var{file}.  The file @option{-} stands
11211 for the standard output.
11212 @end table
11214 @sp 1
11216 As an extension of @command{m4}, it includes the following options:
11218 @table @option
11219 @item --warnings=@var{category}
11220 @itemx -W @var{category}
11221 @evindex WARNINGS
11222 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11223 Report the warnings related to @var{category} (which can actually be a
11224 comma separated list).  @xref{Reporting Messages}, macro
11225 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11226 values include:
11228 @table @samp
11229 @item all
11230 report all the warnings
11232 @item none
11233 report none
11235 @item error
11236 treats warnings as errors
11238 @item no-@var{category}
11239 disable warnings falling into @var{category}
11240 @end table
11242 Warnings about @samp{syntax} are enabled by default, and the environment
11243 variable @env{WARNINGS}, a comma separated list of categories, is
11244 honored.  @samp{autom4te -W @var{category}} actually
11245 behaves as if you had run:
11247 @example
11248 autom4te --warnings=syntax,$WARNINGS,@var{category}
11249 @end example
11251 @noindent
11252 For example, if you want to disable defaults and @env{WARNINGS}
11253 of @command{autom4te}, but enable the warnings about obsolete
11254 constructs, you would use @option{-W none,obsolete}.
11256 @cindex Back trace
11257 @cindex Macro invocation stack
11258 @command{autom4te} displays a back trace for errors, but not for
11259 warnings; if you want them, just pass @option{-W error}.
11261 @item --melt
11262 @itemx -M
11263 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11264 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11265 are executed only when the files are frozen, typically
11266 @code{m4_define}.  For instance, running:
11268 @example
11269 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11270 @end example
11272 @noindent
11273 is roughly equivalent to running:
11275 @example
11276 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11277 @end example
11279 @noindent
11280 while
11282 @example
11283 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11284 @end example
11286 @noindent
11287 is equivalent to:
11289 @example
11290 m4 --reload-state=4.m4f input.m4
11291 @end example
11293 @item --freeze
11294 @itemx -F
11295 Produce a frozen state file.  @command{autom4te} freezing is stricter
11296 than M4's: it must produce no warnings, and no output other than empty
11297 lines (a line with white space is @emph{not} empty) and comments
11298 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11299 this option takes no argument:
11301 @example
11302 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11303 @end example
11305 @noindent
11306 corresponds to
11308 @example
11309 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11310 @end example
11312 @item --mode=@var{octal-mode}
11313 @itemx -m @var{octal-mode}
11314 Set the mode of the non-traces output to @var{octal-mode}; by default
11315 @samp{0666}.
11316 @end table
11318 @sp 1
11320 @cindex @file{autom4te.cache}
11321 As another additional feature over @command{m4}, @command{autom4te}
11322 caches its results.  GNU M4 is able to produce a regular
11323 output and traces at the same time.  Traces are heavily used in the
11324 GNU Build System: @command{autoheader} uses them to build
11325 @file{config.h.in}, @command{autoreconf} to determine what
11326 GNU Build System components are used, @command{automake} to
11327 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11328 traces are cached while performing regular expansion,
11329 and conversely.  This cache is (actually, the caches are) stored in
11330 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11331 at any moment (especially if for some reason @command{autom4te}
11332 considers it trashed).
11334 @table @option
11335 @item --cache=@var{directory}
11336 @itemx -C @var{directory}
11337 Specify the name of the directory where the result should be cached.
11338 Passing an empty value disables caching.  Be sure to pass a relative
11339 file name, as for the time being, global caches are not supported.
11341 @item --no-cache
11342 Don't cache the results.
11344 @item --force
11345 @itemx -f
11346 If a cache is used, consider it obsolete (but update it anyway).
11347 @end table
11349 @sp 1
11351 Because traces are so important to the GNU Build System,
11352 @command{autom4te} provides high level tracing features as compared to
11353 M4, and helps exploiting the cache:
11355 @table @option
11356 @item --trace=@var{macro}[:@var{format}]
11357 @itemx -t @var{macro}[:@var{format}]
11358 Trace the invocations of @var{macro} according to the @var{format}.
11359 Multiple @option{--trace} arguments can be used to list several macros.
11360 Multiple @option{--trace} arguments for a single macro are not
11361 cumulative; instead, you should just make @var{format} as long as
11362 needed.
11364 The @var{format} is a regular string, with newlines if desired, and
11365 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11366 use the following special escapes:
11368 @table @samp
11369 @item $$
11370 @c $$ restore font-lock
11371 The character @samp{$}.
11373 @item $f
11374 The file name from which @var{macro} is called.
11376 @item $l
11377 The line number from which @var{macro} is called.
11379 @item $d
11380 The depth of the @var{macro} call.  This is an M4 technical detail that
11381 you probably don't want to know about.
11383 @item $n
11384 The name of the @var{macro}.
11386 @item $@var{num}
11387 The @var{num}th argument of the call to @var{macro}.
11389 @item $@@
11390 @itemx $@var{sep}@@
11391 @itemx $@{@var{separator}@}@@
11392 All the arguments passed to @var{macro}, separated by the character
11393 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11394 argument is quoted, i.e., enclosed in a pair of square brackets.
11396 @item $*
11397 @itemx $@var{sep}*
11398 @itemx $@{@var{separator}@}*
11399 As above, but the arguments are not quoted.
11401 @item $%
11402 @itemx $@var{sep}%
11403 @itemx $@{@var{separator}@}%
11404 As above, but the arguments are not quoted, all new line characters in
11405 the arguments are smashed, and the default separator is @samp{:}.
11407 The escape @samp{$%} produces single-line trace outputs (unless you put
11408 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11409 not.
11410 @end table
11412 @xref{autoconf Invocation}, for examples of trace uses.
11414 @item --preselect=@var{macro}
11415 @itemx -p @var{macro}
11416 Cache the traces of @var{macro}, but do not enable traces.  This is
11417 especially important to save CPU cycles in the future.  For instance,
11418 when invoked, @command{autoconf} preselects all the macros that
11419 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11420 trace, so that running @command{m4} is not needed to trace them: the
11421 cache suffices.  This results in a huge speed-up.
11422 @end table
11424 @sp 1
11426 @cindex Autom4te Library
11427 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11428 libraries}.  They consists in a powerful yet extremely simple feature:
11429 sets of combined command line arguments:
11431 @table @option
11432 @item --language=@var{language}
11433 @itemx -l @var{language}
11434 Use the @var{language} Autom4te library.  Current languages include:
11436 @table @code
11437 @item M4sugar
11438 create M4sugar output.
11440 @item M4sh
11441 create M4sh executable shell scripts.
11443 @item Autotest
11444 create Autotest executable test suites.
11446 @item Autoconf-without-aclocal-m4
11447 create Autoconf executable configure scripts without
11448 reading @file{aclocal.m4}.
11450 @item Autoconf
11451 create Autoconf executable configure scripts.  This language inherits
11452 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11453 additionally reads @file{aclocal.m4}.
11454 @end table
11456 @item --prepend-include=@var{dir}
11457 @itemx -B @var{dir}
11458 Prepend directory @var{dir} to the search path.  This is used to include
11459 the language-specific files before any third-party macros.
11461 @end table
11463 @cindex @file{autom4te.cfg}
11464 As an example, if Autoconf is installed in its default location,
11465 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11466 strictly equivalent to the command:
11468 @example
11469 autom4te --prepend-include /usr/local/share/autoconf \
11470   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11471 @end example
11473 @noindent
11474 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11475 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11476 foo.m4}, i.e.:
11478 @example
11479 autom4te --prepend-include /usr/local/share/autoconf \
11480   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11481 @end example
11483 @noindent
11484 The definition of the languages is stored in @file{autom4te.cfg}.
11486 @node Customizing autom4te
11487 @subsection Customizing @command{autom4te}
11489 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11490 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11491 as found in the directory from which @command{autom4te} is run).  The
11492 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11493 then @file{./.autom4te.cfg}, and finally the command line arguments.
11495 In these text files, comments are introduced with @code{#}, and empty
11496 lines are ignored.  Customization is performed on a per-language basis,
11497 wrapped in between a @samp{begin-language: "@var{language}"},
11498 @samp{end-language: "@var{language}"} pair.
11500 Customizing a language stands for appending options (@pxref{autom4te
11501 Invocation}) to the current definition of the language.  Options, and
11502 more generally arguments, are introduced by @samp{args:
11503 @var{arguments}}.  You may use the traditional shell syntax to quote the
11504 @var{arguments}.
11506 As an example, to disable Autoconf caches (@file{autom4te.cache})
11507 globally, include the following lines in @file{~/.autom4te.cfg}:
11509 @verbatim
11510 ## ------------------ ##
11511 ## User Preferences.  ##
11512 ## ------------------ ##
11514 begin-language: "Autoconf-without-aclocal-m4"
11515 args: --no-cache
11516 end-language: "Autoconf-without-aclocal-m4"
11517 @end verbatim
11520 @node Programming in M4sugar
11521 @section Programming in M4sugar
11523 @cindex M4sugar
11524 M4 by itself provides only a small, but sufficient, set of all-purpose
11525 macros.  M4sugar introduces additional generic macros.  Its name was
11526 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11527 M4sugar''.
11529 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11530 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11531 define your own macros into these namespaces.
11533 @menu
11534 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11535 * Diagnostic Macros::           Diagnostic messages from M4sugar
11536 * Diversion support::           Diversions in M4sugar
11537 * Conditional constructs::      Conditions in M4
11538 * Looping constructs::          Iteration in M4
11539 * Evaluation Macros::           More quotation and evaluation control
11540 * Text processing Macros::      String manipulation in M4
11541 * Number processing Macros::    Arithmetic computation in M4
11542 * Set manipulation Macros::     Set manipulation in M4
11543 * Forbidden Patterns::          Catching unexpanded macros
11544 @end menu
11546 @node Redefined M4 Macros
11547 @subsection Redefined M4 Macros
11549 @msindex{builtin}
11550 @msindex{changecom}
11551 @msindex{changequote}
11552 @msindex{debugfile}
11553 @msindex{debugmode}
11554 @msindex{decr}
11555 @msindex{define}
11556 @msindex{divnum}
11557 @msindex{errprint}
11558 @msindex{esyscmd}
11559 @msindex{eval}
11560 @msindex{format}
11561 @msindex{ifdef}
11562 @msindex{incr}
11563 @msindex{index}
11564 @msindex{indir}
11565 @msindex{len}
11566 @msindex{pushdef}
11567 @msindex{shift}
11568 @msindex{substr}
11569 @msindex{syscmd}
11570 @msindex{sysval}
11571 @msindex{traceoff}
11572 @msindex{traceon}
11573 @msindex{translit}
11574 With a few exceptions, all the M4 native macros are moved in the
11575 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11576 @code{m4_define} etc.
11578 The list of macros unchanged from M4, except for their name, is:
11579 @itemize @minus
11580 @item m4_builtin
11581 @item m4_changecom
11582 @item m4_changequote
11583 @item m4_debugfile
11584 @item m4_debugmode
11585 @item m4_decr
11586 @item m4_define
11587 @item m4_divnum
11588 @item m4_errprint
11589 @item m4_esyscmd
11590 @item m4_eval
11591 @item m4_format
11592 @item m4_ifdef
11593 @item m4_incr
11594 @item m4_index
11595 @item m4_indir
11596 @item m4_len
11597 @item m4_pushdef
11598 @item m4_shift
11599 @item m4_substr
11600 @item m4_syscmd
11601 @item m4_sysval
11602 @item m4_traceoff
11603 @item m4_traceon
11604 @item m4_translit
11605 @end itemize
11607 Some M4 macros are redefined, and are slightly incompatible with their
11608 native equivalent.
11610 @defmac __file__
11611 @defmacx __line__
11612 @MSindex __file__
11613 @MSindex __line__
11614 All M4 macros starting with @samp{__} retain their original name: for
11615 example, no @code{m4__file__} is defined.
11616 @end defmac
11618 @defmac __oline__
11619 @MSindex __oline__
11620 This is not technically a macro, but a feature of Autom4te.  The
11621 sequence @code{__oline__} can be used similarly to the other m4sugar
11622 location macros, but rather than expanding to the location of the input
11623 file, it is translated to the line number where it appears in the output
11624 file after all other M4 expansions.
11625 @end defmac
11627 @defmac dnl
11628 @MSindex dnl
11629 This macro kept its original name: no @code{m4_dnl} is defined.
11630 @end defmac
11632 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11633 @msindex{bpatsubst}
11634 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11635 is kept for future versions of M4sugar, once GNU M4 2.0 is
11636 released and supports extended regular expression syntax.
11637 @end defmac
11639 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11640 @msindex{bregexp}
11641 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11642 is kept for future versions of M4sugar, once GNU M4 2.0 is
11643 released and supports extended regular expression syntax.
11644 @end defmac
11646 @defmac m4_copy (@var{source}, @var{dest})
11647 @defmacx m4_copy_force (@var{source}, @var{dest})
11648 @defmacx m4_rename (@var{source}, @var{dest})
11649 @defmacx m4_rename_force (@var{source}, @var{dest})
11650 @msindex{copy}
11651 @msindex{copy_force}
11652 @msindex{rename}
11653 @msindex{rename_force}
11654 These macros aren't directly builtins, but are closely related to
11655 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11656 @code{m4_rename} ensure that @var{dest} is undefined, while
11657 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11658 definition.  All four macros then proceed to copy the entire pushdef
11659 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11660 and @code{m4_copy_force} preserve the source (including in the special
11661 case where @var{source} is undefined), while @code{m4_rename} and
11662 @code{m4_rename_force} undefine the original macro name (making it an
11663 error to rename an undefined @var{source}).
11665 Note that attempting to invoke a renamed macro might not work, since the
11666 macro may have a dependence on helper macros accessed via composition of
11667 @samp{$0} but that were not also renamed; likewise, other macros may
11668 have a hard-coded dependence on @var{source} and could break if
11669 @var{source} has been deleted.  On the other hand, it is always safe to
11670 rename a macro to temporarily move it out of the way, then rename it
11671 back later to restore original semantics.
11672 @end defmac
11674 @defmac m4_defn (@var{macro}@dots{})
11675 @msindex{defn}
11676 This macro fails if @var{macro} is not defined, even when using older
11677 versions of M4 that did not warn.  See @code{m4_undefine}.
11678 Unfortunately, in order to support these older versions of M4, there are
11679 some situations involving unbalanced quotes where concatenating multiple
11680 macros together will work in newer M4 but not in m4sugar; use
11681 quadrigraphs to work around this.
11682 @end defmac
11684 @defmac m4_divert (@var{diversion})
11685 @msindex{divert}
11686 M4sugar relies heavily on diversions, so rather than behaving as a
11687 primitive, @code{m4_divert} behaves like:
11688 @example
11689 m4_divert_pop()m4_divert_push([@var{diversion}])
11690 @end example
11691 @noindent
11692 @xref{Diversion support}, for more details about the use of the
11693 diversion stack.  In particular, this implies that @var{diversion}
11694 should be a named diversion rather than a raw number.  But be aware that
11695 it is seldom necessary to explicitly change the diversion stack, and
11696 that when done incorrectly, it can lead to syntactically invalid
11697 scripts.
11698 @end defmac
11700 @defmac m4_dumpdef (@var{name}@dots{})
11701 @defmacx m4_dumpdefs (@var{name}@dots{})
11702 @msindex{dumpdef}
11703 @msindex{dumpdefs}
11704 @code{m4_dumpdef} is like the M4 builtin, except that this version
11705 requires at least one argument, output always goes to standard error
11706 rather than the current debug file, no sorting is done on multiple
11707 arguments, and an error is issued if any
11708 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11709 calls @code{m4_dumpdef} for all of the
11710 @code{m4_pushdef} stack of definitions, starting with the current, and
11711 silently does nothing if @var{name} is undefined.
11713 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11714 builtin is output as the empty string.  This behavior is rectified by
11715 using M4 1.6 or newer.  However, this behavior difference means that
11716 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11717 and never in the final published form of a macro.
11718 @end defmac
11720 @defmac m4_esyscmd_s (@var{command})
11721 @msindex{esyscmd_s}
11722 Like @code{m4_esyscmd}, this macro expands to the result of running
11723 @var{command} in a shell.  The difference is that any trailing newlines
11724 are removed, so that the output behaves more like shell command
11725 substitution.
11726 @end defmac
11728 @defmac m4_exit (@var{exit-status})
11729 @msindex{exit}
11730 This macro corresponds to @code{m4exit}.
11731 @end defmac
11733 @defmac m4_if (@var{comment})
11734 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11735 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11736   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11737 @msindex{if}
11738 This macro corresponds to @code{ifelse}.  @var{string-1} and
11739 @var{string-2} are compared literally, so usually one of the two
11740 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11741 conditional idioms.
11742 @end defmac
11744 @defmac m4_include (@var{file})
11745 @defmacx m4_sinclude (@var{file})
11746 @msindex{include}
11747 @msindex{sinclude}
11748 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11749 @end defmac
11751 @defmac m4_mkstemp (@var{template})
11752 @defmacx m4_maketemp (@var{template})
11753 @msindex{maketemp}
11754 @msindex{mkstemp}
11755 Posix requires @code{maketemp} to replace the trailing @samp{X}
11756 characters in @var{template} with the process id, without regards to the
11757 existence of a file by that name, but this a security hole.  When this
11758 was pointed out to the Posix folks, they agreed to invent a new macro
11759 @code{mkstemp} that always creates a uniquely named file, but not all
11760 versions of GNU M4 support the new macro.  In M4sugar,
11761 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11762 and both have the secure semantics regardless of which macro the
11763 underlying M4 provides.
11764 @end defmac
11766 @defmac m4_popdef (@var{macro}@dots{})
11767 @msindex{popdef}
11768 This macro fails if @var{macro} is not defined, even when using older
11769 versions of M4 that did not warn.  See @code{m4_undefine}.
11770 @end defmac
11772 @defmac m4_undefine (@var{macro}@dots{})
11773 @msindex{undefine}
11774 This macro fails if @var{macro} is not defined, even when using older
11775 versions of M4 that did not warn.  Use
11777 @example
11778 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11779 @end example
11781 @noindent
11782 if you are not sure whether @var{macro} is defined.
11783 @end defmac
11785 @defmac m4_undivert (@var{diversion}@dots{})
11786 @msindex{undivert}
11787 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11788 Also, since the M4sugar diversion stack prefers named
11789 diversions, the use of @code{m4_undivert} to include files is risky.
11790 @xref{Diversion support}, for more details about the use of the
11791 diversion stack.  But be aware that it is seldom necessary to explicitly
11792 change the diversion stack, and that when done incorrectly, it can lead
11793 to syntactically invalid scripts.
11794 @end defmac
11796 @defmac m4_wrap (@var{text})
11797 @defmacx m4_wrap_lifo (@var{text})
11798 @msindex{wrap}
11799 @msindex{wrap_lifo}
11800 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11801 multiple wrap calls to be reprocessed at EOF in the same order
11802 as the original calls (first-in, first-out).  GNU M4 versions
11803 through 1.4.10, however, reprocess them in reverse order (last-in,
11804 first-out).  Both orders are useful, therefore, you can rely on
11805 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11806 LIFO semantics, regardless of the underlying GNU M4 version.
11808 Unlike the GNU M4 builtin, these macros only recognize one
11809 argument, and avoid token pasting between consecutive invocations.  On
11810 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11811 work just as in the builtin.
11812 @end defmac
11815 @node Diagnostic Macros
11816 @subsection Diagnostic messages from M4sugar
11817 @cindex Messages, from @command{M4sugar}
11819 When macros statically diagnose abnormal situations, benign or fatal,
11820 they should report them using these macros.  For issuing dynamic issues,
11821 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11823 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11824 @msindex{assert}
11825 Assert that the arithmetic @var{expression} evaluates to non-zero.
11826 Otherwise, issue a fatal error, and exit @command{autom4te} with
11827 @var{exit-status}.
11828 @end defmac
11830 @defmac m4_errprintn (@var{message})
11831 @msindex{errprintn}
11832 Similar to the builtin @code{m4_errprint}, except that a newline is
11833 guaranteed after @var{message}.
11834 @end defmac
11836 @anchor{m4_fatal}
11837 @defmac m4_fatal (@var{message})
11838 @msindex{fatal}
11839 Report a severe error @var{message} prefixed with the current location,
11840 and have @command{autom4te} die.
11841 @end defmac
11843 @defmac m4_location
11844 @msindex{location}
11845 Useful as a prefix in a message line.  Short for:
11846 @example
11847 __file__:__line__
11848 @end example
11849 @end defmac
11851 @anchor{m4_warn}
11852 @defmac m4_warn (@var{category}, @var{message})
11853 @msindex{warn}
11854 Report @var{message} as a warning (or as an error if requested by the
11855 user) if warnings of the @var{category} are turned on.  If the message
11856 is emitted, it is prefixed with the current location, and followed by a
11857 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11858 current expansion.  You are encouraged to use standard categories, which
11859 currently include:
11861 @table @samp
11862 @item all
11863 messages that don't fall into one of the following categories.  Use of an
11864 empty @var{category} is equivalent.
11866 @item cross
11867 related to cross compilation issues.
11869 @item obsolete
11870 use of an obsolete construct.
11872 @item syntax
11873 dubious syntactic constructs, incorrectly ordered macro calls.
11874 @end table
11875 @end defmac
11878 @node Diversion support
11879 @subsection Diversion support
11881 M4sugar makes heavy use of diversions under the hood, because it is
11882 often the case that
11883 text that must appear early in the output is not discovered until late
11884 in the input.  Additionally, some of the topological sorting algorithms
11885 used in resolving macro dependencies use diversions.  However, most
11886 macros should not need to change diversions directly, but rather rely on
11887 higher-level M4sugar macros to manage diversions transparently.  If you
11888 change diversions improperly, you risk generating a syntactically
11889 invalid script, because an incorrect diversion will violate assumptions
11890 made by many macros about whether prerequisite text has been previously
11891 output.  In short, if you manually change the diversion, you should not
11892 expect any macros provided by the Autoconf package to work until you
11893 have restored the diversion stack back to its original state.
11895 In the rare case that it is necessary to write a macro that explicitly
11896 outputs text to a different diversion, it is important to be aware of an
11897 M4 limitation regarding diversions: text only goes to a diversion if it
11898 is not part of argument collection.  Therefore, any macro that changes
11899 the current diversion cannot be used as an unquoted argument to another
11900 macro, but must be expanded at the top level.  The macro
11901 @code{m4_expand} will diagnose any attempt to change diversions, since
11902 it is generally useful only as an argument to another macro.  The
11903 following example shows what happens when diversion manipulation is
11904 attempted within macro arguments:
11906 @example
11907 m4_do([normal text]
11908 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11909 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11910 @result{}normal text
11911 @result{}unwanted
11912 @end example
11914 @noindent
11915 Notice that the unquoted text @code{unwanted} is output, even though it
11916 was processed while the current diversion was @code{KILL}, because it
11917 was collected as part of the argument to @code{m4_do}.  However, the
11918 text @code{discarded} disappeared as desired, because the diversion
11919 changes were single-quoted, and were not expanded until the top-level
11920 rescan of the output of @code{m4_do}.
11922 To make diversion management easier, M4sugar uses the concept of named
11923 diversions.  Rather than using diversion numbers directly, it is nicer
11924 to associate a name with each diversion.  The diversion number associated
11925 with a particular diversion name is an implementation detail, and a
11926 syntax warning is issued if a diversion number is used instead of a
11927 name.  In general, you should not output text
11928 to a named diversion until after calling the appropriate initialization
11929 routine for your language (@code{m4_init}, @code{AS_INIT},
11930 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11931 below.
11933 M4sugar defines two named diversions.
11934 @table @code
11935 @item KILL
11936 Text written to this diversion is discarded.  This is the default
11937 diversion once M4sugar is initialized.
11938 @item GROW
11939 This diversion is used behind the scenes by topological sorting macros,
11940 such as @code{AC_REQUIRE}.
11941 @end table
11943 M4sh adds several more named diversions.
11944 @table @code
11945 @item BINSH
11946 This diversion is reserved for the @samp{#!} interpreter line.
11947 @item HEADER-REVISION
11948 This diversion holds text from @code{AC_REVISION}.
11949 @item HEADER-COMMENT
11950 This diversion holds comments about the purpose of a file.
11951 @item HEADER-COPYRIGHT
11952 This diversion is managed by @code{AC_COPYRIGHT}.
11953 @item M4SH-SANITIZE
11954 This diversion contains M4sh sanitization code, used to ensure M4sh is
11955 executing in a reasonable shell environment.
11956 @item M4SH-INIT
11957 This diversion contains M4sh initialization code, initializing variables
11958 that are required by other M4sh macros.
11959 @item BODY
11960 This diversion contains the body of the shell code, and is the default
11961 diversion once M4sh is initialized.
11962 @end table
11964 Autotest inherits diversions from M4sh, and changes the default
11965 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11966 more named diversions, with the following subset designed for developer
11967 use.
11968 @table @code
11969 @item PREPARE_TESTS
11970 This diversion contains initialization sequences which are executed
11971 after @file{atconfig} and @file{atlocal}, and after all command line
11972 arguments have been parsed, but prior to running any tests.  It can be
11973 used to set up state that is required across all tests.  This diversion
11974 will work even before @code{AT_INIT}.
11975 @end table
11977 Autoconf inherits diversions from M4sh, and adds the following named
11978 diversions which developers can utilize.
11979 @table @code
11980 @item DEFAULTS
11981 This diversion contains shell variable assignments to set defaults that
11982 must be in place before arguments are parsed.  This diversion is placed
11983 early enough in @file{configure} that it is unsafe to expand any
11984 autoconf macros into this diversion.
11985 @item HELP_ENABLE
11986 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11987 diversion will be included as part of a quoted here-doc providing all of
11988 the @option{--help} output of @file{configure} related to options
11989 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11990 @item INIT_PREPARE
11991 This diversion occurs after all command line options have been parsed,
11992 but prior to the main body of the @file{configure} script.  This
11993 diversion is the last chance to insert shell code such as variable
11994 assignments or shell function declarations that will used by the
11995 expansion of other macros.
11996 @end table
11998 For now, the remaining named diversions of Autoconf, Autoheader, and
11999 Autotest are not documented.  In other words,
12000 intentionally outputting text into an undocumented diversion is subject
12001 to breakage in a future release of Autoconf.
12003 @defmac m4_cleardivert (@var{diversion}@dots{})
12004 @msindex{cleardivert}
12005 Permanently discard any text that has been diverted into
12006 @var{diversion}.
12007 @end defmac
12009 @defmac m4_divert_once (@var{diversion}, @ovar{content})
12010 @msindex{divert_once}
12011 Similar to @code{m4_divert_text}, except that @var{content} is only
12012 output to @var{diversion} if this is the first time that
12013 @code{m4_divert_once} has been called with its particular arguments.
12014 @end defmac
12016 @defmac m4_divert_pop (@ovar{diversion})
12017 @msindex{divert_pop}
12018 If provided, check that the current diversion is indeed @var{diversion}.
12019 Then change to the diversion located earlier on the stack, giving an
12020 error if an attempt is made to pop beyond the initial m4sugar diversion
12021 of @code{KILL}.
12022 @end defmac
12024 @defmac m4_divert_push (@var{diversion})
12025 @msindex{divert_push}
12026 Remember the former diversion on the diversion stack, and output
12027 subsequent text into @var{diversion}.  M4sugar maintains a diversion
12028 stack, and issues an error if there is not a matching pop for every
12029 push.
12030 @end defmac
12032 @anchor{m4_divert_text}
12033 @defmac m4_divert_text (@var{diversion}, @ovar{content})
12034 @msindex{divert_text}
12035 Output @var{content} and a newline into @var{diversion}, without
12036 affecting the current diversion.  Shorthand for:
12037 @example
12038 m4_divert_push([@var{diversion}])@var{content}
12039 m4_divert_pop([@var{diversion}])dnl
12040 @end example
12042 One use of @code{m4_divert_text} is to develop two related macros, where
12043 macro @samp{MY_A} does the work, but adjusts what work is performed
12044 based on whether the optional macro @samp{MY_B} has also been expanded.
12045 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12046 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12047 imposes an ordering restriction on the user; it would be nicer if macros
12048 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12049 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12050 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12051 expanded.
12053 @example
12054 AC_DEFUN([MY_A],
12055 [# various actions
12056 if test -n "$b_was_used"; then
12057   # extra action
12058 fi])
12059 AC_DEFUN([MY_B],
12060 [AC_REQUIRE([MY_A])dnl
12061 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12062 @end example
12064 @end defmac
12066 @defmac m4_init
12067 @msindex{init}
12068 Initialize the M4sugar environment, setting up the default named
12069 diversion to be @code{KILL}.
12070 @end defmac
12072 @node Conditional constructs
12073 @subsection Conditional constructs
12075 The following macros provide additional conditional constructs as
12076 convenience wrappers around @code{m4_if}.
12078 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12079   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12080 @msindex{bmatch}
12081 The string @var{string} is repeatedly compared against a series of
12082 @var{regex} arguments; if a match is found, the expansion is the
12083 corresponding @var{value}, otherwise, the macro moves on to the next
12084 @var{regex}.  If no @var{regex} match, then the result is the optional
12085 @var{default}, or nothing.
12086 @end defmac
12088 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12089   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12090 @msindex{bpatsubsts}
12091 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12092 as if by:
12093 @example
12094 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12095 @end example
12097 @noindent
12098 The result of the substitution is then passed through the next set of
12099 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12100 deletion of any matched portions in the current string.  Note that this
12101 macro over-quotes @var{string}; this behavior is intentional, so that
12102 the result of each step of the recursion remains as a quoted string.
12103 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12104 will line up with the extra quotations, and not the characters of the
12105 original string.  The overquoting is removed after the final
12106 substitution.
12107 @end defmac
12109 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12110   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12111 @msindex{case}
12112 Test @var{string} against multiple @var{value} possibilities, resulting
12113 in the first @var{if-value} for a match, or in the optional
12114 @var{default}.  This is shorthand for:
12115 @example
12116 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12117       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12118       [@var{default}])
12119 @end example
12120 @end defmac
12122 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12123   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12124 @msindex{cond}
12125 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12126 except that each @var{test} is expanded only when it is encountered.
12127 This is useful for short-circuiting expensive tests; while @code{m4_if}
12128 requires all its strings to be expanded up front before doing
12129 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12130 tests have failed.
12132 For an example, these two sequences give the same result, but in the
12133 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12134 version only expands @code{m4_index} once, instead of five times, for
12135 faster computation if this is a common case for @samp{$1}.  Notice that
12136 every third argument is unquoted for @code{m4_if}, and quoted for
12137 @code{m4_cond}:
12139 @example
12140 m4_if(m4_index([$1], [\]), [-1], [$2],
12141       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12142       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12143       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12144       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12145       [$2])
12146 m4_cond([m4_index([$1], [\])], [-1], [$2],
12147         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12148         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12149         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12150         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12151         [$2])
12152 @end example
12153 @end defmac
12155 @defmac m4_default (@var{expr-1}, @var{expr-2})
12156 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12157 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12158 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12159 @msindex{default}
12160 @msindex{default_quoted}
12161 @msindex{default_nblank}
12162 @msindex{default_nblank_quoted}
12163 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12164 @code{m4_default} expands the result, while @code{m4_default_quoted}
12165 does not.  Useful for providing a fixed default if the expression that
12166 results in @var{expr-1} would otherwise be empty.  The difference
12167 between @code{m4_default} and @code{m4_default_nblank} is whether an
12168 argument consisting of just blanks (space, tab, newline) is
12169 significant.  When using the expanding versions, note that an argument
12170 may contain text but still expand to an empty string.
12172 @example
12173 m4_define([active], [ACTIVE])dnl
12174 m4_define([empty], [])dnl
12175 m4_define([demo1], [m4_default([$1], [$2])])dnl
12176 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12177 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12178 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12179 demo1([active], [default])
12180 @result{}ACTIVE
12181 demo1([], [active])
12182 @result{}ACTIVE
12183 demo1([empty], [text])
12184 @result{}
12185 -demo1([ ], [active])-
12186 @result{}- -
12187 demo2([active], [default])
12188 @result{}active
12189 demo2([], [active])
12190 @result{}active
12191 demo2([empty], [text])
12192 @result{}empty
12193 -demo2([ ], [active])-
12194 @result{}- -
12195 demo3([active], [default])
12196 @result{}ACTIVE
12197 demo3([], [active])
12198 @result{}ACTIVE
12199 demo3([empty], [text])
12200 @result{}
12201 -demo3([ ], [active])-
12202 @result{}-ACTIVE-
12203 demo4([active], [default])
12204 @result{}active
12205 demo4([], [active])
12206 @result{}active
12207 demo4([empty], [text])
12208 @result{}empty
12209 -demo4([ ], [active])-
12210 @result{}-active-
12211 @end example
12212 @end defmac
12214 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12215 @msindex{define_default}
12216 If @var{macro} does not already have a definition, then define it to
12217 @var{default-definition}.
12218 @end defmac
12220 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12221 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12222 @msindex{ifblank}
12223 @msindex{ifnblank}
12224 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12225 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12226 variants exist, in order to make it easier to select the correct logical
12227 sense when using only two parameters.  Note that this is more efficient
12228 than the equivalent behavior of:
12229 @example
12230 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12231 @end example
12232 @end defmac
12234 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12235 @msindex{ifndef}
12236 This is shorthand for:
12237 @example
12238 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12239 @end example
12240 @end defmac
12242 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12243 @msindex{ifset}
12244 If @var{macro} is undefined, or is defined as the empty string, expand
12245 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12246 @example
12247 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12248 @end example
12249 @noindent
12250 except that it is not an error if @var{macro} is undefined.
12251 @end defmac
12253 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12254 @msindex{ifval}
12255 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12256 @var{if-false}.  This is shorthand for:
12257 @example
12258 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12259 @end example
12260 @end defmac
12262 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12263 @msindex{ifvaln}
12264 Similar to @code{m4_ifval}, except guarantee that a newline is present
12265 after any non-empty expansion.  Often followed by @code{dnl}.
12266 @end defmac
12268 @defmac m4_n (@var{text})
12269 @msindex{n}
12270 Expand to @var{text}, and add a newline if @var{text} is not empty.
12271 Often followed by @code{dnl}.
12272 @end defmac
12275 @node Looping constructs
12276 @subsection Looping constructs
12278 The following macros are useful in implementing recursive algorithms in
12279 M4, including loop operations.  An M4 list is formed by quoting a list
12280 of quoted elements; generally the lists are comma-separated, although
12281 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12282 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12283 It is common to see lists with unquoted elements when those elements are
12284 not likely to be macro names, as in @samp{[fputc_unlocked,
12285 fgetc_unlocked]}.
12287 Although not generally recommended, it is possible for quoted lists to
12288 have side effects; all side effects are expanded only once, and prior to
12289 visiting any list element.  On the other hand, the fact that unquoted
12290 macros are expanded exactly once means that macros without side effects
12291 can be used to generate lists.  For example,
12293 @example
12294 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12295 @error{}hi
12296 @result{}123
12297 m4_define([list], [[1], [2], [3]])
12298 @result{}
12299 m4_foreach([i], [list], [i])
12300 @result{}123
12301 @end example
12303 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12304 @msindex{argn}
12305 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12306 If there are too few arguments, the empty string is used.  For any
12307 @var{n} besides 1, this is more efficient than the similar
12308 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12309 @end defmac
12311 @defmac m4_car (@var{arg}@dots{})
12312 @msindex{car}
12313 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12314 to recursively iterate
12315 through a list.  Generally, when using quoted lists of quoted elements,
12316 @code{m4_car} should be called without any extra quotes.
12317 @end defmac
12319 @defmac m4_cdr (@var{arg}@dots{})
12320 @msindex{cdr}
12321 Expands to a quoted list of all but the first @var{arg}, or the empty
12322 string if there was only one argument.  Generally, when using quoted
12323 lists of quoted elements, @code{m4_cdr} should be called without any
12324 extra quotes.
12326 For example, this is a simple implementation of @code{m4_map}; note how
12327 each iteration checks for the end of recursion, then merely applies the
12328 first argument to the first element of the list, then repeats with the
12329 rest of the list.  (The actual implementation in M4sugar is a bit more
12330 involved, to gain some speed and share code with @code{m4_map_sep}, and
12331 also to avoid expanding side effects in @samp{$2} twice).
12332 @example
12333 m4_define([m4_map], [m4_ifval([$2],
12334   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12335 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12336 @result{} 1 2 a
12337 @end example
12338 @end defmac
12340 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12341   @var{expression})
12342 @msindex{for}
12343 Loop over the numeric values between @var{first} and @var{last}
12344 including bounds by increments of @var{step}.  For each iteration,
12345 expand @var{expression} with the numeric value assigned to @var{var}.
12346 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12347 on the order of the limits.  If given, @var{step} has to match this
12348 order.  The number of iterations is determined independently from
12349 definition of @var{var}; iteration cannot be short-circuited or
12350 lengthened by modifying @var{var} from within @var{expression}.
12351 @end defmac
12353 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12354 @msindex{foreach}
12355 Loop over the comma-separated M4 list @var{list}, assigning each value
12356 to @var{var}, and expand @var{expression}.  The following example
12357 outputs two lines:
12359 @example
12360 m4_foreach([myvar], [[foo], [bar, baz]],
12361            [echo myvar
12362 ])dnl
12363 @result{}echo foo
12364 @result{}echo bar, baz
12365 @end example
12367 Note that for some forms of @var{expression}, it may be faster to use
12368 @code{m4_map_args}.
12369 @end defmac
12371 @anchor{m4_foreach_w}
12372 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12373 @msindex{foreach_w}
12374 Loop over the white-space-separated list @var{list}, assigning each value
12375 to @var{var}, and expand @var{expression}.  If @var{var} is only
12376 referenced once in @var{expression}, it is more efficient to use
12377 @code{m4_map_args_w}.
12379 The deprecated macro @code{AC_FOREACH} is an alias of
12380 @code{m4_foreach_w}.
12381 @end defmac
12383 @defmac m4_map (@var{macro}, @var{list})
12384 @defmacx m4_mapall (@var{macro}, @var{list})
12385 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12386 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12387 @msindex{map}
12388 @msindex{mapall}
12389 @msindex{map_sep}
12390 @msindex{mapall_sep}
12391 Loop over the comma separated quoted list of argument descriptions in
12392 @var{list}, and invoke @var{macro} with the arguments.  An argument
12393 description is in turn a comma-separated quoted list of quoted elements,
12394 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12395 @code{m4_map_sep} ignore empty argument descriptions, while
12396 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12397 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12398 additionally expand @var{separator} between invocations of @var{macro}.
12400 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12401 separating output with commas, this means that the map result can be
12402 used as a series of arguments, by using a single-quoted comma as
12403 @var{separator}, or as a single string, by using a double-quoted comma.
12405 @example
12406 m4_map([m4_count], [])
12407 @result{}
12408 m4_map([ m4_count], [[],
12409                      [[1]],
12410                      [[1], [2]]])
12411 @result{} 1 2
12412 m4_mapall([ m4_count], [[],
12413                         [[1]],
12414                         [[1], [2]]])
12415 @result{} 0 1 2
12416 m4_map_sep([m4_eval], [,], [[[1+2]],
12417                             [[10], [16]]])
12418 @result{}3,a
12419 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12420 @result{}a,b
12421 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12422 @result{}2
12423 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12424 @result{}a,b
12425 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12426 @result{}1
12427 @end example
12428 @end defmac
12430 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12431 @msindex{map_args}
12432 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12433 argument.  In the following example, three solutions are presented with
12434 the same expansion; the solution using @code{m4_map_args} is the most
12435 efficient.
12436 @example
12437 m4_define([active], [ACTIVE])dnl
12438 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12439 @result{} plain active
12440 m4_map([ m4_echo], [[[plain]], [[active]]])
12441 @result{} plain active
12442 m4_map_args([ m4_echo], [plain], [active])
12443 @result{} plain active
12444 @end example
12446 In cases where it is useful to operate on additional parameters besides
12447 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12448 to supply the argument currying necessary to generate the desired
12449 argument list.  In the following example, @code{list_add_n} is more
12450 efficient than @code{list_add_x}.  On the other hand, using
12451 @code{m4_map_args_sep} can be even more efficient.
12453 @example
12454 m4_define([list], [[1], [2], [3]])dnl
12455 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12456 dnl list_add_n(N, ARG...)
12457 dnl Output a list consisting of each ARG added to N
12458 m4_define([list_add_n],
12459 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12460 list_add_n([1], list)
12461 @result{}2,3,4
12462 list_add_n([2], list)
12463 @result{}3,4,5
12464 m4_define([list_add_x],
12465 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12466   [,add([$1],m4_defn([var]))]))])dnl
12467 list_add_x([1], list)
12468 @result{}2,3,4
12469 @end example
12470 @end defmac
12472 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12473   @var{arg}@dots{})
12474 @msindex{map_args_pair}
12475 For every pair of arguments @var{arg}, invoke @var{macro} with two
12476 arguments.  If there is an odd number of arguments, invoke
12477 @var{macro-end}, which defaults to @var{macro}, with the remaining
12478 argument.
12480 @example
12481 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12482 @result{}, 2, 1, 3
12483 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12484 @result{}, 2, 1, [3]
12485 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12486 @result{}, 2, 1, 4, 3
12487 @end example
12488 @end defmac
12490 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12491 @msindex{map_args_sep}
12492 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12493 argument, additionally expanding @var{sep} between arguments.  One
12494 common use of this macro is constructing a macro call, where the opening
12495 and closing parentheses are split between @var{pre} and @var{post}; in
12496 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12497 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12498 macro provides the most efficient means for iterating over an arbitrary
12499 list of arguments, particularly when repeatedly constructing a macro
12500 call with more arguments than @var{arg}.
12501 @end defmac
12503 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12504 @msindex{map_args_w}
12505 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12506 the whitespace-separated @var{string}, additionally expanding @var{sep}
12507 between words.  This macro provides the most efficient means for
12508 iterating over a whitespace-separated string.  In particular,
12509 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12510 efficient than @code{m4_foreach_w([var], [@var{string}],
12511 [@var{action}(m4_defn([var]))])}.
12512 @end defmac
12514 @defmac m4_shiftn (@var{count}, @dots{})
12515 @defmacx m4_shift2 (@dots{})
12516 @defmacx m4_shift3 (@dots{})
12517 @msindex{shift2}
12518 @msindex{shift3}
12519 @msindex{shiftn}
12520 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12521 along with validation that enough arguments were passed in to match the
12522 shift count, and that the count is positive.  @code{m4_shift2} and
12523 @code{m4_shift3} are specializations
12524 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12525 for two and three shifts, respectively.
12526 @end defmac
12528 @defmac m4_stack_foreach (@var{macro}, @var{action})
12529 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12530 @msindex{stack_foreach}
12531 @msindex{stack_foreach_lifo}
12532 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12533 @var{action} with the single argument of a definition of @var{macro}.
12534 @code{m4_stack_foreach} starts with the oldest definition, while
12535 @code{m4_stack_foreach_lifo} starts with the current definition.
12536 @var{action} should not push or pop definitions of @var{macro}, nor is
12537 there any guarantee that the current definition of @var{macro} matches
12538 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12539 can be used if @var{action} needs more than one argument, although in
12540 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12542 Due to technical limitations, there are a few low-level m4sugar
12543 functions, such as @code{m4_pushdef}, that cannot be used as the
12544 @var{macro} argument.
12546 @example
12547 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12548 m4_stack_foreach([a], [ m4_incr])
12549 @result{} 2 3
12550 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12551 @result{} cd bcd
12552 @end example
12553 @end defmac
12555 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12556 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12557   @ovar{sep})
12558 @msindex{stack_foreach_sep}
12559 @msindex{stack_foreach_sep_lifo}
12560 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12561 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12562 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12563 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12564 the current definition first.  This macro provides the most efficient
12565 means for iterating over a pushdef stack.  In particular,
12566 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12567 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12568 @end defmac
12570 @node Evaluation Macros
12571 @subsection Evaluation Macros
12573 The following macros give some control over the order of the evaluation
12574 by adding or removing levels of quotes.
12576 @defmac m4_apply (@var{macro}, @var{list})
12577 @msindex{apply}
12578 Apply the elements of the quoted, comma-separated @var{list} as the
12579 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12580 without arguments.  Note the difference between @code{m4_indir}, which
12581 expects its first argument to be a macro name but can use names that are
12582 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12583 other text, but must end in a valid macro name.
12584 @example
12585 m4_apply([m4_count], [])
12586 @result{}0
12587 m4_apply([m4_count], [[]])
12588 @result{}1
12589 m4_apply([m4_count], [[1], [2]])
12590 @result{}2
12591 m4_apply([m4_join], [[|], [1], [2]])
12592 @result{}1|2
12593 @end example
12594 @end defmac
12596 @defmac m4_count (@var{arg}, @dots{})
12597 @msindex{count}
12598 This macro returns the decimal count of the number of arguments it was
12599 passed.
12600 @end defmac
12602 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12603 @msindex{curry}
12604 This macro performs argument currying.  The expansion of this macro is
12605 another macro name that expects exactly one argument; that argument is
12606 then appended to the @var{arg} list, and then @var{macro} is expanded
12607 with the resulting argument list.
12609 @example
12610 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12611 @result{}3, 2, 1
12612 @end example
12614 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12615 pass the definition of a builtin macro as the argument to the output of
12616 @code{m4_curry}; the empty string is used instead of the builtin token.
12617 This behavior is rectified by using M4 1.6 or newer.
12618 @end defmac
12620 @defmac m4_do (@var{arg}, @dots{})
12621 @msindex{do}
12622 This macro loops over its arguments and expands each @var{arg} in
12623 sequence.  Its main use is for readability; it allows the use of
12624 indentation and fewer @code{dnl} to result in the same expansion.  This
12625 macro guarantees that no expansion will be concatenated with subsequent
12626 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12627 @var{arg@dots{}}))}.
12629 @example
12630 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12631 m4_do([a],[b])c
12632 @result{}abc
12633 m4_unquote(m4_join([],[a],[b]))c
12634 @result{}3
12635 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12636 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12637 m4_do([a],[b])c
12638 @result{}ABC
12639 m4_unquote(m4_join([],[a],[b]))c
12640 @result{}3
12641 @end example
12642 @end defmac
12644 @defmac m4_dquote (@var{arg}, @dots{})
12645 @msindex{dquote}
12646 Return the arguments as a quoted list of quoted arguments.
12647 Conveniently, if there is just one @var{arg}, this effectively adds a
12648 level of quoting.
12649 @end defmac
12651 @defmac m4_dquote_elt (@var{arg}, @dots{})
12652 @msindex{dquote_elt}
12653 Return the arguments as a series of double-quoted arguments.  Whereas
12654 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12655 as many arguments as it was passed.
12656 @end defmac
12658 @defmac m4_echo (@var{arg}, @dots{})
12659 @msindex{echo}
12660 Return the arguments, with the same level of quoting.  Other than
12661 discarding whitespace after unquoted commas, this macro is a no-op.
12662 @end defmac
12664 @defmac m4_expand (@var{arg})
12665 @msindex{expand}
12666 Return the expansion of @var{arg} as a quoted string.  Whereas
12667 @code{m4_quote} is designed to collect expanded text into a single
12668 argument, @code{m4_expand} is designed to perform one level of expansion
12669 on quoted text.  One distinction is in the treatment of whitespace
12670 following a comma in the original @var{arg}.  Any time multiple
12671 arguments are collected into one with @code{m4_quote}, the M4 argument
12672 collection rules discard the whitespace.  However, with @code{m4_expand},
12673 whitespace is preserved, even after the expansion of macros contained in
12674 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12675 would involve an unterminated comment, whereas expanding that same text
12676 as the argument to @code{m4_quote} runs into difficulty in finding the
12677 end of the argument.  Since manipulating diversions during argument
12678 collection is inherently unsafe, @code{m4_expand} issues an error if
12679 @var{arg} attempts to change the current diversion (@pxref{Diversion
12680 support}).
12682 @example
12683 m4_define([active], [ACT, IVE])dnl
12684 m4_define([active2], [[ACT, IVE]])dnl
12685 m4_quote(active, active)
12686 @result{}ACT,IVE,ACT,IVE
12687 m4_expand([active, active])
12688 @result{}ACT, IVE, ACT, IVE
12689 m4_quote(active2, active2)
12690 @result{}ACT, IVE,ACT, IVE
12691 m4_expand([active2, active2])
12692 @result{}ACT, IVE, ACT, IVE
12693 m4_expand([# m4_echo])
12694 @result{}# m4_echo
12695 m4_quote(# m4_echo)
12697 @result{}# m4_echo)
12698 @result{}
12699 @end example
12701 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12702 literal unbalanced quotes, but that quadrigraphs can be used when
12703 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12704 be supplied with double quoting or a quadrigraph.
12706 @example
12707 m4_define([pattern], [[!@@<:@@]])dnl
12708 m4_define([bar], [BAR])dnl
12709 m4_expand([case $foo in
12710   m4_defn([pattern])@@:@}@@ bar ;;
12711   *[)] blah ;;
12712 esac])
12713 @result{}case $foo in
12714 @result{}  [![]) BAR ;;
12715 @result{}  *) blah ;;
12716 @result{}esac
12717 @end example
12718 @end defmac
12720 @defmac m4_ignore (@dots{})
12721 @msindex{ignore}
12722 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12723 ignoring all of its arguments.  By itself, this isn't very useful.
12724 However, it can be used to conditionally ignore an arbitrary number of
12725 arguments, by deciding which macro name to apply to a list of arguments.
12726 @example
12727 dnl foo outputs a message only if [debug] is defined.
12728 m4_define([foo],
12729 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12730 @end example
12732 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12733 serve the same purpose, although it is less readable.
12734 @end defmac
12736 @defmac m4_make_list (@var{arg}, @dots{})
12737 @msindex{make_list}
12738 This macro exists to aid debugging of M4sugar algorithms.  Its net
12739 effect is similar to @code{m4_dquote}---it produces a quoted list of
12740 quoted arguments, for each @var{arg}.  The difference is that this
12741 version uses a comma-newline separator instead of just comma, to improve
12742 readability of the list; with the result that it is less efficient than
12743 @code{m4_dquote}.
12744 @example
12745 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12746 m4_dquote(zero, [one], [[two]])
12747 @result{}[0],[one],[[two]]
12748 m4_make_list(zero, [one], [[two]])
12749 @result{}[0],
12750 @result{}[one],
12751 @result{}[[two]]
12752 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12753 @result{} 0 1 two
12754 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12755 @result{} 0 1 two
12756 @end example
12757 @end defmac
12759 @c m4_noquote is too dangerous to document - it invokes macros that
12760 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12761 @c user should generally prefer m4_unquote instead.
12763 @defmac m4_quote (@var{arg}, @dots{})
12764 @msindex{quote}
12765 Return the arguments as a single entity, i.e., wrap them into a pair of
12766 quotes.  This effectively collapses multiple arguments into one,
12767 although it loses whitespace after unquoted commas in the process.
12768 @end defmac
12770 @defmac m4_reverse (@var{arg}, @dots{})
12771 @msindex{reverse}
12772 Outputs each argument with the same level of quoting, but in reverse
12773 order, and with space following each comma for readability.
12775 @example
12776 m4_define([active], [ACT,IVE])
12777 @result{}
12778 m4_reverse(active, [active])
12779 @result{}active, IVE, ACT
12780 @end example
12781 @end defmac
12783 @defmac m4_unquote (@var{arg}, @dots{})
12784 @msindex{unquote}
12785 This macro was introduced in Autoconf 2.62.  Expand each argument,
12786 separated by commas.  For a single @var{arg}, this effectively removes a
12787 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12788 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12789 this results in an unquoted list of expansions.  This is commonly used
12790 with @code{m4_split}, in order to convert a single quoted list into a
12791 series of quoted elements.
12792 @end defmac
12794 The following example aims at emphasizing the difference between several
12795 scenarios: not using these macros, using @code{m4_defn}, using
12796 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12798 @example
12799 $ @kbd{cat example.m4}
12800 dnl Overquote, so that quotes are visible.
12801 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12802 m4_define([a], [A])
12803 m4_define([mkargs], [1, 2[,] 3])
12804 m4_define([arg1], [[$1]])
12805 m4_divert([0])dnl
12806 show(a, b)
12807 show([a, b])
12808 show(m4_quote(a, b))
12809 show(m4_dquote(a, b))
12810 show(m4_expand([a, b]))
12812 arg1(mkargs)
12813 arg1([mkargs])
12814 arg1(m4_defn([mkargs]))
12815 arg1(m4_quote(mkargs))
12816 arg1(m4_dquote(mkargs))
12817 arg1(m4_expand([mkargs]))
12818 $ @kbd{autom4te -l m4sugar example.m4}
12819 $1 = A, $@@ = [A],[b]
12820 $1 = a, b, $@@ = [a, b]
12821 $1 = A,b, $@@ = [A,b]
12822 $1 = [A],[b], $@@ = [[A],[b]]
12823 $1 = A, b, $@@ = [A, b]
12826 mkargs
12827 1, 2[,] 3
12828 1,2, 3
12829 [1],[2, 3]
12830 1, 2, 3
12831 @end example
12834 @node Text processing Macros
12835 @subsection String manipulation in M4
12837 The following macros may be used to manipulate strings in M4.  Many of
12838 the macros in this section intentionally result in quoted strings as
12839 output, rather than subjecting the arguments to further expansions.  As
12840 a result, if you are manipulating text that contains active M4
12841 characters, the arguments are passed with single quoting rather than
12842 double.
12844 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12845 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12846   @ovar{if-uniq}, @ovar{if-duplicate})
12847 @msindex{append}
12848 @msindex{append_uniq}
12849 Redefine @var{macro-name} to its former contents with @var{separator}
12850 and @var{string} added at the end.  If @var{macro-name} was undefined
12851 before (but not if it was defined but empty), then no @var{separator} is
12852 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12853 are expanded during this macro; instead, they are expanded when
12854 @var{macro-name} is invoked.
12856 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12857 to grow strings without duplicating substrings.  Additionally,
12858 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12859 @var{if-uniq} is expanded if @var{string} was appended, and
12860 @var{if-duplicate} is expanded if @var{string} was already present.
12861 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12862 occurs within @var{string}, since that can lead to duplicates.
12864 Note that @code{m4_append} can scale linearly in the length of the final
12865 string, depending on the quality of the underlying M4 implementation,
12866 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12867 If an algorithm can tolerate duplicates in the final string, use the
12868 former for speed.  If duplicates must be avoided, consider using
12869 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12871 @example
12872 m4_define([active], [ACTIVE])dnl
12873 m4_append([sentence], [This is an])dnl
12874 m4_append([sentence], [ active ])dnl
12875 m4_append([sentence], [symbol.])dnl
12876 sentence
12877 @result{}This is an ACTIVE symbol.
12878 m4_undefine([active])dnl
12879 @result{}This is an active symbol.
12880 m4_append_uniq([list], [one], [, ], [new], [existing])
12881 @result{}new
12882 m4_append_uniq([list], [one], [, ], [new], [existing])
12883 @result{}existing
12884 m4_append_uniq([list], [two], [, ], [new], [existing])
12885 @result{}new
12886 m4_append_uniq([list], [three], [, ], [new], [existing])
12887 @result{}new
12888 m4_append_uniq([list], [two], [, ], [new], [existing])
12889 @result{}existing
12890 list
12891 @result{}one, two, three
12892 m4_dquote(list)
12893 @result{}[one],[two],[three]
12894 m4_append([list2], [one], [[, ]])dnl
12895 m4_append_uniq([list2], [two], [[, ]])dnl
12896 m4_append([list2], [three], [[, ]])dnl
12897 list2
12898 @result{}one, two, three
12899 m4_dquote(list2)
12900 @result{}[one, two, three]
12901 @end example
12902 @end defmac
12904 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12905 @msindex{append_uniq_w}
12906 This macro was introduced in Autoconf 2.62.  It is similar to
12907 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12908 separated list of words to append, and only appends unique words.
12909 @var{macro-name} is updated with a single space between new words.
12910 @example
12911 m4_append_uniq_w([numbers], [1 1 2])dnl
12912 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12913 numbers
12914 @result{}1 2 3
12915 @end example
12916 @end defmac
12918 @defmac m4_chomp (@var{string})
12919 @defmacx m4_chomp_all (@var{string})
12920 @msindex{chomp}
12921 @msindex{chomp_all}
12922 Output @var{string} in quotes, but without a trailing newline.  The
12923 macro @code{m4_chomp} is slightly faster, and removes at most one
12924 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12925 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12926 and backslash does not influence the result.
12927 @end defmac
12929 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12930   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12931 @msindex{combine}
12932 This macro produces a quoted string containing the pairwise combination
12933 of every element of the quoted, comma-separated @var{prefix-list}, and
12934 every element from the @var{suffix} arguments.  Each pairwise
12935 combination is joined with @var{infix} in the middle, and successive
12936 pairs are joined by @var{separator}.  No expansion occurs on any of the
12937 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12938 list is empty, but the lists can contain empty elements.
12939 @example
12940 m4_define([a], [oops])dnl
12941 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12942 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12943 m4_combine([, ], [[a], [b]], [-])
12944 @result{}
12945 m4_combine([, ], [[a], [b]], [-], [])
12946 @result{}a-, b-
12947 m4_combine([, ], [], [-], [1], [2])
12948 @result{}
12949 m4_combine([, ], [[]], [-], [1], [2])
12950 @result{}-1, -2
12951 @end example
12952 @end defmac
12954 @defmac m4_escape (@var{string})
12955 @msindex{escape}
12956 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12957 within @var{string} into their respective quadrigraphs.  The result is
12958 still a quoted string.
12959 @end defmac
12961 @defmac m4_flatten (@var{string})
12962 @msindex{flatten}
12963 Flatten @var{string} into a single line.  Delete all backslash-newline
12964 pairs, and replace all remaining newlines with a space.  The result is
12965 still a quoted string.
12966 @end defmac
12968 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12969 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12970 @msindex{join}
12971 @msindex{joinall}
12972 Concatenate each @var{arg}, separated by @var{separator}.
12973 @code{joinall} uses every argument, while @code{join} omits empty
12974 arguments so that there are no back-to-back separators in the output.
12975 The result is a quoted string.
12976 @example
12977 m4_define([active], [ACTIVE])dnl
12978 m4_join([|], [one], [], [active], [two])
12979 @result{}one|active|two
12980 m4_joinall([|], [one], [], [active], [two])
12981 @result{}one||active|two
12982 @end example
12984 Note that if all you intend to do is join @var{args} with commas between
12985 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12986 efficient to use @code{m4_dquote}.
12987 @end defmac
12989 @defmac m4_newline (@ovar{text})
12990 @msindex{newline}
12991 This macro was introduced in Autoconf 2.62, and expands to a newline,
12992 followed by any @var{text}.
12993 It is primarily useful for maintaining macro formatting, and ensuring
12994 that M4 does not discard leading whitespace during argument collection.
12995 @end defmac
12997 @defmac m4_normalize (@var{string})
12998 @msindex{normalize}
12999 Remove leading and trailing spaces and tabs, sequences of
13000 backslash-then-newline, and replace multiple spaces, tabs, and newlines
13001 with a single space.  This is a combination of @code{m4_flatten} and
13002 @code{m4_strip}.  To determine if @var{string} consists only of bytes
13003 that would be removed by @code{m4_normalize}, you can use
13004 @code{m4_ifblank}.
13005 @end defmac
13007 @defmac m4_re_escape (@var{string})
13008 @msindex{re_escape}
13009 Backslash-escape all characters in @var{string} that are active in
13010 regexps.
13011 @end defmac
13013 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13014 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
13015 @msindex{split}
13016 Split @var{string} into an M4 list of elements quoted by @samp{[} and
13017 @samp{]}, while keeping white space at the beginning and at the end.
13018 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
13019 If @var{string} is empty, the result is an empty list.
13020 @end defmac
13022 @defmac m4_strip (@var{string})
13023 @msindex{strip}
13024 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
13025 reduced to a single space, then leading and trailing spaces are removed.
13026 The result is still a quoted string.  Note that this does not interfere
13027 with newlines; if you want newlines stripped as well, consider
13028 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
13029 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
13030 @end defmac
13032 @defmac m4_text_box (@var{message}, @dvar{frame, -})
13033 @msindex{text_box}
13034 Add a text box around @var{message}, using @var{frame} as the border
13035 character above and below the message.  The @var{frame} argument must be
13036 a single byte, and does not support quadrigraphs.
13037 The frame correctly accounts for
13038 the subsequent expansion of @var{message}.  For example:
13039 @example
13040 m4_define([macro], [abc])dnl
13041 m4_text_box([macro])
13042 @result{}## --- ##
13043 @result{}## abc ##
13044 @result{}## --- ##
13045 @end example
13047 The @var{message} must contain balanced quotes and parentheses, although
13048 quadrigraphs can be used to work around this.
13049 @end defmac
13051 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13052   @dvarv{prefix1, prefix}, @dvar{width, 79})
13053 @msindex{text_wrap}
13054 Break @var{string} into a series of whitespace-separated words, then
13055 output those words separated by spaces, and wrapping lines any time the
13056 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13057 the first line, and @var{prefix} begins all wrapped lines.  If
13058 @var{prefix1} is longer than @var{prefix}, then the first line consists
13059 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13060 padding is inserted so that the first word of @var{string} begins at the
13061 same indentation as all wrapped lines.  Note that using literal tab
13062 characters in any of the arguments will interfere with the calculation
13063 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13064 words of @var{string}, although quadrigraphs are recognized.
13066 For some examples:
13067 @example
13068 m4_text_wrap([Short string */], [   ], [/* ], [20])
13069 @result{}/* Short string */
13070 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13071 @result{}/* Much longer
13072 @result{}   string */
13073 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13074 @result{}  --short Short doc.
13075 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13076 @result{}  --too-wide
13077 @result{}          Short doc.
13078 m4_text_wrap([Super long documentation.], [     ],
13079              [  --too-wide ], 30)
13080 @result{}  --too-wide
13081 @result{}     Super long
13082 @result{}     documentation.
13083 @end example
13084 @end defmac
13086 @defmac m4_tolower (@var{string})
13087 @defmacx m4_toupper (@var{string})
13088 @msindex{tolower}
13089 @msindex{toupper}
13090 Return @var{string} with letters converted to upper or lower case,
13091 respectively.
13092 @end defmac
13094 @node Number processing Macros
13095 @subsection Arithmetic computation in M4
13097 The following macros facilitate integer arithmetic operations.
13098 Where a parameter is documented as taking an arithmetic expression, you
13099 can use anything that can be parsed by @code{m4_eval}.
13101 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13102 @msindex{cmp}
13103 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13104 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13105 equal, and @samp{1} if @var{expr-1} is larger.
13106 @end defmac
13108 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13109 @msindex{list_cmp}
13110 Compare the two M4 lists consisting of comma-separated arithmetic
13111 expressions, left to right.  Expand to @samp{-1} for the first element
13112 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13113 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13114 same values.  If one list is shorter than the other, the remaining
13115 elements of the longer list are compared against zero.
13116 @example
13117 m4_list_cmp([1, 0],       [1])
13118 @result{}0
13119 m4_list_cmp([1, [1 * 0]], [1, 0])
13120 @result{}0
13121 m4_list_cmp([1, 2],       [1, 0])
13122 @result{}1
13123 m4_list_cmp([1, [1+1], 3],[1, 2])
13124 @result{}1
13125 m4_list_cmp([1, 2, -3],   [1, 2])
13126 @result{}-1
13127 m4_list_cmp([1, 0],       [1, 2])
13128 @result{}-1
13129 m4_list_cmp([1],          [1, 2])
13130 @result{}-1
13131 @end example
13132 @end defmac
13134 @defmac m4_max (@var{arg}, @dots{})
13135 @msindex{max}
13136 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13137 of the maximum arithmetic expression among all the arguments.
13138 @end defmac
13140 @defmac m4_min (@var{arg}, @dots{})
13141 @msindex{min}
13142 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13143 of the minimum arithmetic expression among all the arguments.
13144 @end defmac
13146 @defmac m4_sign (@var{expr})
13147 @msindex{sign}
13148 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13149 @samp{1} if it is positive, and @samp{0} if it is zero.
13150 @end defmac
13152 @anchor{m4_version_compare}
13153 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13154 @msindex{version_compare}
13155 This macro was introduced in Autoconf 2.53, but had a number of
13156 usability limitations that were not lifted until Autoconf 2.62.  Compare
13157 the version strings @var{version-1} and @var{version-2}, and expand to
13158 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13159 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13160 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13161 element is a number along with optional case-insensitive letters
13162 designating beta releases.  The comparison stops at the leftmost element
13163 that contains a difference, although a 0 element compares equal to a
13164 missing element.
13166 It is permissible to include commit identifiers in @var{version}, such
13167 as an abbreviated SHA1 of the commit, provided there is still a
13168 monotonically increasing prefix to allow for accurate version-based
13169 comparisons.  For example, this paragraph was written when the
13170 development snapshot of autoconf claimed to be at version
13171 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13172 abbreviated commit identification of @samp{dc51}.
13174 @example
13175 m4_version_compare([1.1], [2.0])
13176 @result{}-1
13177 m4_version_compare([2.0b], [2.0a])
13178 @result{}1
13179 m4_version_compare([1.1.1], [1.1.1a])
13180 @result{}-1
13181 m4_version_compare([1.2], [1.1.1a])
13182 @result{}1
13183 m4_version_compare([1.0], [1])
13184 @result{}0
13185 m4_version_compare([1.1pre], [1.1PRE])
13186 @result{}0
13187 m4_version_compare([1.1a], [1,10])
13188 @result{}-1
13189 m4_version_compare([2.61a], [2.61a-248-dc51])
13190 @result{}-1
13191 m4_version_compare([2.61b], [2.61a-248-dc51])
13192 @result{}1
13193 @end example
13194 @end defmac
13196 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13197   @dvar{if-old, m4_fatal})
13198 @msindex{version_prereq}
13199 Compares @var{version} against the version of Autoconf currently
13200 running.  If the running version is at @var{version} or newer, expand
13201 @var{if-new-enough}, but if @var{version} is larger than the version
13202 currently executing, expand @var{if-old}, which defaults to printing an
13203 error message and exiting m4sugar with status 63.  When given only one
13204 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13205 Remember that the autoconf philosophy favors feature checks over version
13206 checks.
13207 @end defmac
13209 @node Set manipulation Macros
13210 @subsection Set manipulation in M4
13211 @cindex Set manipulation
13212 @cindex Data structure, set
13213 @cindex Unordered set manipulation
13215 Sometimes, it is necessary to track a set of data, where the order does
13216 not matter and where there are no duplicates in the set.  The following
13217 macros facilitate set manipulations.  Each set is an opaque object,
13218 which can only be accessed via these basic operations.  The underlying
13219 implementation guarantees linear scaling for set creation, which is more
13220 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13221 names and values can be arbitrary strings, except for unbalanced quotes.
13222 This implementation ties up memory for removed elements until the next
13223 operation that must traverse all the elements of a set; and although
13224 that may slow down some operations until the memory for removed elements
13225 is pruned, it still guarantees linear performance.
13227 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13228 @msindex{set_add}
13229 Adds the string @var{value} as a member of set @var{set}.  Expand
13230 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13231 previously in the set.  Operates in amortized constant time, so that set
13232 creation scales linearly.
13233 @end defmac
13235 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13236 @msindex{set_add_all}
13237 Adds each @var{value} to the set @var{set}.  This is slightly more
13238 efficient than repeatedly invoking @code{m4_set_add}.
13239 @end defmac
13241 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13242  @ovar{if-absent})
13243 @msindex{set_contains}
13244 Expands @var{if-present} if the string @var{value} is a member of
13245 @var{set}, otherwise @var{if-absent}.
13247 @example
13248 m4_set_contains([a], [1], [yes], [no])
13249 @result{}no
13250 m4_set_add([a], [1], [added], [dup])
13251 @result{}added
13252 m4_set_add([a], [1], [added], [dup])
13253 @result{}dup
13254 m4_set_contains([a], [1], [yes], [no])
13255 @result{}yes
13256 m4_set_remove([a], [1], [removed], [missing])
13257 @result{}removed
13258 m4_set_contains([a], [1], [yes], [no])
13259 @result{}no
13260 m4_set_remove([a], [1], [removed], [missing])
13261 @result{}missing
13262 @end example
13263 @end defmac
13265 @defmac m4_set_contents (@var{set}, @ovar{sep})
13266 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13267 @msindex{set_contents}
13268 @msindex{set_dump}
13269 Expands to a single string consisting of all the members of the set
13270 @var{set}, each separated by @var{sep}, which is not expanded.
13271 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13272 memory occupied by removed elements, while @code{m4_set_dump} is a
13273 faster one-shot action that also deletes the set.  No provision is made
13274 for disambiguating members that contain a non-empty @var{sep} as a
13275 substring; use @code{m4_set_empty} to distinguish between an empty set
13276 and the set containing only the empty string.  The order of the output
13277 is unspecified; in the current implementation, part of the speed of
13278 @code{m4_set_dump} results from using a different output order than
13279 @code{m4_set_contents}.  These macros scale linearly in the size of the
13280 set before memory pruning, and @code{m4_set_contents([@var{set}],
13281 [@var{sep}])} is faster than
13282 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13284 @example
13285 m4_set_add_all([a], [1], [2], [3])
13286 @result{}
13287 m4_set_contents([a], [-])
13288 @result{}1-2-3
13289 m4_joinall([-]m4_set_listc([a]))
13290 @result{}1-2-3
13291 m4_set_dump([a], [-])
13292 @result{}3-2-1
13293 m4_set_contents([a])
13294 @result{}
13295 m4_set_add([a], [])
13296 @result{}
13297 m4_set_contents([a], [-])
13298 @result{}
13299 @end example
13300 @end defmac
13302 @defmac m4_set_delete (@var{set})
13303 @msindex{set_delete}
13304 Delete all elements and memory associated with @var{set}.  This is
13305 linear in the set size, and faster than removing one element at a time.
13306 @end defmac
13308 @defmac m4_set_difference (@var{seta}, @var{setb})
13309 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13310 @defmacx m4_set_union (@var{seta}, @var{setb})
13311 @msindex{set_difference}
13312 @msindex{set_intersection}
13313 @msindex{set_union}
13314 Compute the relation between @var{seta} and @var{setb}, and output the
13315 result as a list of quoted arguments without duplicates and with a
13316 leading comma.  Set difference selects the elements in @var{seta} but
13317 not @var{setb}, intersection selects only elements in both sets, and
13318 union selects elements in either set.  These actions are linear in the
13319 sum of the set sizes.  The leading comma is necessary to distinguish
13320 between no elements and the empty string as the only element.
13322 @example
13323 m4_set_add_all([a], [1], [2], [3])
13324 @result{}
13325 m4_set_add_all([b], [3], [], [4])
13326 @result{}
13327 m4_set_difference([a], [b])
13328 @result{},1,2
13329 m4_set_difference([b], [a])
13330 @result{},,4
13331 m4_set_intersection([a], [b])
13332 @result{},3
13333 m4_set_union([a], [b])
13334 @result{},1,2,3,,4
13335 @end example
13336 @end defmac
13338 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13339 @msindex{set_empty}
13340 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13341 expand @var{if-elements}.  This macro operates in constant time.  Using
13342 this macro can help disambiguate output from @code{m4_set_contents} or
13343 @code{m4_set_list}.
13344 @end defmac
13346 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13347 @msindex{set_foreach}
13348 For each element in the set @var{set}, expand @var{action} with the
13349 macro @var{variable} defined as the set element.  Behavior is
13350 unspecified if @var{action} recursively lists the contents of @var{set}
13351 (although listing other sets is acceptable), or if it modifies the set
13352 in any way other than removing the element currently contained in
13353 @var{variable}.  This macro is faster than the corresponding
13354 @code{m4_foreach([@var{variable}],
13355 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13356 although @code{m4_set_map} might be faster still.
13358 @example
13359 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13360 @result{}
13361 m4_set_contents([a])
13362 @result{}12345
13363 m4_set_foreach([a], [i],
13364   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13365 @result{}24
13366 m4_set_contents([a])
13367 @result{}135
13368 @end example
13369 @end defmac
13371 @defmac m4_set_list (@var{set})
13372 @defmacx m4_set_listc (@var{set})
13373 @msindex{set_list}
13374 @msindex{set_listc}
13375 Produce a list of arguments, where each argument is a quoted element
13376 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13377 by adding a leading comma if there are any set elements, whereas the
13378 variant @code{m4_set_list} cannot distinguish between an empty set and a
13379 set containing only the empty string.  These can be directly used in
13380 macros that take multiple arguments, such as @code{m4_join} or
13381 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13382 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13383 memory occupied by removed elements is reclaimed during these macros.
13385 @example
13386 m4_set_add_all([a], [1], [2], [3])
13387 @result{}
13388 m4_set_list([a])
13389 @result{}1,2,3
13390 m4_set_list([b])
13391 @result{}
13392 m4_set_listc([b])
13393 @result{}
13394 m4_count(m4_set_list([b]))
13395 @result{}1
13396 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13397 @result{}0
13398 m4_set_add([b], [])
13399 @result{}
13400 m4_set_list([b])
13401 @result{}
13402 m4_set_listc([b])
13403 @result{},
13404 m4_count(m4_set_list([b]))
13405 @result{}1
13406 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13407 @result{}1
13408 @end example
13409 @end defmac
13411 @defmac m4_set_map (@var{set}, @var{action})
13412 @msindex{set_map}
13413 For each element in the set @var{set}, expand @var{action} with a single
13414 argument of the set element.  Behavior is unspecified if @var{action}
13415 recursively lists the contents of @var{set} (although listing other sets
13416 is acceptable), or if it modifies the set in any way other than removing
13417 the element passed as an argument.  This macro is faster than either
13418 corresponding counterpart of
13419 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13420 @code{m4_set_foreach([@var{set}], [var],
13421 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13422 if more than one argument is needed for @var{action}, although it is
13423 more efficient to use @code{m4_set_map_sep} in that case.
13424 @end defmac
13426 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13427 @msindex{set_map_sep}
13428 For each element in the set @var{set}, expand
13429 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13430 between elements.  Behavior is unspecified if the expansion recursively
13431 lists the contents of @var{set} (although listing other sets
13432 is acceptable), or if it modifies the set in any way other than removing
13433 the element visited by the expansion.  This macro provides the most
13434 efficient means for non-destructively visiting the elements of a set; in
13435 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13436 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13437 @end defmac
13439 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13440  @ovar{if-absent})
13441 @msindex{set_remove}
13442 If @var{value} is an element in the set @var{set}, then remove it and
13443 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13444 operates in constant time so that multiple removals will scale linearly
13445 rather than quadratically; but when used outside of
13446 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13447 until the set is later
13448 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13449 other set operations are then less efficient between the time of element
13450 removal and subsequent memory compaction, but still maintain their
13451 guaranteed scaling performance.
13452 @end defmac
13454 @defmac m4_set_size (@var{set})
13455 @msindex{set_size}
13456 Expand to the size of the set @var{set}.  This implementation operates
13457 in constant time, and is thus more efficient than
13458 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13459 @end defmac
13462 @node Forbidden Patterns
13463 @subsection Forbidden Patterns
13464 @cindex Forbidden patterns
13465 @cindex Patterns, forbidden
13467 M4sugar provides a means to define suspicious patterns, patterns
13468 describing tokens which should not be found in the output.  For
13469 instance, if an Autoconf @file{configure} script includes tokens such as
13470 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13471 wrong (typically a macro was not evaluated because of overquotation).
13473 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13474 Additional layers, such as M4sh and Autoconf, add additional forbidden
13475 patterns to the list.
13477 @defmac m4_pattern_forbid (@var{pattern})
13478 @msindex{pattern_forbid}
13479 Declare that no token matching @var{pattern} must be found in the
13480 output.  The output file is (temporarily) split into one word per line
13481 as part of the @command{autom4te} post-processing, with each line (and
13482 therefore word) then being checked against the Perl regular expression
13483 @var{pattern}.  If the regular expression matches, and
13484 @code{m4_pattern_allow} does not also match, then an error is raised.
13486 Comments are not checked; this can be a problem if, for instance, you
13487 have some macro left unexpanded after an @samp{#include}.  No consensus
13488 is currently found in the Autoconf community, as some people consider it
13489 should be valid to name macros in comments (which doesn't make sense to
13490 the authors of this documentation: input, such as macros, should be
13491 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13492 document the output).
13494 As an example, if you define your own macros that begin with @samp{M_}
13495 and are composed from capital letters and underscores, the specification
13496 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13497 are expanded when not used in comments.
13499 As an example of a common use of this macro, consider what happens in
13500 packages that want to use the @command{pkg-config} script via the
13501 third-party @code{PKG_CHECK_MODULES} macro.  By default, if a developer
13502 checks out the development tree but has not yet installed the pkg-config
13503 macros locally, they can manage to successfully run @command{autoconf}
13504 on the package, but the resulting @file{configure} file will likely
13505 result in a confusing shell message about a syntax error on the line
13506 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro.  On the other hand,
13507 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13508 missing pkg-config macros will be detected immediately without allowing
13509 @command{autoconf} to succeed.
13510 @end defmac
13512 Of course, you might encounter exceptions to these generic rules, for
13513 instance you might have to refer to @samp{$m4_flags}.
13515 @defmac m4_pattern_allow (@var{pattern})
13516 @msindex{pattern_allow}
13517 Any token matching @var{pattern} is allowed, including if it matches an
13518 @code{m4_pattern_forbid} pattern.
13520 For example, gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13521 @code{gl_} namespace for itself, but also uses
13522 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13523 valid locale name.
13524 @end defmac
13526 @node Debugging via autom4te
13527 @section Debugging via autom4te
13528 @cindex debugging tips
13529 @cindex autom4te debugging tips
13530 @cindex m4sugar debugging tips
13531 At times, it is desirable to see what was happening inside m4, to see
13532 why output was not matching expectations.  However, post-processing done
13533 by @command{autom4te} means that directly using the m4 builtin
13534 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13535 diversion changes and the concept of forbidden tokens make it difficult
13536 to use @code{m4_defn} to generate inline comments in the final output.
13538 There are a couple of tools to help with this.  One is the use of the
13539 @option{--trace} option provided by @command{autom4te} (as well as each
13540 of the programs that wrap @command{autom4te}, such as
13541 @command{autoconf}), in order to inspect when a macro is called and with
13542 which arguments.  For example, when this paragraph was written, the
13543 autoconf version could be found by:
13545 @example
13546 $ @kbd{autoconf --trace=AC_INIT}
13547 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13548 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13549 version is 2.63b.95-3963
13550 @end example
13552 Another trick is to print out the expansion of various m4 expressions to
13553 standard error or to an independent file, with no further m4 expansion,
13554 and without interfering with diversion changes or the post-processing
13555 done to standard output.  @code{m4_errprintn} shows a given expression
13556 on standard error.  For example, if you want to see the expansion of an
13557 autoconf primitive or of one of your autoconf macros, you can do it like
13558 this:
13560 @example
13561 $ @kbd{cat <<\EOF > configure.ac}
13562 AC_INIT
13563 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13564 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13565 AC_OUTPUT
13567 $ @kbd{autoconf}
13568 @error{}The definition of AC_DEFINE_UNQUOTED:
13569 @error{}_AC_DEFINE_Q([], $@@)
13570 @end example
13572 @node Programming in M4sh
13573 @chapter Programming in M4sh
13575 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13576 scripts.  This name was coined by Lars J. Aas, who notes that,
13577 according to the Webster's Revised Unabridged Dictionary (1913):
13579 @quotation
13580 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13581 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13583 @enumerate 1
13584 @item
13585 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13586 pressure@enddots{}
13588 @item
13589 A mixture of meal or bran and water fed to animals.
13591 @item
13592 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13593 @end enumerate
13594 @end quotation
13596 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13597 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13598 and environment variable namespace @samp{^as_}, and the here-document
13599 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13600 define your own macros or output shell code that conflicts with these
13601 namespaces.
13603 @menu
13604 * Common Shell Constructs::     Portability layer for common shell constructs
13605 * Polymorphic Variables::       Support for indirect variable names
13606 * Initialization Macros::       Macros to establish a sane shell environment
13607 * File Descriptor Macros::      File descriptor macros for input and output
13608 @end menu
13610 @node Common Shell Constructs
13611 @section Common Shell Constructs
13613 M4sh provides portable alternatives for some common shell constructs
13614 that unfortunately are not portable in practice.
13616 @c Deprecated, to be replaced by a better API
13617 @ignore
13618 @defmac AS_BASENAME (@var{file-name})
13619 @asindex{BASENAME}
13620 Output the non-directory portion of @var{file-name}.  For example,
13621 if @code{$file} is @samp{/one/two/three}, the command
13622 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13623 @end defmac
13624 @end ignore
13626 @defmac AS_BOX (@var{text}, @dvar{char, -})
13627 @asindex{BOX}
13628 Expand into shell code that will output @var{text} surrounded by a box
13629 with @var{char} in the top and bottom border.  @var{text} should not
13630 contain a newline, but may contain shell expansions valid for unquoted
13631 here-documents.  @var{char} defaults to @samp{-}, but can be any
13632 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13633 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13634 log files to separate distinct phases of script operation.
13635 @end defmac
13637 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13638   @dots{}, @ovar{default})
13639 @asindex{CASE}
13640 Expand into a shell @samp{case} statement, where @var{word} is matched
13641 against one or more patterns.  @var{if-matched} is run if the
13642 corresponding pattern matched @var{word}, else @var{default} is run.
13643 Avoids several portability issues (@pxref{case, , Limitations of Shell
13644 Builtins}).
13645 @end defmac
13647 @c Deprecated, to be replaced by a better API
13648 @defmac AS_DIRNAME (@var{file-name})
13649 @asindex{DIRNAME}
13650 Output the directory portion of @var{file-name}.  For example,
13651 if @code{$file} is @samp{/one/two/three}, the command
13652 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13654 This interface may be improved in the future to avoid forks and losing
13655 trailing newlines.
13656 @end defmac
13658 @defmac AS_ECHO (@var{word})
13659 @asindex{ECHO}
13660 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13661 must be a single shell word (typically a quoted string).  The bytes of
13662 @var{word} are output as-is, even if it starts with "-" or contains "\".
13663 Redirections can be placed outside the macro invocation.  This is much
13664 more portable than using @command{echo} (@pxref{echo, , Limitations of
13665 Shell Builtins}).
13666 @end defmac
13668 @defmac AS_ECHO_N (@var{word})
13669 @asindex{ECHO_N}
13670 Emits @var{word} to the standard output, without a following newline.
13671 @var{word} must be a single shell word (typically a quoted string) and,
13672 for portability, should not include more than one newline.  The bytes of
13673 @var{word} are output as-is, even if it starts with "-" or contains "\".
13674 Redirections can be placed outside the macro invocation.
13675 @end defmac
13677 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13678 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13679 @asindex{ESCAPE}
13680 Expands to @var{string}, with any characters in @var{chars} escaped with
13681 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13682 and only contain characters from the set @samp{`\"$}; however,
13683 characters may be safely listed more than once in @var{chars} for the
13684 sake of syntax highlighting editors.  The current implementation expands
13685 @var{string} after adding escapes; if @var{string} contains macro calls
13686 that in turn expand to text needing shell quoting, you can use
13687 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13689 The default for @var{chars} (@samp{\"$`}) is the set of characters
13690 needing escapes when @var{string} will be used literally within double
13691 quotes.  One common variant is the set of characters to protect when
13692 @var{string} will be used literally within back-ticks or an unquoted
13693 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13694 be used to form a double-quoted string containing the same expansions
13695 that would have occurred if @var{string} were expanded in an unquoted
13696 here-document; however, when using this variant, care must be taken that
13697 @var{string} does not use double quotes within complex variable
13698 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13699 with improper escapes.
13701 This macro is often used with @code{AS_ECHO}.  For an example, observe
13702 the output generated by the shell code generated from this snippet:
13704 @example
13705 foo=bar
13706 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13707 @result{}"$foo" = "bar"
13708 m4_define([macro], [a, [\b]])
13709 AS_ECHO(["AS_ESCAPE([[macro]])"])
13710 @result{}macro
13711 AS_ECHO(["AS_ESCAPE([macro])"])
13712 @result{}a, b
13713 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13714 @result{}a, \b
13715 @end example
13717 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13718 @comment the case of @var{string} that does not contain '.
13719 To escape a string that will be placed within single quotes, use:
13721 @example
13722 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13723 @end example
13724 @end defmac
13726 @defmac AS_EXECUTABLE_P (@var{file})
13727 @asindex{EXECUTABLE_P}
13728 Emit code to probe whether @var{file} is a regular file with executable
13729 permissions (and not a directory with search permissions).  The caller
13730 is responsible for quoting @var{file}.
13731 @end defmac
13733 @defmac AS_EXIT (@dvar{status, $?})
13734 @asindex{EXIT}
13735 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13736 This macro
13737 works around shells that see the exit status of the command prior to
13738 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13739 of Shell Builtins}).
13740 @end defmac
13742 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13743 @asindex{IF}
13744 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13745 run shell code @var{run-if-true1}, else examine further tests.  If no test
13746 exits with a zero status, run shell code @var{run-if-false}, with
13747 simplifications if either @var{run-if-true1} or @var{run-if-false}
13748 is empty.  For example,
13750 @example
13751 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13752       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13753       [echo foo not specified])
13754 @end example
13756 @noindent
13757 ensures any required macros of @code{HANDLE_FOO}
13758 are expanded before the first test.
13759 @end defmac
13761 @defmac AS_MKDIR_P (@var{file-name})
13762 @asindex{MKDIR_P}
13763 Make the directory @var{file-name}, including intervening directories
13764 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13765 except that it is portable to older versions of @command{mkdir} that
13766 lack support for the @option{-p} option or for the @option{--}
13767 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13768 @code{AS_MKDIR_P}
13769 succeeds if @var{file-name} is a symbolic link to an existing directory,
13770 even though Posix is unclear whether @samp{mkdir -p} should
13771 succeed in that case.  If creation of @var{file-name} fails, exit the
13772 script.
13774 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13775 @end defmac
13777 @defmac AS_SET_STATUS (@var{status})
13778 @asindex{SET_STATUS}
13779 Emit shell code to set the value of @samp{$?} to @var{status}, as
13780 efficiently as possible.  However, this is not guaranteed to abort a
13781 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13782 Builtins}).  This should also be used at the end of a complex shell
13783 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13784 a DJGPP shell bug.
13785 @end defmac
13787 @defmac AS_TR_CPP (@var{expression})
13788 @asindex{TR_CPP}
13789 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13790 For example:
13792 @example
13793 # This outputs "#define HAVE_CHAR_P 1".
13794 # Notice the m4 quoting around #, to prevent an m4 comment
13795 type="char *"
13796 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13797 @end example
13798 @end defmac
13800 @defmac AS_TR_SH (@var{expression})
13801 @asindex{TR_SH}
13802 Transform @var{expression} into shell code that generates a valid shell
13803 variable name.  The result is literal when possible at m4 time, but must
13804 be used with @code{eval} if @var{expression} causes shell indirections.
13805 For example:
13807 @example
13808 # This outputs "Have it!".
13809 header="sys/some file.h"
13810 eval AS_TR_SH([HAVE_$header])=yes
13811 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13812 @end example
13813 @end defmac
13815 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13816 @asindex{SET_CATFILE}
13817 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13818 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13819 @var{file} is absolute, etc.).
13820 @end defmac
13822 @defmac AS_UNSET (@var{var})
13823 @asindex{UNSET}
13824 Unsets the shell variable @var{var}, working around bugs in older
13825 shells (@pxref{unset, , Limitations of Shell
13826 Builtins}).  @var{var} can be a literal or indirect variable name.
13827 @end defmac
13829 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13830   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13831 @asindex{VERSION_COMPARE}
13832 Compare two strings @var{version-1} and @var{version-2}, possibly
13833 containing shell variables, as version strings, and expand
13834 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13835 depending upon the result.
13836 The algorithm to compare is similar to the one used by strverscmp in
13837 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13838 The GNU C Library}).
13839 @end defmac
13841 @node Polymorphic Variables
13842 @section Support for indirect variable names
13843 @cindex variable name indirection
13844 @cindex polymorphic variable name
13845 @cindex indirection, variable name
13847 Often, it is convenient to write a macro that will emit shell code
13848 operating on a shell variable.  The simplest case is when the variable
13849 name is known.  But a more powerful idiom is writing shell code that can
13850 work through an indirection, where another variable or command
13851 substitution produces the name of the variable to actually manipulate.
13852 M4sh supports the notion of polymorphic shell variables, making it easy
13853 to write a macro that can deal with either literal or indirect variable
13854 names and output shell code appropriate for both use cases.  Behavior is
13855 undefined if expansion of an indirect variable does not result in a
13856 literal variable name.
13858 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13859   @dvarv{if-simple-ref, if-not})
13860 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13861   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
13862 @asindex{LITERAL_IF}
13863 @asindex{LITERAL_WORD_IF}
13864 If the expansion of @var{expression} is definitely a shell literal,
13865 expand @var{if-literal}.  If the expansion of @var{expression} looks
13866 like it might contain shell indirections (such as @code{$var} or
13867 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13868 possible to output optimized code if @var{expression} consists only of
13869 shell variable expansions (such as @code{$@{var@}}), in which case
13870 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13871 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13872 @var{if-literal} if @var{expression} looks like a single shell word,
13873 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13874 in @var{expression}.
13876 In order to reduce the time spent recognizing whether an
13877 @var{expression} qualifies as a literal or a simple indirection, the
13878 implementation is somewhat conservative: @var{expression} must be a
13879 single shell word (possibly after stripping whitespace), consisting only
13880 of bytes that would have the same meaning whether unquoted or enclosed
13881 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13882 even though it is not a valid shell variable name; while both @samp{'a'}
13883 and @samp{[$]} result in @var{if-not}, because they behave differently
13884 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13885 for recognizing portable file names (such as in the implementation of
13886 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13887 valid variable names (such as in the implementation of @code{AS_TR_SH},
13888 which uses an additional @code{m4_translit} to convert @samp{.} to
13889 @samp{_}).
13891 This example shows how to read the contents of the shell variable
13892 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13893 results in a script that will output the line @samp{hello} three times.
13895 @example
13896 AC_DEFUN([MY_ACTION],
13897 [AS_LITERAL_IF([$1],
13898   [echo "$$1"],
13899 @c $$
13900   [AS_VAR_COPY([var], [$1])
13901    echo "$var"],
13902   [eval 'echo "$'"$1"\"])])
13903 foo=bar bar=hello
13904 MY_ACTION([bar])
13905 MY_ACTION([`echo bar`])
13906 MY_ACTION([$foo])
13907 @end example
13908 @end defmac
13910 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13911 @asindex{VAR_APPEND}
13912 Emit shell code to append the shell expansion of @var{text} to the end
13913 of the current contents of the polymorphic shell variable @var{var},
13914 taking advantage of shells that provide the @samp{+=} extension for more
13915 efficient scaling.
13917 For situations where the final contents of @var{var} are relatively
13918 short (less than 256 bytes), it is more efficient to use the simpler
13919 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13920 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13921 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13922 when the script will be repeatedly appending text into @code{var},
13923 issues of scaling start to become apparent.  A naive implementation
13924 requires execution time linear to the length of the current contents of
13925 @var{var} as well as the length of @var{text} for a single append, for
13926 an overall quadratic scaling with multiple appends.  This macro takes
13927 advantage of shells which provide the extension
13928 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13929 for a single append, for an overall linear scaling with multiple
13930 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13931 @var{text} be quoted properly to avoid field splitting and file name
13932 expansion.
13933 @end defmac
13935 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13936 @asindex{VAR_ARITH}
13937 Emit shell code to compute the arithmetic expansion of @var{expression},
13938 assigning the result as the contents of the polymorphic shell variable
13939 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13940 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13941 syntax for a valid @var{expression} is rather limited: all operators
13942 must occur as separate shell arguments and with proper quoting, there is
13943 no portable equality operator, all variables containing numeric values
13944 must be expanded prior to the computation, all numeric values must be
13945 provided in decimal without leading zeroes, and the first shell argument
13946 should not be a negative number.  In the following example, this snippet
13947 will print @samp{(2+3)*4 == 20}.
13949 @example
13950 bar=3
13951 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13952 echo "(2+$bar)*4 == $foo"
13953 @end example
13954 @end defmac
13956 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13957 @asindex{VAR_COPY}
13958 Emit shell code to assign the contents of the polymorphic shell variable
13959 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13960 executing this M4sh snippet will output @samp{bar hi}:
13962 @example
13963 foo=bar bar=hi
13964 AS_VAR_COPY([a], [foo])
13965 AS_VAR_COPY([b], [$foo])
13966 echo "$a $b"
13967 @end example
13969 When it is necessary to access the contents of an indirect variable
13970 inside a shell double-quoted context, the recommended idiom is to first
13971 copy the contents into a temporary literal shell variable.
13973 @smallexample
13974 for header in stdint_h inttypes_h ; do
13975   AS_VAR_COPY([var], [ac_cv_header_$header])
13976   echo "$header detected: $var"
13977 done
13978 @end smallexample
13979 @end defmac
13981 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13982 @comment trailing newlines uniformly, and forks too much.
13984 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13985   @ovar{if-not-equal})
13986 @asindex{VAR_IF}
13987 Output a shell conditional statement.  If the contents of the
13988 polymorphic shell variable @var{var} match the string @var{word},
13989 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13990 must be a single shell word (typically a quoted string).  Avoids
13991 shell bugs if an interrupt signal arrives while a command substitution
13992 in @var{var} is being expanded.
13993 @end defmac
13995 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13996 @defmacx AS_VAR_POPDEF (@var{m4-name})
13997 @asindex{VAR_PUSHDEF}
13998 @asindex{VAR_POPDEF}
13999 @cindex composing variable names
14000 @cindex variable names, composing
14001 A common M4sh idiom involves composing shell variable names from an m4
14002 argument (for example, writing a macro that uses a cache variable).
14003 @var{value} can be an arbitrary string, which will be transliterated
14004 into a valid shell name by @code{AS_TR_SH}.  In order to access the
14005 composed variable name based on @var{value}, it is easier to declare a
14006 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
14007 that macro as the argument to subsequent @code{AS_VAR} macros as a
14008 polymorphic variable name, and finally free the temporary macro with
14009 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
14010 to avoid excess newlines in the output.
14012 Here is an involved example, that shows the power of writing macros that
14013 can handle composed shell variable names:
14015 @example
14016 m4_define([MY_CHECK_HEADER],
14017 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
14018 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
14019 AS_VAR_POPDEF([my_Header])dnl
14021 MY_CHECK_HEADER([stdint.h])
14022 for header in inttypes.h stdlib.h ; do
14023   MY_CHECK_HEADER([$header])
14024 done
14025 @end example
14027 @noindent
14028 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
14029 variable names.  In the first invocation, the m4 argument is
14030 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
14031 As a result, the temporary macro @code{my_Header} expands to the literal
14032 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
14033 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
14034 temporary macro @code{my_Header} expands to the indirect shell name
14035 @samp{$as_my_Header}.  During the shell execution of the for loop, when
14036 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
14037 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
14038 platform where all three headers have been previously detected, the
14039 output of the script will include:
14041 @smallexample
14042 header stdint.h detected
14043 header inttypes.h detected
14044 header stdlib.h detected
14045 @end smallexample
14046 @end defmac
14048 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14049 @asindex{VAR_SET}
14050 Emit shell code to assign the contents of the polymorphic shell variable
14051 @var{var} to the shell expansion of @var{value}.  @var{value} is not
14052 subject to field splitting or file name expansion, so if command
14053 substitution is used, it may be done with @samp{`""`} rather than using
14054 an intermediate variable (@pxref{Shell Substitutions}).  However,
14055 @var{value} does undergo rescanning for additional macro names; behavior
14056 is unspecified if late expansion results in any shell meta-characters.
14057 @end defmac
14059 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14060 @asindex{VAR_SET_IF}
14061 Emit a shell conditional statement, which executes @var{if-set} if the
14062 polymorphic shell variable @code{var} is set to any value, and
14063 @var{if-undef} otherwise.
14064 @end defmac
14066 @defmac AS_VAR_TEST_SET (@var{var})
14067 @asindex{VAR_TEST_SET}
14068 Emit a shell statement that results in a successful exit status only if
14069 the polymorphic shell variable @code{var} is set.
14070 @end defmac
14072 @node Initialization Macros
14073 @section Initialization Macros
14075 @defmac AS_BOURNE_COMPATIBLE
14076 @asindex{BOURNE_COMPATIBLE}
14077 Set up the shell to be more compatible with the Bourne shell as
14078 standardized by Posix, if possible.  This may involve setting
14079 environment variables, or setting options, or similar
14080 implementation-specific actions.  This macro is deprecated, since
14081 @code{AS_INIT} already invokes it.
14082 @end defmac
14084 @defmac AS_INIT
14085 @asindex{INIT}
14086 @evindex LC_ALL
14087 @evindex SHELL
14088 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14089 outputs the @code{#! /bin/sh} line, a notice about where the output was
14090 generated from, and code to sanitize the environment for the rest of the
14091 script.  Among other initializations, this sets @env{SHELL} to the shell
14092 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14093 ensure the C locale.  Finally, it changes the current diversion to
14094 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14095 and @code{AT_INIT}, so shell code in @file{configure},
14096 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14097 shell environment.
14098 @end defmac
14100 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14101 @asindex{INIT_GENERATED}
14102 Emit shell code to start the creation of a subsidiary shell script in
14103 @var{file}, including changing @var{file} to be executable.  This macro
14104 populates the child script with information learned from the parent
14105 (thus, the emitted code is equivalent in effect, but more efficient,
14106 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14107 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14108 beginning of the child, prior to the shell initialization code, and is
14109 subject to parameter expansion, command substitution, and backslash
14110 quote removal.  The
14111 parent script should check the exit status after this macro, in case
14112 @var{file} could not be properly created (for example, if the disk was
14113 full).  If successfully created, the parent script can then proceed to
14114 append additional M4sh constructs into the child script.
14116 Note that the child script starts life without a log file open, so if
14117 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14118 must temporarily disable any attempts to use the log file until after
14119 emitting code to open a log within the child.  On the other hand, if the
14120 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14121 @samp{1}, then the child script already has code that copies stdout to
14122 that descriptor.  Currently, the suggested
14123 idiom for writing a M4sh shell script from within another script is:
14125 @example
14126 AS_INIT_GENERATED([@var{file}], [[# My child script.
14127 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14128 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14129 cat >> "@var{file}" <<\__EOF__
14130 # Code to initialize AS_MESSAGE_LOG_FD
14131 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14132 # Additional code
14133 __EOF__
14134 @end example
14136 This, however, may change in the future as the M4sh interface is
14137 stabilized further.
14139 Also, be aware that use of @env{LINENO} within the child script may
14140 report line numbers relative to their location in the parent script,
14141 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14142 unable to locate a shell with working @env{LINENO} support.
14143 @end defmac
14145 @defmac AS_LINENO_PREPARE
14146 @asindex{LINENO_PREPARE}
14147 @evindex LINENO
14148 Find a shell that supports the special variable @env{LINENO}, which
14149 contains the number of the currently executing line.  This macro is
14150 automatically invoked by @code{AC_INIT} in configure scripts.
14151 @end defmac
14153 @defmac AS_ME_PREPARE
14154 @asindex{ME_PREPARE}
14155 Set up variable @env{as_me} to be the basename of the currently executing
14156 script.  This macro is automatically invoked by @code{AC_INIT} in
14157 configure scripts.
14158 @end defmac
14160 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14161 @asindex{TMPDIR}
14162 @evindex TMPDIR
14163 @ovindex tmp
14164 Create, as safely as possible, a temporary sub-directory within
14165 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14166 be 2--4 characters, to make it slightly easier to identify the owner of
14167 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14168 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14169 newly created directory is stored in the shell variable @code{tmp}.  On
14170 error, the script is aborted.
14172 Typically, this macro is coupled with some exit traps to delete the created
14173 directory and its contents on exit or interrupt.  However, there is a
14174 slight window between when the directory is created and when the name is
14175 actually known to the shell, so an interrupt at the right moment might
14176 leave the temporary directory behind.  Hence it is important to use a
14177 @var{prefix} that makes it easier to determine if a leftover temporary
14178 directory from an interrupted script is safe to delete.
14180 The use of the output variable @samp{$tmp} rather than something in the
14181 @samp{as_} namespace is historical; it has the unfortunate consequence
14182 that reusing this otherwise common name for any other purpose inside
14183 your script has the potential to break any cleanup traps designed to
14184 remove the temporary directory.
14185 @end defmac
14187 @defmac AS_SHELL_SANITIZE
14188 @asindex{SHELL_SANITIZE}
14189 Initialize the shell suitably for @command{configure} scripts.  This has
14190 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14191 environment variables for predictable results from configuration tests.
14192 For example, it sets @env{LC_ALL} to change to the default C locale.
14193 @xref{Special Shell Variables}.  This macro is deprecated, since
14194 @code{AS_INIT} already invokes it.
14195 @end defmac
14198 @node File Descriptor Macros
14199 @section File Descriptor Macros
14200 @cindex input
14201 @cindex standard input
14202 @cindex file descriptors
14203 @cindex descriptors
14204 @cindex low-level output
14205 @cindex output, low-level
14207 The following macros define file descriptors used to output messages
14208 (or input values) from @file{configure} scripts.
14209 For example:
14211 @example
14212 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14213 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14214 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14215 @end example
14217 @noindent
14218 However doing so is seldom needed, because Autoconf provides higher
14219 level macros as described below.
14221 @defmac AS_MESSAGE_FD
14222 @asindex{MESSAGE_FD}
14223 The file descriptor for @samp{checking for...}  messages and results.
14224 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14225 clients.  However, @code{AC_INIT} shuffles things around to another file
14226 descriptor, in order to allow the @option{-q} option of
14227 @command{configure} to choose whether messages should go to the script's
14228 standard output or be discarded.
14230 If you want to display some messages, consider using one of the printing
14231 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14232 via these macros are also recorded in @file{config.log}.
14233 @end defmac
14235 @anchor{AS_MESSAGE_LOG_FD}
14236 @defmac AS_MESSAGE_LOG_FD
14237 @asindex{MESSAGE_LOG_FD}
14238 This must either be empty, or expand to a file descriptor for log
14239 messages.  By default, @code{AS_INIT} sets this macro to the empty
14240 string for standalone M4sh clients, thus disabling logging.  However,
14241 @code{AC_INIT} shuffles things around so that both @command{configure}
14242 and @command{config.status} use @file{config.log} for log messages.
14243 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14244 Compiler}), redirect all output to this descriptor.  You may want to do
14245 so if you develop such a low-level macro.
14246 @end defmac
14248 @defmac AS_ORIGINAL_STDIN_FD
14249 @asindex{ORIGINAL_STDIN_FD}
14250 This must expand to a file descriptor for the original standard input.
14251 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14252 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14253 safety.
14255 When @command{configure} runs, it may accidentally execute an
14256 interactive command that has the same name as the non-interactive meant
14257 to be used or checked.  If the standard input was the terminal, such
14258 interactive programs would cause @command{configure} to stop, pending
14259 some user input.  Therefore @command{configure} redirects its standard
14260 input from @file{/dev/null} during its initialization.  This is not
14261 normally a problem, since @command{configure} normally does not need
14262 user input.
14264 In the extreme case where your @file{configure} script really needs to
14265 obtain some values from the original standard input, you can read them
14266 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14267 @end defmac
14270 @c =================================================== Writing Autoconf Macros.
14272 @node Writing Autoconf Macros
14273 @chapter Writing Autoconf Macros
14275 When you write a feature test that could be applicable to more than one
14276 software package, the best thing to do is encapsulate it in a new macro.
14277 Here are some instructions and guidelines for writing Autoconf macros.
14279 @menu
14280 * Macro Definitions::           Basic format of an Autoconf macro
14281 * Macro Names::                 What to call your new macros
14282 * Reporting Messages::          Notifying @command{autoconf} users
14283 * Dependencies Between Macros::  What to do when macros depend on other macros
14284 * Obsoleting Macros::           Warning about old ways of doing things
14285 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14286 @end menu
14288 @node Macro Definitions
14289 @section Macro Definitions
14291 @defmac AC_DEFUN (@var{name}, @ovar{body})
14292 @acindex{DEFUN}
14293 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14294 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14295 named @var{name} and with @var{body} as its expansion.  In addition to
14296 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14297 constrain the order in which macros are called, while avoiding redundant
14298 output (@pxref{Prerequisite Macros}).
14299 @end defmac
14301 An Autoconf macro definition looks like this:
14303 @example
14304 AC_DEFUN(@var{macro-name}, @var{macro-body})
14305 @end example
14307 You can refer to any arguments passed to the macro as @samp{$1},
14308 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4,
14309 GNU M4}, for more complete information on writing M4 macros.
14311 Most macros fall in one of two general categories.  The first category
14312 includes macros which take arguments, in order to generate output
14313 parameterized by those arguments.  Macros in this category are designed
14314 to be directly expanded, often multiple times, and should not be used as
14315 the argument to @code{AC_REQUIRE}.  The other category includes macros
14316 which are shorthand for a fixed block of text, and therefore do not take
14317 arguments.  For this category of macros, directly expanding the macro
14318 multiple times results in redundant output, so it is more common to use
14319 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14320 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14322 Be sure to properly quote both the @var{macro-body} @emph{and} the
14323 @var{macro-name} to avoid any problems if the macro happens to have
14324 been previously defined.
14326 Each macro should have a header comment that gives its prototype, and a
14327 brief description.  When arguments have default values, display them in
14328 the prototype.  For example:
14330 @example
14331 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14332 # --------------------------------------
14333 m4_define([AC_MSG_ERROR],
14334   [@{ AS_MESSAGE([error: $1], [2])
14335      exit m4_default([$2], [1]); @}])
14336 @end example
14338 Comments about the macro should be left in the header comment.  Most
14339 other comments make their way into @file{configure}, so just keep
14340 using @samp{#} to introduce comments.
14342 @cindex @code{dnl}
14343 If you have some special comments about pure M4 code, comments
14344 that make no sense in @file{configure} and in the header comment, then
14345 use the builtin @code{dnl}: it causes M4 to discard the text
14346 through the next newline.
14348 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14349 @code{dnl} is more useful to get rid of the newlines following macros
14350 that produce no output, such as @code{AC_REQUIRE}.
14352 Public third-party macros need to use @code{AC_DEFUN}, and not
14353 @code{m4_define}, in order to be found by @command{aclocal}
14354 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14355 Additionally, if it is ever determined that a macro should be made
14356 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14357 in order to have @command{autoupdate} assist the user in choosing a
14358 better alternative, but there is no corresponding way to make
14359 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14361 There is another subtle, but important, difference between using
14362 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14363 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14364 block of text with a @code{m4_define} macro that will expand to the same
14365 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14366 the same content does not necessarily give the same results, because it
14367 changes the location where any embedded but unsatisfied
14368 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14369 example of this, see @ref{Expanded Before Required}.
14371 @node Macro Names
14372 @section Macro Names
14374 All of the public Autoconf macros have all-uppercase names in the
14375 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14376 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14377 internal macros.  All shell variables that they use for internal
14378 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14379 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14380 @command{configure}, files produced by Autoconf make heavy use of the
14381 file system namespace @samp{^conf}.
14383 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14384 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14385 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14386 @file{configure.ac} is also designed to be scanned by Autoheader,
14387 Autoscan, Autoupdate, and Automake, you should be aware of the
14388 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14389 the namespace of a package that does not own the macro or shell code you
14390 are writing.
14392 To ensure that your macros don't conflict with present or future
14393 Autoconf macros, you should prefix your own macro names and any shell
14394 variables they use with some other sequence.  Possibilities include your
14395 initials, or an abbreviation for the name of your organization or
14396 software package.  Historically, people have not always followed the
14397 rule of using a namespace appropriate for their package, and this has
14398 made it difficult for determining the origin of a macro (and where to
14399 report bugs about that macro), as well as difficult for the true
14400 namespace owner to add new macros without interference from pre-existing
14401 uses of third-party macros.  Perhaps the best example of this confusion
14402 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14403 to Gettext.
14405 Most of the Autoconf macros' names follow a structured naming convention
14406 that indicates the kind of feature check by the name.  The macro names
14407 consist of several words, separated by underscores, going from most
14408 general to most specific.  The names of their cache variables use the
14409 same convention (@pxref{Cache Variable Names}, for more information on
14410 them).
14412 The first word of the name after the namespace initials (such as
14413 @samp{AC_}) usually tells the category
14414 of the feature being tested.  Here are the categories used in Autoconf for
14415 specific test macros, the kind of macro that you are more likely to
14416 write.  They are also used for cache variables, in all-lowercase.  Use
14417 them where applicable; where they're not, invent your own categories.
14419 @table @code
14420 @item C
14421 C language builtin features.
14422 @item DECL
14423 Declarations of C variables in header files.
14424 @item FUNC
14425 Functions in libraries.
14426 @item GROUP
14427 Posix group owners of files.
14428 @item HEADER
14429 Header files.
14430 @item LIB
14431 C libraries.
14432 @item PROG
14433 The base names of programs.
14434 @item MEMBER
14435 Members of aggregates.
14436 @item SYS
14437 Operating system features.
14438 @item TYPE
14439 C builtin or declared types.
14440 @item VAR
14441 C variables in libraries.
14442 @end table
14444 After the category comes the name of the particular feature being
14445 tested.  Any further words in the macro name indicate particular aspects
14446 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14447 @command{make} sets a variable to its own name.
14449 An internal macro should have a name that starts with an underscore;
14450 Autoconf internals should therefore start with @samp{_AC_}.
14451 Additionally, a macro that is an internal subroutine of another macro
14452 should have a name that starts with an underscore and the name of that
14453 other macro, followed by one or more words saying what the internal
14454 macro does.  For example, @code{AC_PATH_X} has internal macros
14455 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14457 @node Reporting Messages
14458 @section Reporting Messages
14459 @cindex Messages, from @command{autoconf}
14461 When macros statically diagnose abnormal situations, benign or fatal, it
14462 is possible to make @command{autoconf} detect the problem, and refuse to
14463 create @file{configure} in the case of an error.  The macros in this
14464 section are considered obsolescent, and new code should use M4sugar
14465 macros for this purpose, see @ref{Diagnostic Macros}.
14467 On the other hand, it is possible to want to detect errors when
14468 @command{configure} is run, which are dependent on the environment of
14469 the user rather than the maintainer.  For dynamic diagnostics, see
14470 @ref{Printing Messages}.
14472 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14473 @acindex{DIAGNOSE}
14474 Report @var{message} as a warning (or as an error if requested by the
14475 user) if warnings of the @var{category} are turned on.  This macro is
14476 obsolescent; you are encouraged to use:
14477 @example
14478 m4_warn([@var{category}], [@var{message}])
14479 @end example
14480 @noindent
14481 instead.  @xref{m4_warn}, for more details, including valid
14482 @var{category} names.
14483 @end defmac
14485 @defmac AC_WARNING (@var{message})
14486 @acindex{WARNING}
14487 Report @var{message} as a syntax warning.  This macro is obsolescent;
14488 you are encouraged to use:
14489 @example
14490 m4_warn([syntax], [@var{message}])
14491 @end example
14492 @noindent
14493 instead.  @xref{m4_warn}, for more details, as well as better
14494 finer-grained categories of warnings (not all problems have to do with
14495 syntax).
14496 @end defmac
14498 @defmac AC_FATAL (@var{message})
14499 @acindex{FATAL}
14500 Report a severe error @var{message}, and have @command{autoconf} die.
14501 This macro is obsolescent; you are encouraged to use:
14502 @example
14503 m4_fatal([@var{message}])
14504 @end example
14505 @noindent
14506 instead.  @xref{m4_fatal}, for more details.
14507 @end defmac
14509 When the user runs @samp{autoconf -W error}, warnings from
14510 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14511 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14513 @node Dependencies Between Macros
14514 @section Dependencies Between Macros
14515 @cindex Dependencies between macros
14517 Some Autoconf macros depend on other macros having been called first in
14518 order to work correctly.  Autoconf provides a way to ensure that certain
14519 macros are called if needed and a way to warn the user if macros are
14520 called in an order that might cause incorrect operation.
14522 @menu
14523 * Prerequisite Macros::         Ensuring required information
14524 * Suggested Ordering::          Warning about possible ordering problems
14525 * One-Shot Macros::             Ensuring a macro is called only once
14526 @end menu
14528 @node Prerequisite Macros
14529 @subsection Prerequisite Macros
14530 @cindex Prerequisite macros
14531 @cindex Macros, prerequisites
14533 A macro that you write might need to use values that have previously
14534 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14535 examines the output of @code{flex} or @code{lex}, so it depends on
14536 @code{AC_PROG_LEX} having been called first to set the shell variable
14537 @code{LEX}.
14539 Rather than forcing the user of the macros to keep track of the
14540 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14541 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14542 called if it is needed, and only called once.
14544 @defmac AC_REQUIRE (@var{macro-name})
14545 @acindex{REQUIRE}
14546 If the M4 macro @var{macro-name} has not already been called, call it
14547 (without any arguments).  Make sure to quote @var{macro-name} with
14548 square brackets.  @var{macro-name} must have been defined using
14549 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14550 that it has been called.
14552 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14553 must not be called from the top level.  Also, it does not make sense to
14554 require a macro that takes parameters.
14555 @end defmac
14557 @code{AC_REQUIRE} is often misunderstood.  It really implements
14558 dependencies between macros in the sense that if one macro depends upon
14559 another, the latter is expanded @emph{before} the body of the
14560 former.  To be more precise, the required macro is expanded before
14561 the outermost defined macro in the current expansion stack.
14562 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14563 @code{FOO}.  For instance, this definition of macros:
14565 @example
14566 @group
14567 AC_DEFUN([TRAVOLTA],
14568 [test "$body_temperature_in_celsius" -gt "38" &&
14569   dance_floor=occupied])
14570 AC_DEFUN([NEWTON_JOHN],
14571 [test "x$hair_style" = xcurly &&
14572   dance_floor=occupied])
14573 @end group
14575 @group
14576 AC_DEFUN([RESERVE_DANCE_FLOOR],
14577 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14578   AC_REQUIRE([TRAVOLTA])
14579   AC_REQUIRE([NEWTON_JOHN])
14580 fi])
14581 @end group
14582 @end example
14584 @noindent
14585 with this @file{configure.ac}
14587 @example
14588 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14589 RESERVE_DANCE_FLOOR
14590 if test "x$dance_floor" = xoccupied; then
14591   AC_MSG_ERROR([cannot pick up here, let's move])
14593 @end example
14595 @noindent
14596 does not leave you with a better chance to meet a kindred soul at
14597 other times than Saturday night since it expands into:
14599 @example
14600 @group
14601 test "$body_temperature_in_Celsius" -gt "38" &&
14602   dance_floor=occupied
14603 test "x$hair_style" = xcurly &&
14604   dance_floor=occupied
14606 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14610 @end group
14611 @end example
14613 This behavior was chosen on purpose: (i) it prevents messages in
14614 required macros from interrupting the messages in the requiring macros;
14615 (ii) it avoids bad surprises when shell conditionals are used, as in:
14617 @example
14618 @group
14619 if @dots{}; then
14620   AC_REQUIRE([SOME_CHECK])
14622 @dots{}
14623 SOME_CHECK
14624 @end group
14625 @end example
14627 However, this implementation can lead to another class of problems.
14628 Consider the case where an outer macro first expands, then indirectly
14629 requires, an inner macro:
14631 @example
14632 AC_DEFUN([TESTA], [[echo in A
14633 if test -n "$SEEN_A" ; then echo duplicate ; fi
14634 SEEN_A=:]])
14635 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14636 if test -z "$SEEN_A" ; then echo bug ; fi]])
14637 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14638 AC_DEFUN([OUTER], [[echo in OUTER]
14639 TESTA
14640 TESTC])
14641 OUTER
14642 @end example
14644 @noindent
14645 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14646 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14647 of @code{OUTER}, but because @code{TESTA} had already been directly
14648 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14649 @code{TESTB} occurs prior to its prerequisites, leading to the following
14650 output:
14652 @example
14653 in B
14655 in OUTER
14656 in A
14657 in C
14658 @end example
14660 @noindent
14661 Newer Autoconf is smart enough to recognize this situation, and hoists
14662 @code{TESTA} even though it has already been expanded, but issues a
14663 syntax warning in the process.  This is because the hoisted expansion of
14664 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14665 redundant code, and causes its own set of problems if the hoisted macro
14666 is not idempotent:
14668 @example
14669 in A
14670 in B
14671 in OUTER
14672 in A
14673 duplicate
14674 in C
14675 @end example
14677 The bug is not in Autoconf, but in the macro definitions.  If you ever
14678 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14679 that the macro only needs to be expanded once.  But to enforce this,
14680 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14681 this only helps in Autoconf 2.64 or newer), or all
14682 uses of that macro should be through @code{AC_REQUIRE}; directly
14683 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14684 eliminate redundant expansion.  In the example, this rule of thumb was
14685 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14686 directly expands it.  One way of fixing the bug is to factor
14687 @code{TESTA} into two macros, the portion designed for direct and
14688 repeated use (here, named @code{TESTA}), and the portion designed for
14689 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14690 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14691 calling convention according to their needs:
14693 @example
14694 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14695 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14696 if test -n "$SEEN_A" ; then echo duplicate ; fi
14697 SEEN_A=:]])
14698 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14699 if test -z "$SEEN_A" ; then echo bug ; fi]])
14700 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14701 AC_DEFUN([OUTER], [[echo in OUTER]
14702 TESTA
14703 TESTC])
14704 OUTER
14705 @end example
14707 @noindent
14708 the resulting output will then obey all dependency rules and avoid any
14709 syntax warnings, whether the script is built with old or new Autoconf
14710 versions:
14712 @example
14713 in A_PREREQ
14714 in B
14715 in OUTER
14716 in A
14717 in C
14718 @end example
14720 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14721 enforce expansion of required macros outside of shell conditional
14722 constructs.  You are furthermore encouraged, although not required, to
14723 put all @code{AC_REQUIRE} calls
14724 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14725 lines they leave.
14727 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14728 macro that has not been defined.  However, the @command{aclocal} tool
14729 relies on parsing an incomplete set of input files to trace which macros
14730 have been required, in order to then pull in additional files that
14731 provide those macros; for this particular use case, pre-defining the
14732 macro @code{m4_require_silent_probe} will avoid the warnings.
14734 @node Suggested Ordering
14735 @subsection Suggested Ordering
14736 @cindex Macros, ordering
14737 @cindex Ordering macros
14739 Some macros should be run before another macro if both are called, but
14740 neither @emph{requires} that the other be called.  For example, a macro
14741 that changes the behavior of the C compiler should be called before any
14742 macros that run the C compiler.  Many of these dependencies are noted in
14743 the documentation.
14745 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14746 with this kind of dependency appear out of order in a
14747 @file{configure.ac} file.  The warning occurs when creating
14748 @command{configure} from @file{configure.ac}, not when running
14749 @command{configure}.
14751 For example, @code{AC_PROG_CPP} checks whether the C compiler
14752 can run the C preprocessor when given the @option{-E} option.  It should
14753 therefore be called after any macros that change which C compiler is
14754 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14756 @example
14757 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14758 @end example
14760 @noindent
14761 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14762 when @code{AC_PROG_CC} is called.
14764 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14765 @acindex{BEFORE}
14766 Make M4 print a warning message to the standard error output if
14767 @var{called-macro-name} has already been called.  @var{this-macro-name}
14768 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14769 macro @var{called-macro-name} must have been defined using
14770 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14771 that it has been called.
14772 @end defmac
14774 @node One-Shot Macros
14775 @subsection One-Shot Macros
14776 @cindex One-shot macros
14777 @cindex Macros, called once
14779 Some macros should be called only once, either because calling them
14780 multiple time is unsafe, or because it is bad style.  For instance
14781 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14782 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14783 sense to run these expensive checks more than once.  Such one-shot
14784 macros can be defined using @code{AC_DEFUN_ONCE}.
14786 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14787 @acindex{DEFUN_ONCE}
14788 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14789 Definitions}), but add additional logic that guarantees that only the
14790 first use of the macro (whether by direct expansion or
14791 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14792 expansion will occur before the start of any enclosing macro defined by
14793 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14794 Generally, it does not make sense for @var{macro-body} to use parameters
14795 such as @code{$1}.
14796 @end defmac
14798 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14799 emit a warning if it was directly expanded a second time, so for
14800 portability, it is better to use @code{AC_REQUIRE} than direct
14801 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14802 (@pxref{Prerequisite Macros}).
14804 @node Obsoleting Macros
14805 @section Obsoleting Macros
14806 @cindex Obsoleting macros
14807 @cindex Macros, obsoleting
14809 Configuration and portability technology has evolved over the years.
14810 Often better ways of solving a particular problem are developed, or
14811 ad-hoc approaches are systematized.  This process has occurred in many
14812 parts of Autoconf.  One result is that some of the macros are now
14813 considered @dfn{obsolete}; they still work, but are no longer considered
14814 the best thing to do, hence they should be replaced with more modern
14815 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14816 with their modern implementation.
14818 Autoconf provides a simple means to obsolete a macro.
14820 @anchor{AU_DEFUN}
14821 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14822 @auindex{DEFUN}
14823 Define @var{old-macro} as @var{implementation}.  The only difference
14824 with @code{AC_DEFUN} is that the user is warned that
14825 @var{old-macro} is now obsolete.
14827 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14828 replaced by the modern @var{implementation}.  @var{message} should
14829 include information on what to do after running @command{autoupdate};
14830 @command{autoupdate} prints it as a warning, and includes it
14831 in the updated @file{configure.ac} file.
14833 The details of this macro are hairy: if @command{autoconf} encounters an
14834 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14835 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14836 macros are expanded here, while all other macros are disabled and
14837 appear literally in the updated @file{configure.ac}.
14838 @end defmac
14840 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14841 @auindex{ALIAS}
14842 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14843 with the same parameters.  This happens for example if the macro was renamed.
14844 @end defmac
14846 @node Coding Style
14847 @section Coding Style
14848 @cindex Coding style
14850 The Autoconf macros follow a strict coding style.  You are encouraged to
14851 follow this style, especially if you intend to distribute your macro,
14852 either by contributing it to Autoconf itself or the
14853 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14854 Archive}, or by other means.
14856 The first requirement is to pay great attention to the quotation.  For
14857 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14859 Do not try to invent new interfaces.  It is likely that there is a macro
14860 in Autoconf that resembles the macro you are defining: try to stick to
14861 this existing interface (order of arguments, default values, etc.).  We
14862 @emph{are} conscious that some of these interfaces are not perfect;
14863 nevertheless, when harmless, homogeneity should be preferred over
14864 creativity.
14866 Be careful about clashes both between M4 symbols and between shell
14867 variables.
14869 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14870 you are unlikely to generate conflicts.  Nevertheless, when you need to
14871 set a special value, @emph{avoid using a regular macro name}; rather,
14872 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14873 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14874 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14875 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14876 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14877 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14878 have been used (yes, with the parentheses).
14879 @c or better yet, high-level macros such as @code{m4_expand_once}
14881 No Autoconf macro should ever enter the user-variable name space; i.e.,
14882 except for the variables that are the actual result of running the
14883 macro, all shell variables should start with @code{ac_}.  In
14884 addition, small macros or any macro that is likely to be embedded in
14885 other macros should be careful not to use obvious names.
14887 @cindex @code{dnl}
14888 Do not use @code{dnl} to introduce comments: most of the comments you
14889 are likely to write are either header comments which are not output
14890 anyway, or comments that should make their way into @file{configure}.
14891 There are exceptional cases where you do want to comment special M4
14892 constructs, in which case @code{dnl} is right, but keep in mind that it
14893 is unlikely.
14895 M4 ignores the leading blanks and newlines before each argument.
14896 Use this feature to
14897 indent in such a way that arguments are (more or less) aligned with the
14898 opening parenthesis of the macro being called.  For instance, instead of
14900 @example
14901 AC_CACHE_CHECK(for EMX OS/2 environment,
14902 ac_cv_emxos2,
14903 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14904 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14905 @end example
14907 @noindent
14908 write
14910 @example
14911 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14912 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14913                    [ac_cv_emxos2=yes],
14914                    [ac_cv_emxos2=no])])
14915 @end example
14917 @noindent
14918 or even
14920 @example
14921 AC_CACHE_CHECK([for EMX OS/2 environment],
14922                [ac_cv_emxos2],
14923                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14924                                                    [return __EMX__;])],
14925                                   [ac_cv_emxos2=yes],
14926                                   [ac_cv_emxos2=no])])
14927 @end example
14929 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14930 cross-compiling, provide a pessimistic value (typically @samp{no}).
14932 Feel free to use various tricks to prevent auxiliary tools, such as
14933 syntax-highlighting editors, from behaving improperly.  For instance,
14934 instead of:
14936 @example
14937 m4_bpatsubst([$1], [$"])
14938 @end example
14940 @noindent
14943 @example
14944 m4_bpatsubst([$1], [$""])
14945 @end example
14947 @noindent
14948 so that Emacsen do not open an endless ``string'' at the first quote.
14949 For the same reasons, avoid:
14951 @example
14952 test $[#] != 0
14953 @end example
14955 @noindent
14956 and use:
14958 @example
14959 test $[@@%:@@] != 0
14960 @end example
14962 @noindent
14963 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14964 breaking the bracket-matching highlighting from Emacsen.  Note the
14965 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14966 not escape when it is unnecessary.  Common examples of useless quotation
14967 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14968 etc.  If you add portability issues to the picture, you'll prefer
14969 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14970 better than hacking Autoconf @code{:-)}.
14972 When using @command{sed}, don't use @option{-e} except for indenting
14973 purposes.  With the @code{s} and @code{y} commands, the preferred
14974 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14975 or replacement, in which case you should use @samp{|}, or optionally
14976 @samp{,} if you know the pattern and replacement cannot contain a file
14977 name.  If none of these characters will do, choose a printable character
14978 that cannot appear in the pattern or replacement.  Characters from the
14979 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14980 replacement might contain a file name, since they have special meaning
14981 to the shell and are less likely to occur in file names.
14983 @xref{Macro Definitions}, for details on how to define a macro.  If a
14984 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14985 of an @code{AC_REQUIRE} directive, and macros required by other macros
14986 inside arguments do not need to be expanded before this macro, then
14987 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14988 Also take into account that public third-party macros need to use
14989 @code{AC_DEFUN} in order to be found by @command{aclocal}
14990 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14991 All the @code{AC_REQUIRE} statements should be at the beginning of the
14992 macro, and each statement should be followed by @code{dnl}.
14994 You should not rely on the number of arguments: instead of checking
14995 whether an argument is missing, test that it is not empty.  It provides
14996 both a simpler and a more predictable interface to the user, and saves
14997 room for further arguments.
14999 Unless the macro is short, try to leave the closing @samp{])} at the
15000 beginning of a line, followed by a comment that repeats the name of the
15001 macro being defined.  This introduces an additional newline in
15002 @command{configure}; normally, that is not a problem, but if you want to
15003 remove it you can use @samp{[]dnl} on the last line.  You can similarly
15004 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
15005 is recommended instead of @samp{dnl} to ensure that M4 does not
15006 interpret the @samp{dnl} as being attached to the preceding text or
15007 macro output.  For example, instead of:
15009 @example
15010 AC_DEFUN([AC_PATH_X],
15011 [AC_MSG_CHECKING([for X])
15012 AC_REQUIRE_CPP()
15013 @r{# @dots{}omitted@dots{}}
15014   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15015 fi])
15016 @end example
15018 @noindent
15019 you would write:
15021 @example
15022 AC_DEFUN([AC_PATH_X],
15023 [AC_REQUIRE_CPP()[]dnl
15024 AC_MSG_CHECKING([for X])
15025 @r{# @dots{}omitted@dots{}}
15026   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
15027 fi[]dnl
15028 ])# AC_PATH_X
15029 @end example
15031 If the macro is long, try to split it into logical chunks.  Typically,
15032 macros that check for a bug in a function and prepare its
15033 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
15034 this setup.  Do not hesitate to introduce auxiliary macros to factor
15035 your code.
15037 In order to highlight the recommended coding style, here is a macro
15038 written the old way:
15040 @example
15041 dnl Check for EMX on OS/2.
15042 dnl _AC_EMXOS2
15043 AC_DEFUN(_AC_EMXOS2,
15044 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15045 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15046 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15047 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15048 @end example
15050 @noindent
15051 and the new way:
15053 @example
15054 # _AC_EMXOS2
15055 # ----------
15056 # Check for EMX on OS/2.
15057 m4_define([_AC_EMXOS2],
15058 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15059 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15060                    [ac_cv_emxos2=yes],
15061                    [ac_cv_emxos2=no])])
15062 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15063 ])# _AC_EMXOS2
15064 @end example
15069 @c ============================================= Portable Shell Programming
15071 @node Portable Shell
15072 @chapter Portable Shell Programming
15073 @cindex Portable shell programming
15075 When writing your own checks, there are some shell-script programming
15076 techniques you should avoid in order to make your code portable.  The
15077 Bourne shell and upward-compatible shells like the Korn shell and Bash
15078 have evolved over the years, and many features added to the original
15079 System7 shell are now supported on all interesting porting targets.
15080 However, the following discussion between Russ Allbery and Robert Lipe
15081 is worth reading:
15083 @noindent
15084 Russ Allbery:
15086 @quotation
15087 The GNU assumption that @command{/bin/sh} is the one and only shell
15088 leads to a permanent deadlock.  Vendors don't want to break users'
15089 existing shell scripts, and there are some corner cases in the Bourne
15090 shell that are not completely compatible with a Posix shell.  Thus,
15091 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15092 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15093 Posix shell.
15094 @end quotation
15096 @noindent
15097 Robert Lipe:
15099 @quotation
15100 This is exactly the problem.  While most (at least most System V's) do
15101 have a Bourne shell that accepts shell functions most vendor
15102 @command{/bin/sh} programs are not the Posix shell.
15104 So while most modern systems do have a shell @emph{somewhere} that meets the
15105 Posix standard, the challenge is to find it.
15106 @end quotation
15108 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15109 is to find such a shell.  But to prevent trouble, if you're not using
15110 M4sh you should not take advantage of features that were added after Unix
15111 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15112 negated character classes, or even @command{unset}.  @code{#} comments,
15113 while not in Unix version 7, were retrofitted in the original Bourne
15114 shell and can be assumed to be part of the least common denominator.
15116 On the other hand, if you're using M4sh you can assume that the shell
15117 has the features that were added in SVR2 (circa 1984), including shell
15118 functions,
15119 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15120 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15121 However, some pitfalls have to be avoided for portable use of these
15122 constructs; these will be documented in the rest of this chapter.
15123 See in particular @ref{Shell Functions} and @ref{Limitations of
15124 Builtins, , Limitations of Shell Builtins}.
15126 Some ancient systems have quite
15127 small limits on the length of the @samp{#!} line; for instance, 32
15128 bytes (not including the newline) on SunOS 4.
15129 However, these ancient systems are no longer of practical concern.
15131 The set of external programs you should run in a @command{configure} script
15132 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15133 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15134 restriction allows users to start out with a fairly small set of
15135 programs and build the rest, avoiding too many interdependencies between
15136 packages.
15138 Some of these external utilities have a portable subset of features; see
15139 @ref{Limitations of Usual Tools}.
15141 There are other sources of documentation about shells.  The
15142 specification for the Posix
15143 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15144 Command Language}, though more generous than the restrictive shell
15145 subset described above, is fairly portable nowadays.  Also please see
15146 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15148 @menu
15149 * Shellology::                  A zoology of shells
15150 * Invoking the Shell::          Invoking the shell as a command
15151 * Here-Documents::              Quirks and tricks
15152 * File Descriptors::            FDs and redirections
15153 * Signal Handling::             Shells, signals, and headaches
15154 * File System Conventions::     File names
15155 * Shell Pattern Matching::      Pattern matching
15156 * Shell Substitutions::         Variable and command expansions
15157 * Assignments::                 Varying side effects of assignments
15158 * Parentheses::                 Parentheses in shell scripts
15159 * Slashes::                     Slashes in shell scripts
15160 * Special Shell Variables::     Variables you should not change
15161 * Shell Functions::             What to look out for if you use them
15162 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15163 * Limitations of Usual Tools::  Portable use of portable tools
15164 @end menu
15166 @node Shellology
15167 @section Shellology
15168 @cindex Shellology
15170 There are several families of shells, most prominently the Bourne family
15171 and the C shell family which are deeply incompatible.  If you want to
15172 write portable shell scripts, avoid members of the C shell family.  The
15173 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15174 Shell difference FAQ} includes a small history of Posix shells, and a
15175 comparison between several of them.
15177 Below we describe some of the members of the Bourne shell family.
15179 @table @asis
15180 @item Ash
15181 @cindex Ash
15182 Ash is often used on GNU/Linux and BSD
15183 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15184 bugs that are fixed in the 0.3.x series, but portable shell scripts
15185 should work around them, since version 0.2 is still shipped with many
15186 GNU/Linux distributions.
15188 To be compatible with Ash 0.2:
15190 @itemize @minus
15191 @item
15192 don't use @samp{$?} after expanding empty or unset variables,
15193 or at the start of an @command{eval}:
15195 @example
15196 foo=
15197 false
15198 $foo
15199 echo "Do not use it: $?"
15200 false
15201 eval 'echo "Do not use it: $?"'
15202 @end example
15204 @item
15205 don't use command substitution within variable expansion:
15207 @example
15208 cat $@{FOO=`bar`@}
15209 @end example
15211 @item
15212 beware that single builtin substitutions are not performed by a
15213 subshell, hence their effect applies to the current shell!  @xref{Shell
15214 Substitutions}, item ``Command Substitution''.
15215 @end itemize
15217 @item Bash
15218 @cindex Bash
15219 To detect whether you are running Bash, test whether
15220 @code{BASH_VERSION} is set.  To require
15221 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15222 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15223 Manual}, for details.
15225 @item Bash 2.05 and later
15226 @cindex Bash 2.05 and later
15227 Versions 2.05 and later of Bash use a different format for the
15228 output of the @command{set} builtin, designed to make evaluating its
15229 output easier.  However, this output is not compatible with earlier
15230 versions of Bash (or with many other shells, probably).  So if
15231 you use Bash 2.05 or higher to execute @command{configure},
15232 you'll need to use Bash 2.05 for all other build tasks as well.
15234 @item Ksh
15235 @cindex Ksh
15236 @cindex Korn shell
15237 @prindex @samp{ksh}
15238 @prindex @samp{ksh88}
15239 @prindex @samp{ksh93}
15240 The Korn shell is compatible with the Bourne family and it mostly
15241 conforms to Posix.  It has two major variants commonly
15242 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15243 release.  It is usually called @command{ksh}, but is called @command{sh}
15244 on some hosts if you set your path appropriately.
15246 Solaris systems have three variants:
15247 @prindex @command{/usr/bin/ksh} on Solaris
15248 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15249 standard on Solaris 2.0 and later.
15250 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15251 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15252 @samp{ksh88}; it is standard on Solaris 9 and later.
15253 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15254 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15255 Variants that are not standard may be parts of optional
15256 packages.  There is no extra charge for these packages, but they are
15257 not part of a minimal OS install and therefore some installations may
15258 not have it.
15260 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15261 is also available as @command{/usr/bin/posix/sh}.  If the environment
15262 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15263 the standard shell conform to Posix.
15265 @item Pdksh
15266 @prindex @samp{pdksh}
15267 A public-domain clone of the Korn shell called @command{pdksh} is widely
15268 available: it has most of the @samp{ksh88} features along with a few of
15269 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15270 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15271 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15272 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15273 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15274 at least one respect, see @ref{Shell Substitutions}.
15276 @item Zsh
15277 @cindex Zsh
15278 To detect whether you are running @command{zsh}, test whether
15279 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15280 compatible with the Bourne shell: you must execute @samp{emulate sh},
15281 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15282 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15283 zsh, The Z Shell Manual}, for details.
15285 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15286 Bash in Mac OS X 10.2.
15287 @end table
15289 @node Invoking the Shell
15290 @section Invoking the Shell
15291 @cindex invoking the shell
15292 @cindex shell invocation
15294 The Korn shell (up to at least version M-12/28/93d) has a bug when
15295 invoked on a file whose name does not contain a slash.  It first
15296 searches for the file's name in @env{PATH}, and if found it executes
15297 that rather than the original file.  For example, assuming there is a
15298 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15299 command in the following example fails because the Korn shell finds
15300 @file{/usr/bin/script} and refuses to execute it as a shell script:
15302 @example
15303 $ @kbd{touch xxyzzyz script}
15304 $ @kbd{ksh xxyzzyz}
15305 $ @kbd{ksh ./script}
15306 $ @kbd{ksh script}
15307 ksh: script: cannot execute
15308 @end example
15310 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15311 option-argument ends in backslash-newline, Bash incorrectly reports a
15312 syntax error.  The problem does not occur if a character follows the
15313 backslash:
15315 @example
15316 $ @kbd{$ bash -c 'echo foo \}
15317 > @kbd{'}
15318 bash: -c: line 2: syntax error: unexpected end of file
15319 $ @kbd{bash -c 'echo foo \}
15320 > @kbd{ '}
15322 @end example
15324 @noindent
15325 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15327 @node Here-Documents
15328 @section Here-Documents
15329 @cindex Here-documents
15330 @cindex Shell here-documents
15332 Don't rely on @samp{\} being preserved just because it has no special
15333 meaning together with the next symbol.  In the native @command{sh}
15334 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15335 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15336 use @samp{\\} to get @samp{\}.
15338 With OpenBSD 2.7's @command{sh}
15340 @example
15341 @group
15342 $ @kbd{cat <<EOF
15343 > \" \\
15344 > EOF}
15345 " \
15346 @end group
15347 @end example
15349 @noindent
15350 and with Bash:
15352 @example
15353 @group
15354 bash-2.04$ @kbd{cat <<EOF
15355 > \" \\
15356 > EOF}
15357 \" \
15358 @end group
15359 @end example
15361 Using command substitutions in a here-document that is fed to a shell
15362 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15364 @example
15365 $ @kbd{kitty () @{ cat; @}}
15366 $ @kbd{kitty <<EOF
15367 > `echo ok`
15368 > EOF}
15369 /tmp/sh199886: cannot open
15370 $ @kbd{echo $?}
15372 @end example
15374 Some shells mishandle large here-documents: for example,
15375 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15376 derived from Korn shell version M-12/28/93d, mishandle braced variable
15377 expansion that crosses a 1024- or 4096-byte buffer boundary
15378 within a here-document.  Only the part of the variable name after the boundary
15379 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15380 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15381 boundary, the shell reports an error, as if you used @code{$@{@}}.
15382 Instead of @code{$@{variable-default@}}, the shell may expand
15383 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15384 be worked around by omitting the braces: @code{$variable}.  The bug was
15385 fixed in
15386 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15387 still shipping older versions with the bug.
15389 Empty here-documents are not portable either; with the following code,
15390 @command{zsh} up to at least version 4.3.10 creates a file with a single
15391 newline, whereas other shells create an empty file:
15393 @example
15394 cat >file <<EOF
15396 @end example
15398 Many shells (including the Bourne shell) implement here-documents
15399 inefficiently.  In particular, some shells can be extremely inefficient when
15400 a single statement contains many here-documents.  For instance if your
15401 @file{configure.ac} includes something like:
15403 @example
15404 @group
15405 if <cross_compiling>; then
15406   assume this and that
15407 else
15408   check this
15409   check that
15410   check something else
15411   @dots{}
15412   on and on forever
15413   @dots{}
15415 @end group
15416 @end example
15418 A shell parses the whole @code{if}/@code{fi} construct, creating
15419 temporary files for each here-document in it.  Some shells create links
15420 for such here-documents on every @code{fork}, so that the clean-up code
15421 they had installed correctly removes them.  It is creating the links
15422 that can take the shell forever.
15424 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15425 @code{if}/@code{fi} constructs, would improve the performance
15426 significantly.  Anyway, this kind of construct is not exactly the
15427 typical use of Autoconf.  In fact, it's even not recommended, because M4
15428 macros can't look into shell conditionals, so we may fail to expand a
15429 macro when it was expanded before in a conditional path, and the
15430 condition turned out to be false at runtime, and we end up not
15431 executing the macro at all.
15433 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15434 behavior is only portable for stripping leading @key{TAB}s, and things
15435 can silently break if an overzealous editor converts to using leading
15436 spaces (not all shells are nice enough to warn about unterminated
15437 here-documents).
15439 @example
15440 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15443 done
15444 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15446   2
15448 done
15449 @end example
15451 @node File Descriptors
15452 @section File Descriptors
15453 @cindex Descriptors
15454 @cindex File descriptors
15455 @cindex Shell file descriptors
15457 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15458 stderr, even for subshells.  This might result in undesirable content
15459 if you meant to capture the standard-error output of the inner command:
15461 @example
15462 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15463 $ @kbd{cat stderr}
15464 + eval echo foo >&2
15465 + echo foo
15467 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15468 $ @kbd{cat stderr}
15469 + eval 'echo foo >&2'
15470 ++ echo foo
15472 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15473 @i{# Traces on startup files deleted here.}
15474 $ @kbd{cat stderr}
15475 +zsh:1> eval echo foo >&2
15476 +zsh:1> echo foo
15478 @end example
15480 @noindent
15481 One workaround is to grep out uninteresting lines, hoping not to remove
15482 good ones.
15484 If you intend to redirect both standard error and standard output,
15485 redirect standard output first.  This works better with HP-UX,
15486 since its shell mishandles tracing if standard error is redirected
15487 first:
15489 @example
15490 $ @kbd{sh -x -c ': 2>err >out'}
15491 + :
15492 + 2> err $ @kbd{cat err}
15493 1> out
15494 @end example
15496 Don't try to redirect the standard error of a command substitution.  It
15497 must be done @emph{inside} the command substitution.  When running
15498 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15499 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15501 On the other hand, some shells, such as Solaris or FreeBSD
15502 @command{/bin/sh}, warn about missing programs before performing
15503 redirections.  Therefore, to silently check whether a program exists, it
15504 is necessary to perform redirections on a subshell or brace group:
15505 @example
15506 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15507 nosuch: not found
15508 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15509 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15510 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15511 @end example
15513 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15514 shell pipeline.
15516 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15517 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15519 Some shells, like @command{ash}, don't recognize bi-directional
15520 redirection (@samp{<>}).  And even on shells that recognize it, it is
15521 not portable to use on fifos: Posix does not require read-write support
15522 for named pipes, and Cygwin does not support it:
15524 @example
15525 $ @kbd{mkfifo fifo}
15526 $ @kbd{exec 5<>fifo}
15527 $ @kbd{echo hi >&5}
15528 bash: echo: write error: Communication error on send
15529 @end example
15531 @noindent
15532 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15533 regular files when using @samp{<>}:
15535 @example
15536 $ @kbd{echo a > file}
15537 $ @kbd{bash -c ': 1<>file'; cat file}
15539 $ @kbd{dash -c ': 1<>file'; cat file}
15540 $ rm a
15541 @end example
15543 When catering to old systems, don't redirect the same file descriptor
15544 several times, as you are doomed to failure under Ultrix.
15546 @example
15547 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15548 UWS V4.4 (Rev. 11)
15549 $ @kbd{eval 'echo matter >fullness' >void}
15550 illegal io
15551 $ @kbd{eval '(echo matter >fullness)' >void}
15552 illegal io
15553 $ @kbd{(eval '(echo matter >fullness)') >void}
15554 Ambiguous output redirect.
15555 @end example
15557 @noindent
15558 In each case the expected result is of course @file{fullness} containing
15559 @samp{matter} and @file{void} being empty.  However, this bug is
15560 probably not of practical concern to modern platforms.
15562 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15563 (even if it is redirected) in a loop after the first iteration, or in a
15564 shell function after the first call:
15566 @example
15567 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15568 $ @kbd{ls x*}
15570 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15571 $ @kbd{ls y*}
15573 @end example
15575 @noindent
15576 As a workaround, @command{echo} or @command{eval} can be used.
15578 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15579 subsidiary program.  If any of these descriptors is closed, the
15580 operating system may open an unspecified file for the descriptor in the
15581 new process image.  Posix 2008 says this may be done only if the
15582 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15583 it even for ordinary programs, and the next version of Posix will allow
15584 HP-UX behavior.
15586 If you want a file descriptor above 2 to be inherited into a child
15587 process, then you must use redirections specific to that command or a
15588 containing subshell or command group, rather than relying on
15589 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15590 @command{sh}, file descriptors above 2 which are opened using
15591 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15592 that involved in the fork-and-exec which runs a program or script):
15594 @example
15595 $ @kbd{echo 'echo hello >&5' >k}
15596 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15597 hello
15598 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15599 hello
15600 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15601 ./k[1]: 5: cannot open [Bad file number]
15602 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15603 hello
15604 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15605 hello
15606 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15607 hello
15608 @end example
15610 Don't rely on duplicating a closed file descriptor to cause an
15611 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15612 ignored, which can cause unintended leaks to the original file
15613 descriptor.  In this example, observe the leak to standard output:
15615 @example
15616 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15617 bash: 3: Bad file descriptor
15619 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15622 @end example
15624 Fortunately, an attempt to close an already closed file descriptor will
15625 portably succeed.  Likewise, it is safe to use either style of
15626 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15627 even if it doesn't match the read/write mode that the file descriptor
15628 was opened with.
15630 DOS variants cannot rename or remove open files, such as in
15631 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15632 perfectly portable among Posix hosts.
15634 A few ancient systems reserved some file descriptors.  By convention,
15635 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15636 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15637 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15638 1990), though we don't now remember what it was.  Both these systems are
15639 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15640 other file descriptors.
15642 On the other hand, you can't portably use multi-digit file descriptors.
15643 Solaris @command{ksh} doesn't understand any file descriptor larger than
15644 @samp{9}:
15646 @example
15647 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15649 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15651 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15652 ksh[1]: exec: 10: not found
15654 @end example
15656 @c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15657 @node Signal Handling
15658 @section Signal Handling
15659 @cindex Signal handling in the shell
15660 @cindex Signals, shells and
15662 Portable handling of signals within the shell is another major source of
15663 headaches.  This is worsened by the fact that various different, mutually
15664 incompatible approaches are possible in this area, each with its
15665 distinctive merits and demerits.  A detailed description of these possible
15666 approaches, as well as of their pros and cons, can be found in
15667 @uref{http://www.cons.org/cracauer/sigint.html, this article}.
15669 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15670 @c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15671 the shell still exits with error upon termination by one of those signals,
15672 but in such a case the exit status might be somewhat unexpected (even if
15673 allowed by POSIX, strictly speaking):
15675 @example
15676 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15677 Hangup
15679 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15680 Terminated
15682 $ @kbd{for sig in 1 2 3 15; do}
15683 > @kbd{  echo $sig:}
15684 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15685 > @kbd{done}
15686 signal 1:
15687 Hangup
15689 signal 2:
15691 signal 3:
15693 signal 15:
15695 @end example
15697 This gets even worse if one is using the POSIX ``wait'' interface to get
15698 details about the shell process terminations: it will result in the shell
15699 having exited normally, rather than by receiving a signal.
15701 @example
15702 $ @kbd{cat > foo.c <<'END'}
15703 #include <stdio.h>    /* for printf */
15704 #include <stdlib.h>   /* for system */
15705 #include <sys/wait.h> /* for WIF* macros */
15706 int main(void)
15708   int status = system ("kill -15 $$");
15709   printf ("Terminated by signal: %s\n",
15710           WIFSIGNALED (status) ? "yes" : "no");
15711   printf ("Exited normally: %s\n",
15712           WIFEXITED (status) ? "yes" : "no");
15713   return 0;
15716 @c $$ font-lock
15717 $ @kbd{cc -o foo foo.c}
15718 $ @kbd{./a.out} # On GNU/Linux
15719 Terminated by signal: no
15720 Exited normally: yes
15721 $ @kbd{./a.out} # On Solaris 10
15722 Terminated by signal: yes
15723 Exited normally: no
15724 @end example
15726 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15727 if it is not blocked, and even if the shell is not running interactively
15728 (in fact, even if the shell has no attached tty); among these shells
15729 are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15730 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15731 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15732 these shells.  OTOH, some other shells doesn't special-case the handling
15733 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15734 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15736 @c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15737 Some shells (especially Korn shells and derivatives) might try to
15738 propagate to themselves a signal that has killed a child process; this is
15739 not a bug, but a conscious design choice (although its overall value might
15740 be debatable).  The exact details of how this is attained vary from shell
15741 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15742 the perl process has been interrupted AT&T @code{ksh93} (2011) will
15743 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15744 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15745 128 + 2). In any case, if there is an active trap associated with
15746 @code{SIGINT}, those shells will correctly execute it.
15748 @c See: <http://www.austingroupbugs.net/view.php?id=51>
15749 Some Korn shells, when a child process die due receiving a signal with
15750 signal number @var{n}, can leave in @samp{$?} an exit status of
15751 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15752 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15753 Debian:
15755 @example
15756 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15757 /bin/ksh: line 1: 7837: Hangup
15759 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15760 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15762 @end example
15764 @noindent
15765 This @command{ksh} behavior is allowed by POSIX, if implemented with
15766 due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15767 Austin Group discussion} for more background.  However, if it is not
15768 implemented with proper care, such a behavior might cause problems
15769 in some corner cases.  To see why, assume we have a ``wrapper'' script
15770 like this:
15772 @example
15773 #!/bin/sh
15774 # Ignore some signals in the shell only, not in its child processes.
15775 trap : 1 2 13 15
15776 wrapped_command "$@@"
15777 ret=$?
15778 other_command
15779 exit $ret
15780 @end example
15782 @noindent
15783 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15784 has signal number 1), @code{ret} will be set to 257.  Unless the
15785 @command{exit} shell builtin is smart enough to understand that such
15786 a value can only have originated from a signal, and adjust the final
15787 wait status of the shell appropriately, the value 257 will just get
15788 truncated to 1 by the closing @code{exit} call, so that a caller of
15789 the script will have no way to determine that termination by a signal
15790 was involved.  Observe the different behavior of AT&T @code{ksh93}
15791 (2011) and @code{bash} 4.1.5 on Debian:
15793 @example
15794 $ @kbd{cat foo.sh}
15795 #!/bin/sh
15796 sh -c 'kill -1 $$'
15797 ret=$?
15798 echo $ret
15799 exit $ret
15800 $ @kbd{/bin/ksh foo.sh; echo $?}
15801 foo.sh: line 2: 12479: Hangup
15804 $ @kbd{/bin/bash foo.sh; echo $?}
15805 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15808 @end example
15810 @node File System Conventions
15811 @section File System Conventions
15812 @cindex File system conventions
15814 Autoconf uses shell-script processing extensively, so the file names
15815 that it processes should not contain characters that are special to the
15816 shell.  Special characters include space, tab, newline, NUL, and
15817 the following:
15819 @example
15820 " # $ & ' ( ) * ; < = > ? [ \ ` |
15821 @end example
15823 Also, file names should not begin with @samp{~} or @samp{-}, and should
15824 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15825 immediately after @samp{:}.  On Posix-like platforms, directory names
15826 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15827 path separator.
15829 These restrictions apply not only to the files that you distribute, but
15830 also to the absolute file names of your source, build, and destination
15831 directories.
15833 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15834 they should be avoided.
15836 Posix lets implementations treat leading @file{//} specially, but
15837 requires leading @file{///} and beyond to be equivalent to @file{/}.
15838 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15839 @file{//} as a ``super-root'' that can provide access to files that are
15840 not otherwise reachable from @file{/}.  The super-root tradition began
15841 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15842 has revived it.
15844 While @command{autoconf} and friends are usually run on some Posix
15845 variety, they can be used on other systems, most notably DOS
15846 variants.  This impacts several assumptions regarding file names.
15848 @noindent
15849 For example, the following code:
15851 @example
15852 case $foo_dir in
15853   /*) # Absolute
15854      ;;
15855   *)
15856      foo_dir=$dots$foo_dir ;;
15857 esac
15858 @end example
15860 @noindent
15861 fails to properly detect absolute file names on those systems, because
15862 they can use a drivespec, and usually use a backslash as directory
15863 separator.  If you want to be portable to DOS variants (at the
15864 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15865 you can check for absolute file names like this:
15867 @cindex absolute file names, detect
15868 @example
15869 case $foo_dir in
15870   [\\/]* | ?:[\\/]* ) # Absolute
15871      ;;
15872   *)
15873      foo_dir=$dots$foo_dir ;;
15874 esac
15875 @end example
15877 @noindent
15878 Make sure you quote the brackets if appropriate and keep the backslash as
15879 first character (@pxref{case, , Limitations of Shell Builtins}).
15881 Also, because the colon is used as part of a drivespec, these systems don't
15882 use it as path separator.  When creating or accessing paths, you can use the
15883 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15884 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15885 starts up.
15887 File names need extra care as well.  While DOS variants
15888 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15889 are usually able to handle long file names properly, there are still
15890 limitations that can seriously break packages.  Several of these issues
15891 can be easily detected by the
15892 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15893 package.
15895 A short overview follows; problems are marked with SFN/LFN to
15896 indicate where they apply: SFN means the issues are only relevant to
15897 plain DOS, not to DOS under Microsoft Windows
15898 variants, while LFN identifies problems that exist even under
15899 Microsoft Windows variants.
15901 @table @asis
15902 @item No multiple dots (SFN)
15903 DOS cannot handle multiple dots in file names.  This is an especially
15904 important thing to remember when building a portable configure script,
15905 as @command{autoconf} uses a .in suffix for template files.
15907 This is perfectly OK on Posix variants:
15909 @example
15910 AC_CONFIG_HEADERS([config.h])
15911 AC_CONFIG_FILES([source.c foo.bar])
15912 AC_OUTPUT
15913 @end example
15915 @noindent
15916 but it causes problems on DOS, as it requires @samp{config.h.in},
15917 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15918 to DOS-based environments, you should use this instead:
15920 @example
15921 AC_CONFIG_HEADERS([config.h:config.hin])
15922 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15923 AC_OUTPUT
15924 @end example
15926 @item No leading dot (SFN)
15927 DOS cannot handle file names that start with a dot.  This is usually
15928 not important for @command{autoconf}.
15930 @item Case insensitivity (LFN)
15931 DOS is case insensitive, so you cannot, for example, have both a
15932 file called @samp{INSTALL} and a directory called @samp{install}.  This
15933 also affects @command{make}; if there's a file called @samp{INSTALL} in
15934 the directory, @samp{make install} does nothing (unless the
15935 @samp{install} target is marked as PHONY).
15937 @item The 8+3 limit (SFN)
15938 Because the DOS file system only stores the first 8 characters of
15939 the file name and the first 3 of the extension, those must be unique.
15940 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15941 @file{foobar-prettybird.c} all resolve to the same file name
15942 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15943 @file{foo.bartender}.
15945 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15946 uses numeric
15947 tails in the short version of file names to make them unique.  However, a
15948 registry setting can turn this behavior off.  While this makes it
15949 possible to share file trees containing long file names between SFN
15950 and LFN environments, it also means the above problem applies there
15951 as well.
15953 @item Invalid characters (LFN)
15954 Some characters are invalid in DOS file names, and should therefore
15955 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15956 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15957 In a SFN environment, other characters are also invalid.  These
15958 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15960 @item Invalid names (LFN)
15961 Some DOS file names are reserved, and cause problems if you
15962 try to use files with those names.  These names include @file{CON},
15963 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15964 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15965 File names are case insensitive, so even names like
15966 @file{aux/config.guess} are disallowed.
15968 @end table
15970 @node Shell Pattern Matching
15971 @section Shell Pattern Matching
15972 @cindex Shell pattern matching
15974 Nowadays portable patterns can use negated character classes like
15975 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15976 some shells but not others; hence portable scripts should never use
15977 @samp{^} as the first character of a bracket pattern.
15979 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15980 they may match characters that are not lower-case letters.
15982 @node Shell Substitutions
15983 @section Shell Substitutions
15984 @cindex Shell substitutions
15986 Contrary to a persistent urban legend, the Bourne shell does not
15987 systematically split variables and back-quoted expressions, in particular
15988 on the right-hand side of assignments and in the argument of @code{case}.
15989 For instance, the following code:
15991 @example
15992 case "$given_srcdir" in
15993 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15994 *)  top_srcdir="$dots$given_srcdir" ;;
15995 esac
15996 @end example
15998 @noindent
15999 is more readable when written as:
16001 @example
16002 case $given_srcdir in
16003 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
16004 *)  top_srcdir=$dots$given_srcdir ;;
16005 esac
16006 @end example
16008 @noindent
16009 and in fact it is even @emph{more} portable: in the first case of the
16010 first attempt, the computation of @code{top_srcdir} is not portable,
16011 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
16012 for example Solaris 10 ksh:
16014 @example
16015 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
16016 ksh: : cannot execute
16017 ksh: bar | sed 's, ,,': cannot execute
16018 @end example
16020 @noindent
16021 Posix does not specify behavior for this sequence.  On the other hand,
16022 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
16023 but in practice, not all shells understand it the same way: pdksh 5.2.14
16024 prints spurious quotes when in Posix mode:
16026 @example
16027 $ @kbd{echo "`echo \"hello\"`"}
16028 hello
16029 $ @kbd{set -o posix}
16030 $ @kbd{echo "`echo \"hello\"`"}
16031 "hello"
16032 @end example
16034 @noindent
16035 There is just no portable way to use double-quoted strings inside
16036 double-quoted back-quoted expressions (pfew!).
16038 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
16039 parameter expansions are elided during word splitting.  Meanwhile, zsh
16040 does not perform word splitting except when in Bourne compatibility
16041 mode.  In the example below, the correct behavior is to have five
16042 arguments to the function, and exactly two spaces on either side of the
16043 middle @samp{-}, since word splitting collapses multiple spaces in
16044 @samp{$f} but leaves empty arguments intact.
16046 @example
16047 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16048 3- - -
16049 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16050 5-  -  -
16051 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16052 3-   -   -
16053 $ @kbd{zsh -c 'emulate sh;}
16054 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16055 5-  -  -
16056 @end example
16058 @noindent
16059 You can work around this by doing manual word splitting, such as using
16060 @samp{"$str" $list} rather than @samp{"$str"$list}.
16062 There are also portability pitfalls with particular expansions:
16064 @table @code
16065 @item $@@
16066 @cindex @code{"$@@"}
16067 One of the most famous shell-portability issues is related to
16068 @samp{"$@@"}.  When there are no positional arguments, Posix says
16069 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
16070 original Unix version 7 Bourne shell treated it as equivalent to
16071 @samp{""} instead, and this behavior survives in later implementations
16072 like Digital Unix 5.0.
16074 The traditional way to work around this portability problem is to use
16075 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
16076 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
16077 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
16079 @example
16080 zsh $ @kbd{emulate sh}
16081 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16082 Hello World
16084 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16085 Hello
16086 World
16088 @end example
16090 @noindent
16091 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16092 @samp{"$@@"} because of the portability problems mentioned above.
16093 One workaround relies on Zsh's ``global aliases'' to convert
16094 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16096 @example
16097 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16098 @end example
16100 Zsh only recognizes this alias when a shell word matches it exactly;
16101 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16102 case always yields at least one shell word, use plain @samp{"$@@"}.
16104 A more conservative workaround is to avoid @samp{"$@@"} if it is
16105 possible that there may be no positional arguments.  For example,
16106 instead of:
16108 @example
16109 cat conftest.c "$@@"
16110 @end example
16112 you can use this instead:
16114 @example
16115 case $# in
16116 0) cat conftest.c;;
16117 *) cat conftest.c "$@@";;
16118 esac
16119 @end example
16121 Autoconf macros often use the @command{set} command to update
16122 @samp{$@@}, so if you are writing shell code intended for
16123 @command{configure} you should not assume that the value of @samp{$@@}
16124 persists for any length of time.
16127 @item $@{10@}
16128 @cindex positional parameters
16129 The 10th, 11th, @dots{} positional parameters can be accessed only after
16130 a @code{shift}.  The 7th Edition shell reported an error if given
16131 @code{$@{10@}}, and
16132 Solaris 10 @command{/bin/sh} still acts that way:
16134 @example
16135 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16136 $ @kbd{echo $@{10@}}
16137 bad substitution
16138 @end example
16140 Conversely, not all shells obey the Posix rule that when braces are
16141 omitted, multiple digits beyond a @samp{$} imply the single-digit
16142 positional parameter expansion concatenated with the remaining literal
16143 digits.  To work around the issue, you must use braces.
16145 @example
16146 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16147 a0 a0
16148 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16149 j a0
16150 @end example
16152 @item $@{@var{var}:-@var{value}@}
16153 @c Info cannot handle ':' in index entries.
16154 @ifnotinfo
16155 @cindex @code{$@{@var{var}:-@var{value}@}}
16156 @end ifnotinfo
16157 @cindex @code{$@{@var{var}-@var{value}@}}
16158 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16159 colon for any shell substitution, and complain and die.
16160 Similarly for @code{$@{@var{var}:=@var{value}@}},
16161 @code{$@{@var{var}:?@var{value}@}}, etc.
16162 However, all shells that support functions allow the use of colon in
16163 shell substitution, and since m4sh requires functions, you can portably
16164 use null variable substitution patterns in configure scripts.
16166 @item $@{@var{var}+@var{value}@}
16167 @cindex @code{$@{@var{var}+@var{value}@}}
16168 When using @samp{$@{@var{var}-@var{value}@}} or
16169 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16170 @var{value} must either be a single shell word, quoted, or in the
16171 context of an unquoted here-document.  Solaris
16172 @command{/bin/sh} complains otherwise.
16174 @example
16175 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16176 /bin/sh: bad substitution
16177 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16178 b c
16179 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16180 b c
16181 $ @kbd{/bin/sh -c 'cat <<EOF
16182 $@{a-b c@}
16183 EOF}
16184 b c
16185 @end example
16187 Most shells treat the special parameters @code{*} and @code{@@} as being
16188 unset if there are no positional parameters.  However, some shells treat
16189 them as being set to the empty string.  Posix does not clearly specify
16190 either behavior.
16192 @example
16193 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16194 * is unset.
16195 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16196 * is .
16197 @end example
16199 According to Posix, if an expansion occurs inside double quotes, then
16200 the use of unquoted double quotes within @var{value} is unspecified, and
16201 any single quotes become literal characters; in that case, escaping must
16202 be done with backslash.  Likewise, the use of unquoted here-documents is
16203 a case where double quotes have unspecified results:
16205 @example
16206 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16207 /bin/sh: bad substitution
16208 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16209 b c
16210 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16211 b  c
16212 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16213 b  c
16214 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16215 'b  c'
16216 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16217 "b  c"
16218 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16219 b  c
16220 $ @kbd{/bin/sh -c 'cat <<EOF
16221 $@{a-"b  c"@}
16222 EOF'}
16223 "b  c"
16224 $ @kbd{/bin/sh -c 'cat <<EOF
16225 $@{a-'b  c'@}
16226 EOF'}
16227 'b  c'
16228 $ @kbd{bash -c 'cat <<EOF
16229 $@{a-"b  c"@}
16230 EOF'}
16231 b  c
16232 $ @kbd{bash -c 'cat <<EOF
16233 $@{a-'b  c'@}
16234 EOF'}
16235 'b  c'
16236 @end example
16238 Perhaps the easiest way to work around quoting issues in a manner
16239 portable to all shells is to place the results in a temporary variable,
16240 then use @samp{$t} as the @var{value}, rather than trying to inline
16241 the expression needing quoting.
16243 @example
16244 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16245 b  c"'@}\
16246 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16247 b  c"'@}\
16248 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16249 b  c"'@}\
16250 @end example
16252 @item $@{@var{var}=@var{value}@}
16253 @cindex @code{$@{@var{var}=@var{value}@}}
16254 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16255 to @var{var}, remember that even though the assignment to @var{var} does
16256 not undergo file name expansion, the result of the variable expansion
16257 does unless the expansion occurred within double quotes.  In particular,
16258 when using @command{:} followed by unquoted variable expansion for the
16259 side effect of setting a default value, if the final value of
16260 @samp{$var} contains any globbing characters (either from @var{value} or
16261 from prior contents), the shell has to spend time performing file name
16262 expansion and field splitting even though those results will not be
16263 used.  Therefore, it is a good idea to consider double quotes when performing
16264 default initialization; while remembering how this impacts any quoting
16265 characters appearing in @var{value}.
16267 @example
16268 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16269 /usr/bin/*
16271 real    0m0.005s
16272 user    0m0.002s
16273 sys     0m0.003s
16274 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16275 /usr/bin/*
16277 real    0m0.039s
16278 user    0m0.026s
16279 sys     0m0.009s
16280 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16281 /usr/bin/*
16283 real    0m0.031s
16284 user    0m0.020s
16285 sys     0m0.010s
16287 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16288 /usr/bin/*
16290 real    0m0.006s
16291 user    0m0.002s
16292 sys     0m0.003s
16293 @end example
16295 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16296 if the @var{value} contains more than one shell word; either single
16297 quotes for just the @var{value}, or double quotes around the entire
16298 expansion:
16300 @example
16301 $ @kbd{: $@{var1='Some words'@}}
16302 $ @kbd{: "$@{var2=like this@}"}
16303 $ @kbd{echo $var1 $var2}
16304 Some words like this
16305 @end example
16307 @noindent
16308 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16309 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16310 requires that with @samp{=}, quote removal happens prior to the
16311 assignment, and the expansion be the final contents of @var{var} without
16312 quoting (and thus subject to field splitting), in contrast to the
16313 behavior with @samp{-} passing the quoting through to the final
16314 expansion.  However, @command{bash} 4.1 does not obey this rule.
16316 @example
16317 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16318 a  b
16319 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16320 a b
16321 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16322 a  b
16323 @end example
16325 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16326 commands, it is unspecified whether the assignments affect the parent
16327 shell environment.  It is best to perform assignments independently from
16328 commands, to avoid the problems demonstrated in this example:
16330 @example
16331 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16332 +b+b+
16334 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16335 ++b+
16337 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16338 +b+b+
16340 @end example
16342 @item $@{@var{var}=@var{value}@}
16343 @cindex @code{$@{@var{var}=@var{literal}@}}
16344 Solaris @command{/bin/sh} has a frightening bug in its handling of
16345 literal assignments.  Imagine you need set a variable to a string containing
16346 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16347 when the affected variable was already set.  This bug can be exercised
16348 by running:
16350 @example
16351 $ @kbd{unset foo}
16352 $ @kbd{foo=$@{foo='@}'@}}
16353 $ @kbd{echo $foo}
16355 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16356 $ @kbd{echo $foo}
16358 $ @kbd{foo=$@{foo='@}'@}}
16359 $ @kbd{echo $foo}
16360 @}@}
16361  ^ ugh!
16362 @end example
16364 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16365 though it is enclosed in single quotes.  The problem doesn't happen
16366 using double quotes, or when using a temporary variable holding the
16367 problematic string.
16369 @item $@{@var{var}=@var{expanded-value}@}
16370 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16371 On Ultrix,
16372 running
16374 @example
16375 default="yu,yaa"
16376 : $@{var="$default"@}
16377 @end example
16379 @noindent
16380 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16381 each char is set.  You don't observe the phenomenon using a simple
16382 @samp{echo $var} since apparently the shell resets the 8th bit when it
16383 expands $var.  Here are two means to make this shell confess its sins:
16385 @example
16386 $ @kbd{cat -v <<EOF
16387 $var
16388 EOF}
16389 @end example
16391 @noindent
16394 @example
16395 $ @kbd{set | grep '^var=' | cat -v}
16396 @end example
16398 One classic incarnation of this bug is:
16400 @example
16401 default="a b c"
16402 : $@{list="$default"@}
16403 for c in $list; do
16404   echo $c
16405 done
16406 @end example
16408 @noindent
16409 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16410 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16411 bit set, hence no IFS splitting is performed!!!
16413 One piece of good news is that Ultrix works fine with @samp{:
16414 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16415 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16416 @var{default}!
16418 The portable way out consists in using a double assignment, to switch
16419 the 8th bit twice on Ultrix:
16421 @example
16422 list=$@{list="$default"@}
16423 @end example
16425 @noindent
16426 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16427 use:
16429 @example
16430 test $@{var+y@} || var=@var{@{value@}}
16431 @end example
16433 @item $@{#@var{var}@}
16434 @itemx $@{@var{var}%@var{word}@}
16435 @itemx $@{@var{var}%%@var{word}@}
16436 @itemx $@{@var{var}#@var{word}@}
16437 @itemx $@{@var{var}##@var{word}@}
16438 @cindex @code{$@{#@var{var}@}}
16439 @cindex @code{$@{@var{var}%@var{word}@}}
16440 @cindex @code{$@{@var{var}%%@var{word}@}}
16441 @cindex @code{$@{@var{var}#@var{word}@}}
16442 @cindex @code{$@{@var{var}##@var{word}@}}
16443 Posix requires support for these usages, but they do not work with many
16444 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16446 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16447 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16448 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16449 yields the empty string.
16452 @item `@var{commands}`
16453 @cindex @code{`@var{commands}`}
16454 @cindex Command Substitution
16455 Posix requires shells to trim all trailing newlines from command
16456 output before substituting it, so assignments like
16457 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16458 @samp{$file} ends in a newline.
16460 While in general it makes no sense, do not substitute a single builtin
16461 with side effects, because Ash 0.2, trying to optimize, does not fork a
16462 subshell to perform the command.
16464 For instance, if you wanted to check that @command{cd} is silent, do not
16465 use @samp{test -z "`cd /`"} because the following can happen:
16467 @example
16468 $ @kbd{pwd}
16469 /tmp
16470 $ @kbd{test -z "`cd /`" && pwd}
16472 @end example
16474 @noindent
16475 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16477 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16478 command substitution of a native program, if the end of the substitution
16479 is not aligned with the end of the double quote.  This may be worked
16480 around by inserting another pair of quotes:
16482 @example
16483 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16484 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16485 - broken differ: char 4, line 1
16486 @end example
16488 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16489 replace it with a null string, and wrongly evaluate the enclosing
16490 command before entering the trap or ending the script.  This can lead to
16491 spurious errors:
16493 @example
16494 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16495 $ @kbd{^C}
16496 sh: test: hi: unexpected operator/operand
16497 @end example
16499 @noindent
16500 You can avoid this by assigning the command substitution to a temporary
16501 variable:
16503 @example
16504 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16505          if test "x$res" = xhi; then echo yes; fi'}
16506 $ @kbd{^C}
16507 @end example
16509 @item $(@var{commands})
16510 @cindex @code{$(@var{commands})}
16511 This construct is meant to replace @samp{`@var{commands}`},
16512 and it has most of the problems listed under @code{`@var{commands}`}.
16514 This construct can be
16515 nested while this is impossible to do portably with back quotes.
16516 Although it is almost universally supported, unfortunately Solaris 10
16517 and earlier releases lack it:
16519 @example
16520 $ @kbd{showrev -c /bin/sh | grep version}
16521 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16522 $ @kbd{echo $(echo blah)}
16523 syntax error: `(' unexpected
16524 @end example
16526 @noindent
16527 nor does IRIX 6.5's Bourne shell:
16528 @example
16529 $ @kbd{uname -a}
16530 IRIX firebird-image 6.5 07151432 IP22
16531 $ @kbd{echo $(echo blah)}
16532 $(echo blah)
16533 @end example
16535 If you do use @samp{$(@var{commands})}, make sure that the commands
16536 do not start with a parenthesis, as that would cause confusion with
16537 a different notation @samp{$((@var{expression}))} that in modern
16538 shells is an arithmetic expression not a command.  To avoid the
16539 confusion, insert a space between the two opening parentheses.
16541 Avoid @var{commands} that contain unbalanced parentheses in
16542 here-documents, comments, or case statement patterns, as many shells
16543 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16544 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16546 @example
16547 echo $(case x in x) echo hello;; esac)
16548 @end example
16551 @item $((@var{expression}))
16552 @cindex @code{$((@var{expression}))}
16553 Arithmetic expansion is not portable as some shells (most
16554 notably Solaris 10 @command{/bin/sh}) don't support it.
16556 Among shells that do support @samp{$(( ))}, not all of them obey the
16557 Posix rule that octal and hexadecimal constants must be recognized:
16559 @example
16560 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16562 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16564 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16566 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16567 pdksh:  010 + 0x10 : bad number `0x10'
16568 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16570 @end example
16572 When it is available, using arithmetic expansion provides a noticeable
16573 speedup in script execution; but testing for support requires
16574 @command{eval} to avoid syntax errors.  The following construct is used
16575 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16576 arguments are provided in decimal and without a leading zero, and all
16577 operators are properly quoted and appear as distinct arguments:
16579 @example
16580 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16581   eval 'func_arith ()
16582   @{
16583     func_arith_result=$(( $* ))
16584   @}'
16585 else
16586   func_arith ()
16587   @{
16588     func_arith_result=`expr "$@@"`
16589   @}
16591 func_arith 1 + 1
16592 foo=$func_arith_result
16593 @end example
16596 @item ^
16597 @cindex @code{^} quoting
16598 Always quote @samp{^}, otherwise traditional shells such as
16599 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16601 @end table
16604 @node Assignments
16605 @section Assignments
16606 @cindex Shell assignments
16608 When setting several variables in a row, be aware that the order of the
16609 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16610 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16611 You must use
16612 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16614 Don't rely on the following to find @file{subdir/program}:
16616 @example
16617 PATH=subdir$PATH_SEPARATOR$PATH program
16618 @end example
16620 @noindent
16621 as this does not work with Zsh 3.0.6.  Use something like this
16622 instead:
16624 @example
16625 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16626 @end example
16628 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16629 the status and propagates that of the last statement:
16631 @example
16632 $ @kbd{false || foo=bar; echo $?}
16634 $ @kbd{false || foo=`:`; echo $?}
16636 @end example
16638 @noindent
16639 and to make things even worse, QNX 4.25 just sets the exit status
16640 to 0 in any case:
16642 @example
16643 $ @kbd{foo=`exit 1`; echo $?}
16645 @end example
16647 To assign default values, follow this algorithm:
16649 @enumerate
16650 @item
16651 If the default value is a literal and does not contain any closing
16652 brace, use:
16654 @example
16655 : "$@{var='my literal'@}"
16656 @end example
16658 @item
16659 If the default value contains no closing brace, has to be expanded, and
16660 the variable being initialized is not intended to be IFS-split
16661 (i.e., it's not a list), then use:
16663 @example
16664 : $@{var="$default"@}
16665 @end example
16667 @item
16668 If the default value contains no closing brace, has to be expanded, and
16669 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16670 then use:
16672 @example
16673 var=$@{var="$default"@}
16674 @end example
16676 @item
16677 If the default value contains a closing brace, then use:
16679 @example
16680 test $@{var+y@} || var="has a '@}'"
16681 @end example
16682 @end enumerate
16684 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16685 doubt, just use the last form.  @xref{Shell Substitutions}, items
16686 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16687 for the rationale.
16689 @node Parentheses
16690 @section Parentheses in Shell Scripts
16691 @cindex Shell parentheses
16693 Beware of two opening parentheses in a row, as many shell
16694 implementations treat them specially, and Posix says that a portable
16695 script cannot use @samp{((} outside the @samp{$((} form used for shell
16696 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16697 @samp{(cat)}; but many shells, including
16698 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16699 expression equivalent to @samp{let "cat"}, and may or may not report an
16700 error when they detect that @samp{cat} is not a number.  As another
16701 example, @samp{pdksh} 5.2.14 does not treat the following code
16702 as a traditional shell would:
16704 @example
16705 if ((true) || false); then
16706   echo ok
16708 @end example
16710 @noindent
16711 To work around this problem, insert a space between the two opening
16712 parentheses.  There is a similar problem and workaround with
16713 @samp{$((}; see @ref{Shell Substitutions}.
16715 @node Slashes
16716 @section Slashes in Shell Scripts
16717 @cindex Shell slashes
16719 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16720 arguments that contain two trailing slashes:
16722 @example
16723 $ @kbd{echo / // /// //// .// //.}
16724 / / // /// ./ //.
16725 $ @kbd{x=//}
16726 $ @kbd{eval "echo \$x"}
16728 $ @kbd{set -x}
16729 $ @kbd{echo abc | tr -t ab //}
16730 + echo abc
16731 + tr -t ab /
16733 @end example
16735 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16736 variable is empty and the second double-quote is followed by a word that
16737 begins and ends with slash:
16739 @example
16740 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16742 + echo //ouch/
16743 //ouch/
16744 @end example
16746 However, our understanding is that patches are available, so perhaps
16747 it's not worth worrying about working around these horrendous bugs.
16749 @node Special Shell Variables
16750 @section Special Shell Variables
16751 @cindex Shell variables
16752 @cindex Special shell variables
16754 Some shell variables should not be used, since they can have a deep
16755 influence on the behavior of the shell.  In order to recover a sane
16756 behavior from the shell, some variables should be unset; M4sh takes
16757 care of this and provides fallback values, whenever needed, to cater
16758 for a very old @file{/bin/sh} that does not support @command{unset}.
16759 (@pxref{Portable Shell, , Portable Shell Programming}).
16761 As a general rule, shell variable names containing a lower-case letter
16762 are safe; you can define and use these variables without worrying about
16763 their effect on the underlying system, and without worrying about
16764 whether the shell changes them unexpectedly.  (The exception is the
16765 shell variable @code{status}, as described below.)
16767 Here is a list of names that are known to cause trouble.  This list is
16768 not exhaustive, but you should be safe if you avoid the name
16769 @code{status} and names containing only upper-case letters and
16770 underscores.
16772 @c Alphabetical order, case insensitive, `A' before `a'.
16773 @table @code
16774 @item ?
16775 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16776 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16777 correctly in shell functions (@pxref{Shell Functions}) or in traps
16778 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16779 @samp{$?} to zero after an empty command.
16781 @example
16782 $ @kbd{bash -c 'false; $empty; echo $?'}
16784 $ @kbd{zsh -c 'false; $empty; echo $?'}
16786 @end example
16788 @item _
16789 @evindex _
16790 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16791 the last command executed.
16793 @item BIN_SH
16794 @evindex BIN_SH
16795 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16796 the standard shell conform to Posix.
16798 @item CDPATH
16799 @evindex CDPATH
16800 When this variable is set it specifies a list of directories to search
16801 when invoking @code{cd} with a relative file name that did not start
16802 with @samp{./} or @samp{../}.  Posix
16803 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16804 is used successfully, @code{cd} prints the resulting absolute
16805 file name.  Unfortunately this output can break idioms like
16806 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16807 Also, many shells do not conform to this part of Posix; for
16808 example, @command{zsh} prints the result only if a directory name
16809 other than @file{.} was chosen from @env{CDPATH}.
16811 In practice the shells that have this problem also support
16812 @command{unset}, so you can work around the problem as follows:
16814 @example
16815 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16816 @end example
16818 You can also avoid output by ensuring that your directory name is
16819 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16821 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16822 possible, so you need not worry about this problem in those scripts.
16824 @item CLICOLOR_FORCE
16825 @evindex CLICOLOR_FORCE
16826 When this variable is set, some implementations of tools like
16827 @command{ls} attempt to add color to their output via terminal escape
16828 sequences, even when the output is not directed to a terminal, and can
16829 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16830 which automatically unsets this variable.
16832 @item DUALCASE
16833 @evindex DUALCASE
16834 In the MKS shell, case statements and file name generation are
16835 case-insensitive unless @env{DUALCASE} is nonzero.
16836 Autoconf-generated scripts export this variable when they start up.
16838 @item ENV
16839 @itemx MAIL
16840 @itemx MAILPATH
16841 @itemx PS1
16842 @itemx PS2
16843 @itemx PS4
16844 @evindex ENV
16845 @evindex MAIL
16846 @evindex MAILPATH
16847 @evindex PS1
16848 @evindex PS2
16849 @evindex PS4
16850 These variables should not matter for shell scripts, since they are
16851 supposed to affect only interactive shells.  However, at least one
16852 shell (the pre-3.0 UWIN Korn shell) gets confused about
16853 whether it is interactive, which means that (for example) a @env{PS1}
16854 with a side effect can unexpectedly modify @samp{$?}.  To work around
16855 this bug, M4sh scripts (including @file{configure} scripts) do something
16856 like this:
16858 @example
16859 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16860 PS1='$ '
16861 PS2='> '
16862 PS4='+ '
16863 @end example
16865 @noindent
16866 (actually, there is some complication due to bugs in @command{unset};
16867 @pxref{unset, , Limitations of Shell Builtins}).
16869 @item FPATH
16870 @evindex FPATH
16871 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16872 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16873 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16874 to find whether a command exists, since they might report the wrong
16875 result if @env{FPATH} is also set.
16877 @item GREP_OPTIONS
16878 @evindex GREP_OPTIONS
16879 When this variable is set, some implementations of @command{grep} honor
16880 these options, even if the options include direction to enable colored
16881 output via terminal escape sequences, and the result can cause spurious
16882 failures when the output is not directed to a terminal.  Configure
16883 scripts use M4sh, which automatically unsets this variable.
16885 @item IFS
16886 @evindex IFS
16887 Long ago, shell scripts inherited @env{IFS} from the environment,
16888 but this caused many problems so modern shells ignore any environment
16889 settings for @env{IFS}.
16891 Don't set the first character of @env{IFS} to backslash.  Indeed,
16892 Bourne shells use the first character (backslash) when joining the
16893 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16894 backslash escapes, so you can end up with backspace and other strange
16895 characters.
16897 The proper value for @env{IFS} (in regular code, not when performing
16898 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16899 especially important, as it is used to join the arguments in @samp{$*};
16900 however, note that traditional shells, but also bash-2.04, fail to adhere
16901 to this and join with a space anyway.
16903 M4sh guarantees that @env{IFS} will have the default value at the
16904 beginning of a script, and many macros within autoconf rely on this
16905 setting.  It is okay to use blocks of shell code that temporarily change
16906 the value of @env{IFS} in order to split on another character, but
16907 remember to restore it before expanding further macros.
16909 Unsetting @code{IFS} instead of resetting it to the default sequence
16910 is not suggested, since code that tries to save and restore the
16911 variable's value will incorrectly reset it to an empty value, thus
16912 disabling field splitting:
16914 @example
16915 unset IFS
16916 # default separators used for field splitting
16918 save_IFS=$IFS
16919 IFS=:
16920 # ...
16921 IFS=$save_IFS
16922 # no field splitting performed
16923 @end example
16925 @item LANG
16926 @itemx LC_ALL
16927 @itemx LC_COLLATE
16928 @itemx LC_CTYPE
16929 @itemx LC_MESSAGES
16930 @itemx LC_MONETARY
16931 @itemx LC_NUMERIC
16932 @itemx LC_TIME
16933 @evindex LANG
16934 @evindex LC_ALL
16935 @evindex LC_COLLATE
16936 @evindex LC_CTYPE
16937 @evindex LC_MESSAGES
16938 @evindex LC_MONETARY
16939 @evindex LC_NUMERIC
16940 @evindex LC_TIME
16942 You should set all these variables to @samp{C} because so much
16943 configuration code assumes the C locale and Posix requires that locale
16944 environment variables be set to @samp{C} if the C locale is desired;
16945 @file{configure} scripts and M4sh do that for you.
16946 Export these variables after setting them.
16948 @c  However, some older, nonstandard
16949 @c  systems (notably SCO) break if locale environment variables
16950 @c  are set to @samp{C}, so when running on these systems
16951 @c  Autoconf-generated scripts unset the variables instead.
16953 @item LANGUAGE
16954 @evindex LANGUAGE
16956 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16957 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16958 should set it too.
16960 @item LC_ADDRESS
16961 @itemx LC_IDENTIFICATION
16962 @itemx LC_MEASUREMENT
16963 @itemx LC_NAME
16964 @itemx LC_PAPER
16965 @itemx LC_TELEPHONE
16966 @evindex LC_ADDRESS
16967 @evindex LC_IDENTIFICATION
16968 @evindex LC_MEASUREMENT
16969 @evindex LC_NAME
16970 @evindex LC_PAPER
16971 @evindex LC_TELEPHONE
16973 These locale environment variables are GNU extensions.  They
16974 are treated like their Posix brethren (@env{LC_COLLATE},
16975 etc.)@: as described above.
16977 @item LINENO
16978 @evindex LINENO
16979 Most modern shells provide the current line number in @code{LINENO}.
16980 Its value is the line number of the beginning of the current command.
16981 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16982 a shell that supports @code{LINENO}.  If no such shell is available, it
16983 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16984 instance of the string @code{$LINENO} (not followed by an alphanumeric
16985 character) with the line's number.  In M4sh scripts you should execute
16986 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16987 your script; configure scripts do this automatically in @code{AC_INIT}.
16989 You should not rely on @code{LINENO} within @command{eval} or shell
16990 functions, as the behavior differs in practice.  The presence of a
16991 quoted newline within simple commands can alter which line number is
16992 used as the starting point for @code{$LINENO} substitutions within that
16993 command.  Also, the possibility of the Sed prepass means that you should
16994 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16995 line continuations are used.  Subshells should be OK, though.  In the
16996 following example, lines 1, 9, and 14 are portable, but the other
16997 instances of @code{$LINENO} do not have deterministic values:
16999 @example
17000 @group
17001 $ @kbd{cat lineno}
17002 echo 1. $LINENO
17003 echo "2. $LINENO
17004 3. $LINENO"
17005 cat <<EOF
17006 5. $LINENO
17007 6. $LINENO
17008 7. \$LINENO
17010 ( echo 9. $LINENO )
17011 eval 'echo 10. $LINENO'
17012 eval 'echo 11. $LINENO
17013 echo 12. $LINENO'
17014 echo 13. '$LINENO'
17015 echo 14. $LINENO '
17016 15.' $LINENO
17017 f () @{ echo $1 $LINENO;
17018 echo $1 $LINENO @}
17019 f 18.
17020 echo 19. \
17021 $LINENO
17022 @end group
17023 @group
17024 $ @kbd{bash-3.2 ./lineno}
17025 1. 1
17026 2. 3
17027 3. 3
17028 5. 4
17029 6. 4
17030 7. $LINENO
17031 9. 9
17032 10. 10
17033 11. 12
17034 12. 13
17035 13. $LINENO
17036 14. 14
17037 15. 14
17038 18. 16
17039 18. 17
17040 19. 19
17041 @end group
17042 @group
17043 $ @kbd{zsh-4.3.4 ./lineno}
17044 1. 1
17045 2. 2
17046 3. 2
17047 5. 4
17048 6. 4
17049 7. $LINENO
17050 9. 9
17051 10. 1
17052 11. 1
17053 12. 2
17054 13. $LINENO
17055 14. 14
17056 15. 14
17057 18. 0
17058 18. 1
17059 19. 19
17060 @end group
17061 @group
17062 $ @kbd{pdksh-5.2.14 ./lineno}
17063 1. 1
17064 2. 2
17065 3. 2
17066 5. 4
17067 6. 4
17068 7. $LINENO
17069 9. 9
17070 10. 0
17071 11. 0
17072 12. 0
17073 13. $LINENO
17074 14. 14
17075 15. 14
17076 18. 16
17077 18. 17
17078 19. 19
17079 @end group
17080 @group
17081 $ @kbd{sed '=' <lineno |}
17082 > @kbd{  sed '}
17083 > @kbd{    N}
17084 > @kbd{    s,$,-,}
17085 > @kbd{    t loop}
17086 > @kbd{    :loop}
17087 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17088 > @kbd{    t loop}
17089 > @kbd{    s,-$,,}
17090 > @kbd{    s,^[0-9]*\n,,}
17091 > @kbd{  ' |}
17092 > @kbd{  sh}
17093 1. 1
17094 2. 2
17095 3. 3
17096 5. 5
17097 6. 6
17098 7. \7
17099 9. 9
17100 10. 10
17101 11. 11
17102 12. 12
17103 13. 13
17104 14. 14
17105 15. 15
17106 18. 16
17107 18. 17
17108 19. 20
17109 @end group
17110 @end example
17112 In particular, note that @file{config.status} (and any other subsidiary
17113 script created by @code{AS_INIT_GENERATED}) might report line numbers
17114 relative to the parent script as a result of the potential Sed pass.
17116 @item NULLCMD
17117 @evindex NULLCMD
17118 When executing the command @samp{>foo}, @command{zsh} executes
17119 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17120 compatibility mode and the @command{zsh} version is newer
17121 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17122 and forget to set @env{NULLCMD},
17123 your script might be suspended waiting for data on its standard input.
17125 @item options
17126 @evindex options
17127 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17128 array even after @code{emulate sh}, so it should not be used.
17130 @item PATH_SEPARATOR
17131 @evindex PATH_SEPARATOR
17132 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17133 variable can be set to either @samp{:} or @samp{;} to control the path
17134 separator Bash uses to set up certain environment variables (such as
17135 @env{PATH}).  You can set this variable to @samp{;} if you want
17136 @command{configure} to use @samp{;} as a separator; this might be useful
17137 if you plan to use non-Posix shells to execute files.  @xref{File System
17138 Conventions}, for more information about @code{PATH_SEPARATOR}.
17140 @item POSIXLY_CORRECT
17141 @evindex POSIXLY_CORRECT
17142 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17143 (even empty) causes programs to try harder to conform to Posix.
17144 Autoconf does not directly manipulate this variable, but @command{bash}
17145 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17146 running in Posix mode.  Therefore, take care when exporting or unsetting
17147 this variable, so as not to change whether @command{bash} is in Posix
17148 mode.
17150 @example
17151 $ @kbd{bash --posix -c 'set -o | grep posix}
17152 > @kbd{unset POSIXLY_CORRECT}
17153 > @kbd{set -o | grep posix'}
17154 posix           on
17155 posix           off
17156 @end example
17158 @item PWD
17159 @evindex PWD
17160 Posix 1003.1-2001 requires that @command{cd} and
17161 @command{pwd} must update the @env{PWD} environment variable to point
17162 to the logical name of the current directory, but traditional shells
17163 do not support this.  This can cause confusion if one shell instance
17164 maintains @env{PWD} but a subsidiary and different shell does not know
17165 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17166 points to the wrong directory.  Use @samp{`pwd`} rather than
17167 @samp{$PWD}.
17169 @item RANDOM
17170 @evindex RANDOM
17171 Many shells provide @code{RANDOM}, a variable that returns a different
17172 integer each time it is used.  Most of the time, its value does not
17173 change when it is not used, but on IRIX 6.5 the value changes all
17174 the time.  This can be observed by using @command{set}.  It is common
17175 practice to use @code{$RANDOM} as part of a file name, but code
17176 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17178 @item status
17179 @evindex status
17180 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17181 hence read-only.  Do not use it.
17182 @end table
17184 @node Shell Functions
17185 @section Shell Functions
17186 @cindex Shell Functions
17188 Nowadays, it is difficult to find a shell that does not support
17189 shell functions at all.  However, some differences should be expected.
17191 When declaring a shell function, you must include whitespace between the
17192 @samp{)} after the function name and the start of the compound
17193 expression, to avoid upsetting @command{ksh}.  While it is possible to
17194 use any compound command, most scripts use @samp{@{@dots{}@}}.
17196 @example
17197 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17199 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17200 ksh: syntax error at line 1: `@}' unexpected
17201 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17203 @end example
17205 Inside a shell function, you should not rely on the error status of a
17206 subshell if the last command of that subshell was @code{exit} or
17207 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17208 find a shell that does not exhibit the bug, zsh might be the only shell
17209 present on the user's machine.
17211 Likewise, the state of @samp{$?} is not reliable when entering a shell
17212 function.  This has the effect that using a function as the first
17213 command in a @command{trap} handler can cause problems.
17215 @example
17216 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17219 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17222 @end example
17224 DJGPP bash 2.04 has a bug in that @command{return} from a
17225 shell function which also used a command substitution causes a
17226 segmentation fault.  To work around the issue, you can use
17227 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17228 in the execution flow of the function (@pxref{Common Shell Constructs}).
17230 Not all shells treat shell functions as simple commands impacted by
17231 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17233 @example
17234 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17235 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17236 oops
17237 @end example
17239 Shell variables and functions may share the same namespace, for example
17240 with Solaris 10 @command{/bin/sh}:
17242 @example
17243 $ @kbd{f () @{ :; @}; f=; f}
17244 f: not found
17245 @end example
17247 @noindent
17248 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17249 uses the prefix @samp{as_fn_} for its functions.
17251 Handling of positional parameters and shell options varies among shells.
17252 For example, Korn shells reset and restore trace output (@samp{set -x})
17253 and other options upon function entry and exit.  Inside a function,
17254 IRIX sh sets @samp{$0} to the function name.
17256 It is not portable to pass temporary environment variables to shell
17257 functions.  Solaris @command{/bin/sh} does not see the variable.
17258 Meanwhile, not all shells follow the Posix rule that the assignment must
17259 affect the current environment in the same manner as special built-ins.
17261 @example
17262 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17263 @result{}
17264 @result{}
17265 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17266 @result{}1
17267 @result{}
17268 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17269 @result{}1
17270 @result{}1
17271 @end example
17273 Some ancient Bourne shell variants with function support did not reset
17274 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17275 arguments of the script were lost after the first function invocation.
17276 It is probably not worth worrying about these shells any more.
17278 With AIX sh, a @command{trap} on 0 installed in a shell function
17279 triggers at function exit rather than at script exit.  @xref{trap, ,
17280 Limitations of Shell Builtins}.
17282 @node Limitations of Builtins
17283 @section Limitations of Shell Builtins
17284 @cindex Shell builtins
17285 @cindex Limitations of shell builtins
17287 No, no, we are serious: some shells do have limitations!  :)
17289 You should always keep in mind that any builtin or command may support
17290 options, and therefore differ in behavior with arguments
17291 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17292 can give unexpected results when @code{word} starts with a dash.  It is
17293 often possible to avoid this problem using @samp{echo "x$word"}, taking
17294 the @samp{x} into account later in the pipe.  Many of these limitations
17295 can be worked around using M4sh (@pxref{Programming in M4sh}).
17297 @c This table includes things like `@command{test} (files)', so we can't
17298 @c use @table @command.
17299 @table @asis
17300 @item @command{.}
17301 @c --------------
17302 @prindex @command{.}
17303 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17304 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17305 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17306 some shells, including bash 3.2, implicitly append the current directory
17307 to this @env{PATH} search, even though Posix forbids it.  So if you want
17308 to use @command{.} on a file @file{foo} in the current directory, you
17309 must use @samp{. ./foo}.
17311 Not all shells gracefully handle syntax errors within a sourced file.
17312 On one extreme, some non-interactive shells abort the entire script.  On
17313 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17314 syntax error.
17316 @example
17317 $ @kbd{echo 'fi' > syntax}
17318 $ @kbd{bash -c '. ./syntax; echo $?'}
17319 ./syntax: line 1: syntax error near unexpected token `fi'
17320 ./syntax: line 1: `fi'
17322 $ @kbd{ash -c '. ./syntax; echo $?'}
17323 ./syntax: 1: Syntax error: "fi" unexpected
17324 $ @kbd{zsh -c '. ./syntax; echo $?'}
17325 ./syntax:1: parse error near `fi'
17327 @end example
17329 @item @command{!}
17330 @c --------------
17331 @prindex @command{!}
17332 The Unix version 7 shell did not support
17333 negating the exit status of commands with @command{!}, and this feature
17334 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17335 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17336 bugs when using @command{!}:
17338 @example
17339 $ @kbd{sh -c '! : | :'; echo $?}
17341 $ @kbd{ash -c '! : | :'; echo $?}
17343 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17345 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17346 @{: not found
17347 Syntax error: "@}" unexpected
17349 @end example
17351 Shell code like this:
17353 @example
17354 if ! cmp file1 file2 >/dev/null 2>&1; then
17355   echo files differ or trouble
17357 @end example
17359 is therefore not portable in practice.  Typically it is easy to rewrite
17360 such code, e.g.:
17362 @example
17363 cmp file1 file2 >/dev/null 2>&1 ||
17364   echo files differ or trouble
17365 @end example
17367 More generally, one can always rewrite @samp{! @var{command}} as:
17369 @example
17370 if @var{command}; then (exit 1); else :; fi
17371 @end example
17374 @item @command{@{...@}}
17375 @c --------------------
17376 @prindex @command{@{...@}}
17377 Bash 3.2 (and earlier versions) sometimes does not properly set
17378 @samp{$?} when failing to write redirected output of a compound command.
17379 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17380 not occur with @samp{(@dots{})}.  For example:
17382 @example
17383 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17384 bash: line 1: /bad: Permission denied
17386 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17387 bash: line 1: /bad: Permission denied
17389 @end example
17391 To work around the bug, prepend @samp{:;}:
17393 @example
17394 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17395 bash: line 1: /bad: Permission denied
17397 @end example
17399 Posix requires a syntax error if a brace list has no contents.  However,
17400 not all shells obey this rule; and on shells where empty lists are
17401 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17402 ensure that a brace list is never empty.
17404 @example
17405 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17406 bash: line 1: syntax error near unexpected token `@}'
17407 bash: line 1: `false; @{ @}; echo $?'
17409 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17411 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17413 @end example
17416 @item @command{break}
17417 @c ------------------
17418 @prindex @command{break}
17419 The use of @samp{break 2} etc.@: is safe.
17422 @anchor{case}
17423 @item @command{case}
17424 @c -----------------
17425 @prindex @command{case}
17426 You don't need to quote the argument; no splitting is performed.
17428 You don't need the final @samp{;;}, but you should use it.
17430 Posix requires support for @code{case} patterns with opening
17431 parentheses like this:
17433 @example
17434 case $file_name in
17435   (*.c) echo "C source code";;
17436 esac
17437 @end example
17439 @noindent
17440 but the @code{(} in this example is not portable to many Bourne
17441 shell implementations, which is a pity for those of us using tools that
17442 rely on balanced parentheses.  For instance, with Solaris
17443 @command{/bin/sh}:
17445 @example
17446 $ @kbd{case foo in (foo) echo foo;; esac}
17447 @error{}syntax error: `(' unexpected
17448 @end example
17450 @noindent
17451 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17452 contexts where unbalanced parentheses cause other problems, such as when
17453 using a syntax-highlighting editor that searches for the balancing
17454 counterpart, or more importantly, when using a case statement as an
17455 underquoted argument to an Autoconf macro.  @xref{Balancing
17456 Parentheses}, for tradeoffs involved in various styles of dealing with
17457 unbalanced @samp{)}.
17459 Zsh handles pattern fragments derived from parameter expansions or
17460 command substitutions as though quoted:
17462 @example
17463 $ pat=\?; case aa in ?$pat) echo match;; esac
17464 $ pat=\?; case a? in ?$pat) echo match;; esac
17465 match
17466 @end example
17468 @noindent
17469 Because of a bug in its @code{fnmatch}, Bash fails to properly
17470 handle backslashes in character classes:
17472 @example
17473 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17474 bash-2.02$
17475 @end example
17477 @noindent
17478 This is extremely unfortunate, since you are likely to use this code to
17479 handle Posix or MS-DOS absolute file names.  To work around this
17480 bug, always put the backslash first:
17482 @example
17483 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17485 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17487 @end example
17489 Many Bourne shells cannot handle closing brackets in character classes
17490 correctly.
17492 Some shells also have problems with backslash escaping in case you do not want
17493 to match the backslash: both a backslash and the escaped character match this
17494 pattern.  To work around this, specify the character class in a variable, so
17495 that quote removal does not apply afterwards, and the special characters don't
17496 have to be backslash-escaped:
17498 @example
17499 $ @kbd{case '\' in [\<]) echo OK;; esac}
17501 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17503 @end example
17505 Even with this, Solaris @command{ksh} matches a backslash if the set
17506 contains any
17507 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17509 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17510 a closing parenthesis if not specified in a character class:
17512 @example
17513 $ @kbd{case foo in *\)*) echo fail ;; esac}
17514 fail
17515 $ @kbd{case foo in *')'*) echo fail ;; esac}
17516 fail
17517 @end example
17519 Some shells, such as Ash 0.3.8, are confused by an empty
17520 @code{case}/@code{esac}:
17522 @example
17523 ash-0.3.8 $ @kbd{case foo in esac;}
17524 @error{}Syntax error: ";" unexpected (expecting ")")
17525 @end example
17527 Posix requires @command{case} to give an exit status of 0 if no cases
17528 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17529 rule.  Meanwhile, it is unclear whether a case that matches, but
17530 contains no statements, must also change the exit status to 0.  The M4sh
17531 macro @code{AS_CASE} works around these inconsistencies.
17533 @example
17534 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17536 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17538 @end example
17541 @item @command{cd}
17542 @c ---------------
17543 @prindex @command{cd}
17544 Posix 1003.1-2001 requires that @command{cd} must support
17545 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17546 with @option{-L} being the default.  However, traditional shells do
17547 not support these options, and their @command{cd} command has the
17548 @option{-P} behavior.
17550 Portable scripts should assume neither option is supported, and should
17551 assume neither behavior is the default.  This can be a bit tricky,
17552 since the Posix default behavior means that, for example,
17553 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17554 the current logical directory is a symbolic link.  It is safe to use
17555 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17556 Also, Autoconf-generated scripts check for this problem when computing
17557 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17558 so it is safe to @command{cd} to these variables.
17560 Posix states that behavior is undefined if @command{cd} is given an
17561 explicit empty argument.  Some shells do nothing, some change to the
17562 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17563 the shell rather than returning an error.  Unfortunately, this means
17564 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17565 than @samp{cd $var} (at least the latter is well-behaved in all shells
17566 at changing to @env{HOME}, although this is probably not what you wanted
17567 in a script).  You should check that a directory name was supplied
17568 before trying to change locations.
17570 @xref{Special Shell Variables}, for portability problems involving
17571 @command{cd} and the @env{CDPATH} environment variable.
17572 Also please see the discussion of the @command{pwd} command.
17575 @anchor{echo}
17576 @item @command{echo}
17577 @c -----------------
17578 @prindex @command{echo}
17579 The simple @command{echo} is probably the most surprising source of
17580 portability troubles.  It is not possible to use @samp{echo} portably
17581 unless both options and escape sequences are omitted.  Don't expect any
17582 option.
17584 Do not use backslashes in the arguments, as there is no consensus on
17585 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17586 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17587 The problem is truly @command{echo}: all the shells
17588 understand @samp{'\n'} as the string composed of a backslash and an
17589 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17590 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17591 the first character @samp{s} only, followed by a newline, and then
17592 entirely drop the output of the next echo in a command substitution.
17594 Because of these problems, do not pass a string containing arbitrary
17595 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17596 only if you know that @var{foo}'s value cannot contain backslashes and
17597 cannot start with @samp{-}.
17599 Normally, @command{printf} is safer and easier to use than @command{echo}
17600 and @command{echo -n}.  Thus, you should use @command{printf "%s\n"}
17601 instead of @command{echo}, and similarly use @command{printf %s} instead
17602 of @command{echo -n}.
17604 Older scripts, written before @command{printf} was portable,
17605 sometimes used a here-document as a safer alternative to @command{echo},
17606 like this:
17608 @example
17609 cat <<EOF
17610 $foo
17612 @end example
17615 @item @command{eval}
17616 @c -----------------
17617 @prindex @command{eval}
17618 The @command{eval} command is useful in limited circumstances, e.g.,
17619 using commands like @samp{eval table_$key=\$value} and @samp{eval
17620 value=table_$key} to simulate a hash table when the key is known to be
17621 alphanumeric.
17623 You should also be wary of common bugs in @command{eval} implementations.
17624 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17625 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17626 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17627 @samp{$?} is 0, so they exhibit behavior like this:
17629 @example
17630 $ @kbd{false; eval 'echo $?'}
17632 @end example
17634 The correct behavior here is to output a nonzero value,
17635 but portable scripts should not rely on this.
17637 You should not rely on @code{LINENO} within @command{eval}.
17638 @xref{Special Shell Variables}.
17640 Note that, even though these bugs are easily avoided,
17641 @command{eval} is tricky to use on arbitrary arguments.
17642 It is obviously unwise to use @samp{eval $cmd} if the string value of
17643 @samp{cmd} was derived from an untrustworthy source.  But even if the
17644 string value is valid, @samp{eval $cmd} might not work as intended,
17645 since it causes field splitting and file name expansion to occur twice,
17646 once for the @command{eval} and once for the command itself.  It is
17647 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17648 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17649 equivalent of @samp{cat test;.c} if there happens to be a file named
17650 @file{test;.c} in the current directory; and this in turn
17651 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17652 then execute the command @command{.c}.  To avoid this problem, use
17653 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17655 However, suppose that you want to output the text of the evaluated
17656 command just before executing it.  Assuming the previous example,
17657 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17658 this output doesn't show the user that @samp{test;.c} is the actual name
17659 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17660 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17661 since it mistakenly replaces the contents of @file{bar} by the
17662 string @samp{cat foo}.  No simple, general, and portable solution to
17663 this problem is known.
17665 @item @command{exec}
17666 @c -----------------
17667 @prindex @command{exec}
17668 Posix describes several categories of shell built-ins.  Special
17669 built-ins (such as @command{exit}) must impact the environment of the
17670 current shell, and need not be available through @command{exec}.  All
17671 other built-ins are regular, and must not propagate variable assignments
17672 to the environment of the current shell.  However, the group of regular
17673 built-ins is further distinguished by commands that do not require a
17674 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17675 are offered as a more efficient version of something that must still be
17676 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17677 clear on whether @command{exec} must work with the list of 17 utilities
17678 that are invoked without a @env{PATH} search, and many platforms lack an
17679 executable for some of those built-ins:
17681 @example
17682 $ @kbd{sh -c 'exec cd /tmp'}
17683 sh: line 0: exec: cd: not found
17684 @end example
17686 All other built-ins that provide utilities specified by Posix must have
17687 a counterpart executable that exists on @env{PATH}, although Posix
17688 allows @command{exec} to use the built-in instead of the executable.
17689 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17691 @example
17692 $ @kbd{bash -c 'pwd --version' | head -n1}
17693 bash: line 0: pwd: --: invalid option
17694 pwd: usage: pwd [-LP]
17695 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17696 pwd (GNU coreutils) 6.10
17697 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17698 pdksh: pwd: --: unknown option
17699 @end example
17701 When it is desired to avoid a regular shell built-in, the workaround is
17702 to use some other forwarding command, such as @command{env} or
17703 @command{nice}, that will ensure a path search:
17705 @example
17706 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17707 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17708 true (GNU coreutils) 6.10
17709 $ @kbd{pdksh -c 'env true --version' | head -n1}
17710 true (GNU coreutils) 6.10
17711 @end example
17713 @item @command{exit}
17714 @c -----------------
17715 @prindex @command{exit}
17716 The default value of @command{exit} is supposed to be @code{$?};
17717 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17718 perform @samp{exit 0}.
17720 @example
17721 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17722 fail
17723 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17724 fail
17725 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17726 bash-2.04$
17727 @end example
17729 Using @samp{exit $?} restores the expected behavior.
17731 Some shell scripts, such as those generated by @command{autoconf}, use a
17732 trap to clean up before exiting.  If the last shell command exited with
17733 nonzero status, the trap also exits with nonzero status so that the
17734 invoker can tell that an error occurred.
17736 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17737 trap ignores the @code{exit} command's argument.  In these shells, a trap
17738 cannot determine whether it was invoked by plain @code{exit} or by
17739 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17740 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17743 @anchor{export}
17744 @item @command{export}
17745 @c -------------------
17746 @prindex @command{export}
17747 The builtin @command{export} dubs a shell variable @dfn{environment
17748 variable}.  Each update of exported variables corresponds to an update
17749 of the environment variables.  Conversely, each environment variable
17750 received by the shell when it is launched should be imported as a shell
17751 variable marked as exported.
17753 Alas, many shells, such as Solaris @command{/bin/sh},
17754 IRIX 6.3, IRIX 5.2,
17755 AIX 4.1.5, and Digital Unix 4.0, forget to
17756 @command{export} the environment variables they receive.  As a result,
17757 two variables coexist: the environment variable and the shell
17758 variable.  The following code demonstrates this failure:
17760 @example
17761 #!/bin/sh
17762 echo $FOO
17763 FOO=bar
17764 echo $FOO
17765 exec /bin/sh $0
17766 @end example
17768 @noindent
17769 when run with @samp{FOO=foo} in the environment, these shells print
17770 alternately @samp{foo} and @samp{bar}, although they should print only
17771 @samp{foo} and then a sequence of @samp{bar}s.
17773 Therefore you should @command{export} again each environment variable
17774 that you update; the export can occur before or after the assignment.
17776 Posix is not clear on whether the @command{export} of an undefined
17777 variable causes the variable to be defined with the value of an empty
17778 string, or merely marks any future definition of a variable by that name
17779 for export.  Various shells behave differently in this regard:
17781 @example
17782 $ @kbd{sh -c 'export foo; env | grep foo'}
17783 $ @kbd{ash -c 'export foo; env | grep foo'}
17784 foo=
17785 @end example
17787 Posix requires @command{export} to honor assignments made as arguments,
17788 but older shells do not support this, including @command{/bin/sh} in
17789 Solaris 10.  Portable scripts should separate assignments and exports
17790 into different statements.
17792 @example
17793 $ @kbd{bash -c 'export foo=bar; echo $foo'}
17795 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17796 /bin/sh: foo=bar: is not an identifier
17797 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17799 @end example
17801 Posix requires @command{export} to work with any arbitrary value for the
17802 contents of the variable being exported, as long as the total size of
17803 the environment combined with arguments doesn't exceed @code{ARG_MAX}
17804 when executing a child process.  However, some shells have extensions
17805 that involve interpreting some environment values specially, regardless
17806 of the variable name.  We currently know of one case: all versions of
17807 Bash released prior to 27 September 2014 intepret an environment
17808 variable with an initial content substring of @code{() @{} as an
17809 exported function definition (this is the ``Shellshock'' remote
17810 execution bug, CVE-2014-6271 and friends, where it was possible to
17811 eploit the function parser to cause remote code execution on child bash
17812 startup; newer versions of Bash use special environment variable
17813 @emph{names} instead of values to implement the same feature).
17815 There may be entries inherited into the environment that are not valid
17816 as shell variable names; Posix states that processes should be tolerant
17817 of these names.  Some shells such as @command{dash} do this by removing
17818 those names from the environment at startup, while others such as
17819 @command{bash} hide the entry from shell access but still pass it on to
17820 child processes.  While you can set such names using @command{env} for a
17821 direct child process, you cannot rely on them being preserved through an
17822 intermediate pass through the shell.
17824 @item @command{false}
17825 @c ------------------
17826 @prindex @command{false}
17827 Don't expect @command{false} to exit with status 1: in native
17828 Solaris @file{/bin/false} exits with status 255.
17831 @item @command{for}
17832 @c ----------------
17833 @prindex @command{for}
17834 To loop over positional arguments, use:
17836 @example
17837 for arg
17839   echo "$arg"
17840 done
17841 @end example
17843 @noindent
17844 You may @emph{not} leave the @code{do} on the same line as @code{for},
17845 since some shells improperly grok:
17847 @example
17848 for arg; do
17849   echo "$arg"
17850 done
17851 @end example
17853 If you want to explicitly refer to the positional arguments, given the
17854 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17856 @example
17857 for arg in $@{1+"$@@"@}; do
17858   echo "$arg"
17859 done
17860 @end example
17862 @noindent
17863 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17864 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17865 item @samp{$@@}, for more.
17867 Posix requires support for a @command{for} loop with no list after
17868 @code{in}.  However, Solaris @command{/bin/sh} treats that as a syntax
17869 error.  It is possible to work around this by providing any shell word
17870 that expands to nothing, or by ignoring an obvious sentinel.
17872 @example
17873 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
17874 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
17875 /bin/sh: syntax error at line 1: `;' unexpected
17876 @end example
17878 This syntax problem is most frequently encountered in code that goes
17879 through several layers of expansion, such as an m4 macro or makefile
17880 variable used as a list body, where the first layer of expansion (m4 or
17881 make) can end up expanding to nothing in the version handed to the
17882 shell.  In the makefile context, one common workaround is to use a shell
17883 variable rather than a make variable as the source of the list.
17885 @example
17886 $ @kbd{cat Makefile}
17887 list =
17888 bad:
17889         @@for arg in $(list); do echo $$arg; done
17890 good:
17891         @@list='$(list)'; for arg in $$list; do echo $$arg; done
17892 $ @kbd{make bad 2&>1 | head -n1}
17893 sh: syntax error at line 1: `;' unexpected
17894 $ @kbd{make bad list='a b'}
17897 $ @kbd{make good}
17898 $ @kbd{make good list='a b'}
17901 @end example
17903 In Solaris @command{/bin/sh}, when the list of arguments of a
17904 @command{for} loop starts with @emph{unquoted} tokens looking like
17905 variable assignments, the loop is not executed on those tokens:
17907 @example
17908 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17911 @end example
17913 @noindent
17914 Thankfully, quoting the assignment-like tokens, or starting the list
17915 with other tokens (including unquoted variable expansion that results in
17916 an assignment-like result), avoids the problem, so it is easy to work
17917 around:
17919 @example
17920 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17922 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17925 @end example
17927 @anchor{if}
17928 @item @command{if}
17929 @c ---------------
17930 @prindex @command{if}
17931 Using @samp{!} is not portable.  Instead of:
17933 @example
17934 if ! cmp -s file file.new; then
17935   mv file.new file
17937 @end example
17939 @noindent
17940 use:
17942 @example
17943 if cmp -s file file.new; then :; else
17944   mv file.new file
17946 @end example
17948 @noindent
17949 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17950 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17951 of conditionals:
17953 @example
17954 AS_IF([cmp -s file file.new], [], [mv file.new file])
17955 @end example
17957 This is especially useful in other M4 macros, where the @dfn{then} and
17958 @dfn{else} branches might be macro arguments.
17960 Some very old shells did not reset the exit status from an @command{if}
17961 with no @command{else}:
17963 @example
17964 $ @kbd{if (exit 42); then true; fi; echo $?}
17966 @end example
17968 @noindent
17969 whereas a proper shell should have printed @samp{0}.  But this is no
17970 longer a portability problem; any shell that supports functions gets it
17971 correct.  However, it explains why some makefiles have lengthy
17972 constructs:
17974 @example
17975 if test -f "$file"; then
17976   install "$file" "$dest"
17977 else
17978   :
17980 @end example
17983 @item @command{printf}
17984 @c ------------------
17985 @prindex @command{printf}
17986 A format string starting with a @samp{-} can cause problems.
17987 Bash interprets it as an option and
17988 gives an error.  And @samp{--} to mark the end of options is not good
17989 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17990 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17991 or @samp{%s} is probably easiest:
17993 @example
17994 printf %s -foo
17995 @end example
17997 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17999 @example
18000 $ @kbd{printf '\045'}
18001 bash: printf: `%': missing format character
18002 @end example
18004 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
18005 example, @file{/usr/bin/printf} is buggy, so when using
18006 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
18007 core.
18009 Since @command{printf} is not always a shell builtin, there is a
18010 potential speed penalty for using @code{printf '%s\n'} as a replacement
18011 for an @command{echo} that does not interpret @samp{\} or leading
18012 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
18013 -r --} for this role instead.
18015 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
18016 portable alternatives to both @command{printf} and @command{echo}.
18019 @item @command{pwd}
18020 @c ----------------
18021 @prindex @command{pwd}
18022 With modern shells, plain @command{pwd} outputs a ``logical''
18023 directory name, some of whose components may be symbolic links.  These
18024 directory names are in contrast to ``physical'' directory names, whose
18025 components are all directories.
18027 Posix 1003.1-2001 requires that @command{pwd} must support
18028 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
18029 with @option{-L} being the default.  However, traditional shells do
18030 not support these options, and their @command{pwd} command has the
18031 @option{-P} behavior.
18033 Portable scripts should assume neither option is supported, and should
18034 assume neither behavior is the default.  Also, on many hosts
18035 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
18036 does not require this behavior and portable scripts should not rely on
18039 Typically it's best to use plain @command{pwd}.  On modern hosts this
18040 outputs logical directory names, which have the following advantages:
18042 @itemize @bullet
18043 @item
18044 Logical names are what the user specified.
18045 @item
18046 Physical names may not be portable from one installation
18047 host to another due to network file system gymnastics.
18048 @item
18049 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18050 some parent directory, but plain @command{pwd} cannot fail for this
18051 reason.
18052 @end itemize
18054 Also please see the discussion of the @command{cd} command.
18057 @item @command{read}
18058 @c -----------------
18059 @prindex @command{read}
18060 No options are portable, not even support @option{-r} (Solaris
18061 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
18062 @command{read} as a special built-in, so it may exit if input is
18063 redirected from a non-existent or unreadable file.
18066 @anchor{set}
18067 @item @command{set}
18068 @c ----------------
18069 @prindex @command{set}
18070 With the FreeBSD 6.0 shell, the @command{set} command (without
18071 any options) does not sort its output.
18073 The @command{set} builtin faces the usual problem with arguments
18074 starting with a
18075 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
18076 the end of the options (any argument after @option{--} is a parameter,
18077 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18078 10 @command{/bin/sh}) simply stop option
18079 processing as soon as a non-option argument is found.  Therefore, use
18080 @samp{dummy} or simply @samp{x} to end the option processing, and use
18081 @command{shift} to pop it out:
18083 @example
18084 set x $my_list; shift
18085 @end example
18087 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
18088 longer requires support for this command, and in traditional shells
18089 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18090 makes scripts harder to debug.
18092 Some nonstandard shells do not recognize more than one option
18093 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
18094 better to combine them:
18096 @example
18097 set -ex
18098 @end example
18100 @cindex @command{set -e}
18101 The option @option{-e} has historically been underspecified, with enough
18102 ambiguities to cause numerous differences across various shell
18103 implementations; see for example
18104 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18105 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
18106 documenting a change to Posix 2008 to match @command{ksh88} behavior.
18107 Note that mixing @code{set -e} and shell functions is asking for surprises:
18109 @example
18110 set -e
18111 doit()
18113   rm file
18114   echo one
18116 doit || echo two
18117 @end example
18119 @noindent
18120 According to the recommendation, @samp{one} should always be output
18121 regardless of whether the @command{rm} failed, because it occurs within
18122 the body of the shell function @samp{doit} invoked on the left side of
18123 @samp{||}, where the effects of @samp{set -e} are not enforced.
18124 Likewise, @samp{two} should never be printed, since the failure of
18125 @command{rm} does not abort the function, such that the status of
18126 @samp{doit} is 0.
18128 The BSD shell has had several problems with the @option{-e}
18129 option.  Older versions of the BSD
18130 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18131 @samp{case} when @option{-e} was in effect, causing the shell to exit
18132 unexpectedly in some cases.  This was particularly a problem with
18133 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18134 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18135 wrapper works around the bug (@pxref{Failure in Make Rules}).
18137 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18138 wrongly exit with @option{-e} if the last command within a compound
18139 statement fails and is guarded by an @samp{&&} only.  For example:
18141 @example
18142 #! /bin/sh
18143 set -e
18144 foo=''
18145 test -n "$foo" && exit 1
18146 echo one
18147 if :; then
18148   test -n "$foo" && exit 1
18149   echo two
18150   test -n "$foo" && exit 1
18152 echo three
18153 @end example
18155 @noindent
18156 does not print @samp{three}.  One workaround is to change the last
18157 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18158 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18159 users not to use @samp{sh -e}.
18161 When @samp{set -e} is in effect, a failed command substitution in
18162 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
18164 @example
18165 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18166 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18169 @end example
18171 @noindent
18172 Moreover, a command substitution, successful or not, causes this shell to
18173 exit from a failing outer command even in presence of an @samp{&&} list:
18175 @example
18176 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18178 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18180 @end example
18182 Portable scripts should not use @samp{set -e} if @command{trap} is used
18183 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18184 sometimes enters the trap handler with the exit status of the command
18185 prior to the one that triggered the errexit handler:
18187 @example
18188 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18190 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18192 @end example
18194 @noindent
18195 Thus, when writing a script in M4sh, rather than trying to rely on
18196 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18197 statement where it is desirable to abort on failure.
18199 @cindex @command{set -b}
18200 @cindex @command{set -m}
18201 Job control is not provided by all shells, so the use of @samp{set -m}
18202 or @samp{set -b} must be done with care.  When using @command{zsh} in
18203 native mode, asynchronous notification (@samp{set -b}) is enabled by
18204 default, and using @samp{emulate sh} to switch to Posix mode does not
18205 clear this setting (although asynchronous notification has no impact
18206 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18207 earlier have a bug where job control can be manipulated in interactive
18208 shells, but not in subshells or scripts.  Furthermore, some shells, like
18209 @command{pdksh}, fail to treat subshells as interactive, even though the
18210 parent shell was.
18212 @example
18213 $ @kbd{echo $ZSH_VERSION}
18214 4.3.10
18215 $ @kbd{set -m; echo $?}
18217 $ @kbd{zsh -c 'set -m; echo $?'}
18218 set: can't change option: -m
18219 $ @kbd{(set -m); echo $?}
18220 set: can't change option: -m
18222 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18225 @end example
18227 @cindex @command{set -n}
18228 Use of @command{set -n} (typically via @command{sh -n script}) to
18229 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18230 helpful by informing you about better syntax, but switching the script
18231 to use the suggested syntax in order to silence the warnings would
18232 render the script no longer portable to older shells:
18234 @example
18235 $ @kbd{ksh -nc '``'}
18236 ksh: warning: line 1: `...` obsolete, use $(...)
18238 @end example
18240 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18241 into an infinite loop; even with that bug fixed, Solaris 8
18242 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18243 itself uses @command{sh -n} within its testsuite to check that correct
18244 scripts were generated, but only after first probing for other shell
18245 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18246 a reasonably fast and working implementation.
18248 @item @command{shift}
18249 @c ------------------
18250 @prindex @command{shift}
18251 Not only is @command{shift}ing a bad idea when there is nothing left to
18252 shift, but in addition it is not portable: the shell of MIPS
18253 RISC/OS 4.52 refuses to do it.
18255 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18256 it is also absent in many pre-Posix shells.
18259 @item @command{source}
18260 @c -------------------
18261 @prindex @command{source}
18262 This command is not portable, as Posix does not require it; use
18263 @command{.} instead.
18266 @item @command{test}
18267 @c -----------------
18268 @prindex @command{test}
18269 The @code{test} program is the way to perform many file and string
18270 tests.  It is often invoked by the alternate name @samp{[}, but using
18271 that name in Autoconf code is asking for trouble since it is an M4 quote
18272 character.
18274 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18275 present in all implementations, and have been marked obsolete by Posix
18276 2008.  This is because there are inherent ambiguities in using them.
18277 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18278 check whether two strings are both non-empty, but if @samp{$1} is the
18279 literal @samp{!}, then some implementations of @command{test} treat it
18280 as a negation of the unary operator @option{-a}.
18282 Thus, portable uses of @command{test} should never have more than four
18283 arguments, and scripts should use shell constructs like @samp{&&} and
18284 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18285 statement, keep in mind that they have equal precedence, so it is often
18286 better to parenthesize even when this is redundant.  For example:
18288 @smallexample
18289 # Not portable:
18290 test "X$a" = "X$b" -a \
18291   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18293 # Portable:
18294 test "X$a" = "X$b" &&
18295   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18296 @end smallexample
18298 @command{test} does not process options like most other commands do; for
18299 example, it does not recognize the @option{--} argument as marking the
18300 end of options.
18302 It is safe to use @samp{!} as a @command{test} operator.  For example,
18303 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18304 -d foo; @dots{}} is not.
18307 @item @command{test} (files)
18308 @c -------------------------
18309 To enable @command{configure} scripts to support cross-compilation, they
18310 shouldn't do anything that tests features of the build system instead of
18311 the host system.  But occasionally you may find it necessary to check
18312 whether some arbitrary file exists.  To do so, use @samp{test -f},
18313 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18314 Solaris 10 @command{/bin/sh}
18315 lacks it.  To test for symbolic links on systems that have them, use
18316 @samp{test -h} rather than @samp{test -L}; either form conforms to
18317 Posix 1003.1-2001, but older shells like Solaris 8
18318 @code{/bin/sh} support only @option{-h}.
18320 For historical reasons, Posix reluctantly allows implementations of
18321 @samp{test -x} that will succeed for the root user, even if no execute
18322 permissions are present.  Furthermore, shells do not all agree on
18323 whether Access Control Lists should affect @samp{test -r}, @samp{test
18324 -w}, and @samp{test -x}; some shells base test results strictly on the
18325 current user id compared to file owner and mode, as if by
18326 @code{stat(2)}; while other shells base test results on whether the
18327 current user has the given right, even if that right is only granted by
18328 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18329 time of check to time of use race between any use of @command{test}
18330 followed by operating on the just-checked file.  Therefore, it is a good
18331 idea to write scripts that actually attempt an operation, and are
18332 prepared for the resulting failure if permission is denied, rather than
18333 trying to avoid an operation based solely on whether @command{test}
18334 guessed that it might not be permitted.
18336 @item @command{test} (strings)
18337 @c ---------------------------
18338 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18339 not null, but this usage is not portable to traditional platforms like
18340 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18341 @samp{-n}.  However, it @emph{is} portable to test if a variable is set
18342 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18343 implementations properly distinguish between no arguments and a
18344 known-safe string of @samp{y}.
18346 Posix also says that @samp{test ! "@var{string}"},
18347 @samp{test -n "@var{string}"} and
18348 @samp{test -z "@var{string}"} work with any string, but many
18349 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18350 Digital Unix 4, etc.)@: get confused if
18351 @var{string} looks like an operator:
18353 @example
18354 $ @kbd{test -n =}
18355 test: argument expected
18356 $ @kbd{test ! -n}
18357 test: argument expected
18358 $ @kbd{test -z ")"; echo $?}
18360 @end example
18362 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18363 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18364 strings, but in practice this is not true for troublesome strings that
18365 look like operators or parentheses, or that begin with @samp{-}.
18367 It is best to protect such strings with a leading @samp{X}, e.g.,
18368 @samp{test "X@var{string}" != X} rather than @samp{test -n
18369 "@var{string}"} or @samp{test ! "@var{string}"}.
18371 It is common to find variations of the following idiom:
18373 @example
18374 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18375   @var{action}
18376 @end example
18378 @noindent
18379 to take an action when a token matches a given pattern.  Such constructs
18380 should be avoided by using:
18382 @example
18383 case $ac_feature in
18384   *[!-a-zA-Z0-9_]*) @var{action};;
18385 esac
18386 @end example
18388 If the pattern is a complicated regular expression that cannot be
18389 expressed as a shell pattern, use something like this instead:
18391 @example
18392 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18393   @var{action}
18394 @end example
18396 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18397 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18398 @samp{@var{foo}} contains backslashes.
18401 @anchor{trap}
18402 @item @command{trap}
18403 @c -----------------
18404 @prindex @command{trap}
18405 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18406 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18407 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18408 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18409 will invoke the trap at the end of this function.
18411 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18412 specified signals to their default values, but many common shells (e.g.,
18413 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18414 ``command'' named @command{-} when the specified conditions arise.
18415 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18416 reset traps, as this is supported by a larger set of shells, but there
18417 are still shells like @command{dash} that mistakenly try to execute
18418 @command{1} instead of resetting the traps.  Therefore, there is no
18419 portable workaround, except for @samp{trap - 0}, for which
18420 @samp{trap '' 0} is a portable substitute.
18422 Although Posix is not absolutely clear on this point, it is widely
18423 admitted that when entering the trap @samp{$?} should be set to the exit
18424 status of the last command run before the trap.  The ambiguity can be
18425 summarized as: ``when the trap is launched by an @command{exit}, what is
18426 the @emph{last} command run: that before @command{exit}, or
18427 @command{exit} itself?''
18429 Bash considers @command{exit} to be the last command, while Zsh and
18430 Solaris @command{/bin/sh} consider that when the trap is run it is
18431 @emph{still} in the @command{exit}, hence it is the previous exit status
18432 that the trap receives:
18434 @example
18435 $ @kbd{cat trap.sh}
18436 trap 'echo $?' 0
18437 (exit 42); exit 0
18438 $ @kbd{zsh trap.sh}
18440 $ @kbd{bash trap.sh}
18442 @end example
18444 The portable solution is then simple: when you want to @samp{exit 42},
18445 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18446 set the exit status to 42 for Zsh, and the second to trigger the trap
18447 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18448 @code{AS_EXIT}.
18450 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18451 reset to 0 by empty lines if the code is inside @command{trap}.
18453 @example
18454 $ @kbd{trap 'false}
18456 echo $?' 0
18457 $ @kbd{exit}
18459 @end example
18461 @noindent
18462 Fortunately, this bug only affects @command{trap}.
18464 Several shells fail to execute an exit trap that is defined inside a
18465 subshell, when the last command of that subshell is not a builtin.  A
18466 workaround is to use @samp{exit $?} as the shell builtin.
18468 @example
18469 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18471 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18472 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18474 @end example
18476 @noindent
18477 Likewise, older implementations of @command{bash} failed to preserve
18478 @samp{$?} across an exit trap consisting of a single cleanup command.
18480 @example
18481 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18483 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18485 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18487 @end example
18489 Be aware that a trap can be called from any number of places in your
18490 script, and therefore the trap handler should not make assumptions about
18491 shell state.  For some examples, if your script temporarily modifies
18492 @env{IFS}, then the trap should include an initialization back to its
18493 typical value of space-tab-newline (autoconf does this for generated
18494 @file{configure} files).  Likewise, if your script changes the current
18495 working directory at some point after the trap is installed, then your
18496 trap cannot assume which directory it is in, and should begin by
18497 changing directories to an absolute path if that is important to the
18498 cleanup efforts (autotest does this for generated @file{testsuite}
18499 files).
18501 @item @command{true}
18502 @c -----------------
18503 @prindex @command{true}
18504 @c Info cannot handle `:' in index entries.
18505 @c @prindex @command{:}
18506 Don't worry: as far as we know @command{true} is portable.
18507 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18508 portable shell community tends to prefer using @command{:}.  This has a
18509 funny side effect: when asked whether @command{false} is more portable
18510 than @command{true} Alexandre Oliva answered:
18512 @quotation
18513 In a sense, yes, because if it doesn't exist, the shell will produce an
18514 exit status of failure, which is correct for @command{false}, but not
18515 for @command{true}.
18516 @end quotation
18518 Remember that even though @samp{:} ignores its arguments, it still takes
18519 time to compute those arguments.  It is a good idea to use double quotes
18520 around any arguments to @samp{:} to avoid time spent in field splitting
18521 and file name expansion.
18524 @anchor{unset}
18525 @item @command{unset}
18526 @c ------------------
18527 @prindex @command{unset}
18528 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18529 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18530 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18531 with @code{set -e} operation.  You can use
18533 @smallexample
18534 FOO=; unset FOO
18535 @end smallexample
18537 @noindent
18538 if you are not sure that @code{FOO} is set.
18540 A few ancient shells lack @command{unset} entirely.  For some variables
18541 such as @code{PS1}, you can use a neutralizing value instead:
18543 @smallexample
18544 PS1='$ '
18545 @end smallexample
18547 Usually, shells that do not support @command{unset} need less effort to
18548 make the environment sane, so for example is not a problem if you cannot
18549 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18550 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18551 So, you should do something like
18553 @smallexample
18554 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18555 @end smallexample
18557 @noindent
18558 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18559 @ref{export, , Limitations of Builtins}, for
18560 the case of environment variables.
18562 @item @command{wait}
18563 @c -----------------
18564 @prindex @command{wait}
18565 The exit status of @command{wait} is not always reliable.
18566 @end table
18568 @node Limitations of Usual Tools
18569 @section Limitations of Usual Tools
18570 @cindex Limitations of usual tools
18572 The small set of tools you can expect to find on any machine can still
18573 include some limitations you should be aware of.
18575 @comment Between this list and the list of builtins above, we should
18576 @comment mention all the tools in GNU Coding Standards ``Utilities in
18577 @comment Makefiles''.
18579 @c This table includes things like `@command{expr} (|)', so we can't
18580 @c use @table @command.
18581 @table @asis
18582 @anchor{awk}
18583 @item @command{awk}
18584 @c ----------------
18585 @prindex @command{awk}
18586 Don't leave white space before the opening parenthesis in a user function call.
18587 Posix does not allow this and GNU Awk rejects it:
18589 @example
18590 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18591         BEGIN @{ die () @}'}
18592 gawk: cmd. line:2:         BEGIN @{ die () @}
18593 gawk: cmd. line:2:                      ^ parse error
18594 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18595         BEGIN @{ die() @}'}
18596 Aaaaarg!
18597 @end example
18599 Posix says that if a program contains only @samp{BEGIN} actions, and
18600 contains no instances of @code{getline}, then the program merely
18601 executes the actions without reading input.  However, traditional Awk
18602 implementations (such as Solaris 10 @command{awk}) read and discard
18603 input in this case.  Portable scripts can redirect input from
18604 @file{/dev/null} to work around the problem.  For example:
18606 @example
18607 awk 'BEGIN @{print "hello world"@}' </dev/null
18608 @end example
18610 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18611 @samp{$1}) retain their value from the last record read, if no
18612 intervening @samp{getline} occurred.  However, some implementations
18613 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18614 @samp{awk}) reset these variables.  A workaround is to use an
18615 intermediate variable prior to the @samp{END} block.  For example:
18617 @example
18618 $ @kbd{cat end.awk}
18619 @{ tmp = $1 @}
18620 END @{ print "a", $1, $NF, "b", tmp @}
18621 $ @kbd{echo 1 | awk -f end.awk}
18622 a   b 1
18623 $ @kbd{echo 1 | gawk -f end.awk}
18624 a 1 1 b 1
18625 @end example
18627 If you want your program to be deterministic, don't depend on @code{for}
18628 on arrays:
18630 @example
18631 $ @kbd{cat for.awk}
18632 END @{
18633   arr["foo"] = 1
18634   arr["bar"] = 1
18635   for (i in arr)
18636     print i
18638 $ @kbd{gawk -f for.awk </dev/null}
18641 $ @kbd{nawk -f for.awk </dev/null}
18644 @end example
18646 Some Awk implementations, such as HP-UX 11.0's native one,
18647 mishandle anchors:
18649 @example
18650 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18651 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18653 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18654 xfoo
18655 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18657 @end example
18659 @noindent
18660 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18661 or use a simple test to reject such implementations.
18663 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18664 after @code{%u}:
18666 @example
18667 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18668 0 0
18669 @end example
18671 AIX version 5.2 has an arbitrary limit of 399 on the
18672 length of regular expressions and literal strings in an Awk program.
18674 Traditional Awk implementations derived from Unix version 7, such as
18675 Solaris @command{/bin/awk}, have many limitations and do not
18676 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18677 Programs}) finds you an Awk that doesn't have these problems, but if
18678 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18679 address them.  For more detailed descriptions, see @ref{Language
18680 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18682 Traditional Awk does not support multidimensional arrays or user-defined
18683 functions.
18685 Traditional Awk does not support the @option{-v} option.  You can use
18686 assignments after the program instead, e.g., @code{$AWK '@{print v
18687 $1@}' v=x}; however, don't forget that such assignments are not
18688 evaluated until they are encountered (e.g., after any @code{BEGIN}
18689 action).
18691 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18693 Traditional Awk does not support the expressions
18694 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18695 or @code{@var{a}^=@var{b}}.
18697 Traditional Awk does not support the predefined @code{CONVFMT} or
18698 @code{ENVIRON} variables.
18700 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18701 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18702 @code{sqrt}, and @code{substr}.
18704 Traditional Awk @code{getline} is not at all compatible with Posix;
18705 avoid it.
18707 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18708 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18710 In code portable to both traditional and modern Awk, @code{FS} must be a
18711 string containing just one ordinary character, and similarly for the
18712 field-separator argument to @code{split}.
18714 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18715 implementations, like Tru64's, split the input even if you don't refer
18716 to any field in the script, to circumvent this problem, set @samp{FS}
18717 to an unusual character and use @code{split}.
18719 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18720 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18721 dumps core.
18723 The original version of Awk had a limit of at most 99 bytes per
18724 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18725 per run of non-special characters in a @code{printf} format, but these
18726 bugs have been fixed on all practical hosts that we know of.
18728 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18729 of at most 3070 bytes.
18731 @item @command{basename}
18732 @c ---------------------
18733 @prindex @command{basename}
18734 Not all hosts have a working @command{basename}.
18735 You can use @command{expr} instead.
18737 @c AS_BASENAME is to be replaced by a better API.
18738 @ignore
18739 Not all hosts have a working @command{basename}, and you should instead
18740 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18741 @command{expr} if you need to strip a suffix.  For example:
18743 @example
18744 a=`basename "$aname"`       # This is not portable.
18745 a=`AS_BASENAME(["$aname"])` # This is more portable.
18747 # This is not portable.
18748 c=`basename "$cname" .c`
18750 # This is more portable.
18751 c=`AS_BASENAME(["$cname"])`
18752 case $c in
18753 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18754 esac
18755 @end example
18756 @end ignore
18759 @item @command{cat}
18760 @c ----------------
18761 @prindex @command{cat}
18762 Don't rely on any option.
18765 @item @command{cc}
18766 @c ---------------
18767 @prindex @command{cc}
18768 The command @samp{cc -c foo.c} traditionally produces an object file
18769 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18770 with @option{-o} to specify a different object file name, but
18771 Posix does not require this combination and a few compilers
18772 lack support for it.  @xref{C Compiler}, for how GNU Make
18773 tests for this feature with @code{AC_PROG_CC_C_O}.
18775 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18776 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18778 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18779 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18780 nothing.
18782 The default executable, produced by @samp{cc foo.c}, can be
18784 @itemize
18785 @item @file{a.out} -- usual Posix convention.
18786 @item @file{b.out} -- i960 compilers (including @command{gcc}).
18787 @item @file{a.exe} -- DJGPP port of @command{gcc}.
18788 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
18789 @item @file{foo.exe} -- various MS-DOS compilers.
18790 @end itemize
18792 The C compiler's traditional name is @command{cc}, but other names like
18793 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
18794 name @command{c99}, but older Posix editions specified
18795 @command{c89}, future POSIX standards will likely specify
18796 @command{c11}, and anyway these standard names are rarely used in
18797 practice.  Typically the C compiler is invoked from makefiles that use
18798 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18799 compiler name.
18801 @item @command{chgrp}
18802 @itemx @command{chown}
18803 @c -------------------
18804 @prindex @command{chgrp}
18805 @prindex @command{chown}
18806 It is not portable to change a file's group to a group that the owner
18807 does not belong to.
18809 @item @command{chmod}
18810 @c ------------------
18811 @prindex @command{chmod}
18812 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18813 instead, for two reasons.  First, plain @option{-w} does not necessarily
18814 make the file unwritable, since it does not affect mode bits that
18815 correspond to bits in the file mode creation mask.  Second,
18816 Posix says that the @option{-w} might be interpreted as an
18817 implementation-specific option, not as a mode; Posix suggests
18818 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18819 @samp{--} does not work on some older hosts.
18822 @item @command{cmp}
18823 @c ----------------
18824 @prindex @command{cmp}
18825 @command{cmp} performs a raw data comparison of two files, while
18826 @command{diff} compares two text files.  Therefore, if you might compare
18827 DOS files, even if only checking whether two files are different, use
18828 @command{diff} to avoid spurious differences due to differences of
18829 newline encoding.
18832 @item @command{cp}
18833 @c ---------------
18834 @prindex @command{cp}
18835 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18836 obsolescent and its behavior on special files is implementation-defined.
18837 Use @option{-R} instead.  On GNU hosts the two options
18838 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18839 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18840 corrupt its own memory with some directory hierarchies and error out or
18841 dump core:
18843 @example
18844 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18845 @kbd{touch 12345678/12345678/x}
18846 @kbd{cp -R 12345678 t}
18847 cp: 0653-440 12345678/12345678/: name too long.
18848 @end example
18850 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18851 trailing slashes at the end of nonexistent destination directories.  To
18852 avoid this problem, omit the trailing slashes.  For example, use
18853 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18854 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18856 The @option{-f} option is portable nowadays.
18858 @cindex timestamp resolution
18859 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18860 -p} copied the timestamps exactly.  However, many modern file systems
18861 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18862 @samp{cp -p} implementations truncate timestamps when copying files,
18863 which can cause the destination file to appear to be older than the
18864 source.  The exact amount of truncation depends on the resolution of
18865 the system calls that @command{cp} uses.  Traditionally this was
18866 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18867 implementations such as GNU Core Utilities 5.0.91 (2003) use
18868 @code{utimes}, which has 1-microsecond resolution.  Modern
18869 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18870 the full nanosecond resolution, using the modern system calls
18871 @code{futimens} and @code{utimensat} when they are available.  As of
18872 2011, though, many platforms do not yet fully support these new system
18873 calls.
18875 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18876 ownerships.  But whether it actually does copy ownerships or not is a
18877 system dependent policy decision implemented by the kernel.  If the
18878 kernel allows it then it happens.  If the kernel does not allow it then
18879 it does not happen.  It is not something @command{cp} itself has control
18880 over.
18882 In Unix System V any user can chown files to any other user, and System
18883 V also has a non-sticky @file{/tmp}.  That probably derives from the
18884 heritage of System V in a business environment without hostile users.
18885 BSD changed this
18886 to be a more secure model where only root can @command{chown} files and
18887 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18888 of BSD in a campus environment.
18890 GNU/Linux and Solaris by default follow BSD, but
18891 can be configured to allow a System V style @command{chown}.  On the
18892 other hand, HP-UX follows System V, but can
18893 be configured to use the modern security model and disallow
18894 @command{chown}.  Since it is an administrator-configurable parameter
18895 you can't use the name of the kernel as an indicator of the behavior.
18899 @item @command{date}
18900 @c -----------------
18901 @prindex @command{date}
18902 Some versions of @command{date} do not recognize special @samp{%} directives,
18903 and unfortunately, instead of complaining, they just pass them through,
18904 and exit with success:
18906 @example
18907 $ @kbd{uname -a}
18908 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18909 $ @kbd{date "+%s"}
18911 @end example
18914 @item @command{diff}
18915 @c -----------------
18916 @prindex @command{diff}
18917 Option @option{-u} is nonportable.
18919 Some implementations, such as Tru64's, fail when comparing to
18920 @file{/dev/null}.  Use an empty file instead.
18923 @item @command{dirname}
18924 @c --------------------
18925 @prindex @command{dirname}
18926 Not all hosts have a working @command{dirname}, and you should instead
18927 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18929 @example
18930 dir=`dirname "$file"`       # This is not portable.
18931 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18932 @end example
18935 @item @command{egrep}
18936 @c ------------------
18937 @prindex @command{egrep}
18938 Posix 1003.1-2001 no longer requires @command{egrep},
18939 but many hosts do not yet support the Posix
18940 replacement @code{grep -E}.  Also, some traditional implementations do
18941 not work on long input lines.  To work around these problems, invoke
18942 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18944 Portable extended regular expressions should use @samp{\} only to escape
18945 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18946 is not portable, even though it typically matches @samp{@}}.
18948 The empty alternative is not portable.  Use @samp{?} instead.  For
18949 instance with Digital Unix v5.0:
18951 @example
18952 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18953 |foo
18954 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18955 bar|
18956 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18958 |bar
18959 @end example
18961 @command{$EGREP} also suffers the limitations of @command{grep}
18962 (@pxref{grep, , Limitations of Usual Tools}).
18964 @item @command{expr}
18965 @c -----------------
18966 @prindex @command{expr}
18967 Not all implementations obey the Posix rule that @samp{--} separates
18968 options from arguments; likewise, not all implementations provide the
18969 extension to Posix that the first argument can be treated as part of a
18970 valid expression rather than an invalid option if it begins with
18971 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18972 @samp{$var} might be a negative number, to keep @command{expr} from
18973 interpreting it as an option.
18975 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18976 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18977 misinterpreting @var{word}.
18979 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18981 @item @command{expr} (@samp{|})
18982 @prindex @command{expr} (@samp{|})
18983 You can use @samp{|}.  Although Posix does require that @samp{expr
18984 ''} return the empty string, it does not specify the result when you
18985 @samp{|} together the empty string (or zero) with the empty string.  For
18986 example:
18988 @example
18989 expr '' \| ''
18990 @end example
18992 Posix 1003.2-1992 returns the empty string
18993 for this case, but traditional Unix returns @samp{0} (Solaris is
18994 one such example).  In Posix 1003.1-2001, the specification was
18995 changed to match traditional Unix's behavior (which is
18996 bizarre, but it's too late to fix this).  Please note that the same
18997 problem does arise when the empty string results from a computation,
18998 as in:
19000 @example
19001 expr bar : foo \| foo : bar
19002 @end example
19004 @noindent
19005 Avoid this portability problem by avoiding the empty string.
19008 @item @command{expr} (@samp{:})
19009 @c ----------------------------
19010 @prindex @command{expr}
19011 Portable @command{expr} regular expressions should use @samp{\} to
19012 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
19013 For example, alternation, @samp{\|}, is common but Posix does not
19014 require its support, so it should be avoided in portable scripts.
19015 Similarly, @samp{\+} and @samp{\?} should be avoided.
19017 Portable @command{expr} regular expressions should not begin with
19018 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
19019 not needed anyway.
19021 On the other hand, the behavior of the @samp{$} anchor is not portable
19022 on multi-line strings.  Posix is ambiguous whether the anchor applies to
19023 each line, as was done in older versions of the GNU Core Utilities, or
19024 whether it applies only to the end of the overall string, as in
19025 Coreutils 6.0 and most other implementations.
19027 @example
19028 $ @kbd{baz='foo}
19029 > @kbd{bar'}
19030 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
19032 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
19034 @end example
19036 The Posix standard is ambiguous as to whether
19037 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
19038 In practice, it outputs the empty string on most platforms, but portable
19039 scripts should not assume this.  For instance, the QNX 4.25 native
19040 @command{expr} returns @samp{0}.
19042 One might think that a way to get a uniform behavior would be to use
19043 the empty string as a default value:
19045 @example
19046 expr a : '\(b\)' \| ''
19047 @end example
19049 @noindent
19050 Unfortunately this behaves exactly as the original expression; see the
19051 @command{expr} (@samp{|}) entry for more information.
19053 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
19054 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
19055 @command{expr} to fail if the matched substring is longer than 120
19056 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
19057 @command{expr} fails.  Nowadays this is of practical importance only for
19058 the rare installer who mistakenly puts @file{/usr/ucb} before
19059 @file{/usr/bin} in @env{PATH}.
19061 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19062 some cases.  For example, the command
19063 @example
19064 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19065 @end example
19067 @noindent
19068 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19069 This particular case can be worked around by substituting @samp{[^--]}
19070 for @samp{[^-]}.
19072 Don't leave, there is some more!
19074 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19075 the empty string, has a funny behavior in its exit status: it's always 1
19076 when parentheses are used!
19078 @example
19079 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19080 0: 1
19081 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19082 1: 0
19084 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19085 1: a
19086 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19087 1: 0
19088 @end example
19090 @noindent
19091 In practice this can be a big problem if you are ready to catch failures
19092 of @command{expr} programs with some other method (such as using
19093 @command{sed}), since you may get twice the result.  For instance
19095 @example
19096 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19097 @end example
19099 @noindent
19100 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
19101 simple workaround consists of testing @command{expr} and using a variable
19102 set to @command{expr} or to @command{false} according to the result.
19104 Tru64 @command{expr} incorrectly treats the result as a number, if it
19105 can be interpreted that way:
19107 @example
19108 $ @kbd{expr 00001 : '.*\(...\)'}
19110 @end example
19112 On HP-UX 11, @command{expr} only supports a single
19113 sub-expression.
19115 @example
19116 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19117 expr: More than one '\(' was used.
19118 @end example
19121 @item @command{fgrep}
19122 @c ------------------
19123 @prindex @command{fgrep}
19124 Posix 1003.1-2001 no longer requires @command{fgrep},
19125 but many hosts do not yet support the Posix
19126 replacement @code{grep -F}.  Also, some traditional implementations do
19127 not work on long input lines.  To work around these problems, invoke
19128 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19130 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
19133 @item @command{find}
19134 @c -----------------
19135 @prindex @command{find}
19136 The option @option{-maxdepth} seems to be GNU specific.
19137 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
19138 commands do not understand it.
19140 The replacement of @samp{@{@}} is guaranteed only if the argument is
19141 exactly @emph{@{@}}, not if it's only a part of an argument.  For
19142 instance on DU, and HP-UX 10.20 and HP-UX 11:
19144 @example
19145 $ @kbd{touch foo}
19146 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19147 @{@}-@{@}
19148 @end example
19150 @noindent
19151 while GNU @command{find} reports @samp{./foo-./foo}.
19154 @anchor{grep}
19155 @item @command{grep}
19156 @c -----------------
19157 @prindex @command{grep}
19158 Portable scripts can rely on the @command{grep} options @option{-c},
19159 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19160 options.  For example, don't use @option{-w}, as Posix does not require
19161 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19162 portable scripts should not combine @option{-c} with @option{-l},
19163 as Posix does not allow this.
19165 Some of the options required by Posix are not portable in practice.
19166 Don't use @samp{grep -q} to suppress output, because many @command{grep}
19167 implementations (e.g., Solaris) do not support @option{-q}.
19168 Don't use @samp{grep -s} to suppress output either, because Posix
19169 says @option{-s} does not suppress output, only some error messages;
19170 also, the @option{-s} option of traditional @command{grep} behaved
19171 like @option{-q} does in most modern implementations.  Instead,
19172 redirect the standard output and standard error (in case the file
19173 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19174 status of @code{grep} to determine whether it found a match.
19176 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19177 but works with @code{grep -c '^'}.  Other alternatives for counting
19178 lines are to use @code{sed -n '$='} or @code{wc -l}.
19180 Some traditional @command{grep} implementations do not work on long
19181 input lines.  On AIX the default @code{grep} silently truncates long
19182 lines on the input before matching.
19184 Also, many implementations do not support multiple regexps
19185 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19186 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19187 work around these problems, invoke @code{AC_PROG_GREP} and then use
19188 @code{$GREP}.
19190 Another possible workaround for the multiple @option{-e} problem is to
19191 separate the patterns by newlines, for example:
19193 @example
19194 grep 'foo
19195 bar' in.txt
19196 @end example
19198 @noindent
19199 except that this fails with traditional @command{grep}
19200 implementations and with OpenBSD 3.8 @command{grep}.
19202 Traditional @command{grep} implementations (e.g., Solaris) do not
19203 support the @option{-E} or @option{-F} options.  To work around these
19204 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19205 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19206 willing to require support for Posix @command{grep}, your script should
19207 not use both @option{-E} and @option{-F}, since Posix does not allow
19208 this combination.
19210 Portable @command{grep} regular expressions should use @samp{\} only to
19211 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19212 alternation, @samp{\|}, is common but Posix does not require its
19213 support in basic regular expressions, so it should be avoided in
19214 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19215 Similarly, the following escape sequences should also be avoided:
19216 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19217 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19219 Posix does not specify the behavior of @command{grep} on binary files.
19220 An example where this matters is using BSD @command{grep} to
19221 search text that includes embedded ANSI escape sequences for
19222 colored output to terminals (@samp{\033[m} is the sequence to restore
19223 normal output); the behavior depends on whether input is seekable:
19225 @example
19226 $ @kbd{printf 'esc\033[mape\n' > sample}
19227 $ @kbd{grep . sample}
19228 Binary file sample matches
19229 $ @kbd{cat sample | grep .}
19230 escape
19231 @end example
19234 @item @command{join}
19235 @c -----------------
19236 @prindex @command{join}
19237 Solaris 8 @command{join} has bugs when the second operand is standard
19238 input, and when standard input is a pipe.  For example, the following
19239 shell script causes Solaris 8 @command{join} to loop forever:
19241 @example
19242 cat >file <<'EOF'
19243 1 x
19244 2 y
19246 cat file | join file -
19247 @end example
19249 Use @samp{join - file} instead.
19251 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19252 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19253 the workaround is to use @command{join -a1 file1 file2} instead.
19255 @item @command{ln}
19256 @c ---------------
19257 @prindex @command{ln}
19258 The @option{-f} option is portable nowadays.
19260 @cindex Symbolic links
19261 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19262 a portable substitute.
19264 For versions of the DJGPP before 2.04,
19265 @command{ln} emulates symbolic links
19266 to executables by generating a stub that in turn calls the real
19267 program.  This feature also works with nonexistent files like in the
19268 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19269 which attempts to call @file{file.exe} if run.  But this feature only
19270 works for executables, so @samp{cp -p} is used instead for these
19271 systems.  DJGPP versions 2.04 and later have full support
19272 for symbolic links.
19275 @item @command{ls}
19276 @c ---------------
19277 @prindex @command{ls}
19278 @cindex Listing directories
19279 The portable options are @option{-acdilrtu}.  Current practice is for
19280 @option{-l} to output both owner and group, even though ancient versions
19281 of @command{ls} omitted the group.
19283 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19284 to standard output if @file{foo} did not exist.  Hence a shell command
19285 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19286 was equivalent to @samp{sources='*.c not found'} in the absence of
19287 @samp{.c} files.  This is no longer a practical problem, since current
19288 @command{ls} implementations send diagnostics to standard error.
19290 The behavior of @command{ls} on a directory that is being concurrently
19291 modified is not always predictable, because of a data race where cached
19292 information returned by @code{readdir} does not match the current
19293 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19294 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19295 once if other files were added or removed from the directory immediately
19296 prior to the @command{ls} call.  Since @command{ls} already sorts its
19297 output, the duplicate entries can be avoided by piping the results
19298 through @code{uniq}.
19300 @anchor{mkdir}
19301 @item @command{mkdir}
19302 @c ------------------
19303 @prindex @command{mkdir}
19304 @cindex Making directories
19305 No @command{mkdir} option is portable to older systems.  Instead of
19306 @samp{mkdir -p @var{file-name}}, you should use
19307 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19308 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19310 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19311 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19312 @command{mkdir} incorrectly attempts to change the permissions of
19313 @var{dir} even if it already exists.  HP-UX 11.23 and
19314 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19315 any newly-created parents of @var{dir}.
19317 Posix does not clearly specify whether @samp{mkdir -p foo}
19318 should succeed when @file{foo} is a symbolic link to an already-existing
19319 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19320 succeeds, but Solaris @command{mkdir} fails.
19322 Traditional @code{mkdir -p} implementations suffer from race conditions.
19323 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19324 at the same time, both processes might detect that @file{a} is missing,
19325 one might create @file{a}, then the other might try to create @file{a}
19326 and fail with a @code{File exists} diagnostic.  The GNU Core
19327 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19328 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19329 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19330 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19331 vulnerable as of Solaris 10, and other traditional Unix systems are
19332 probably vulnerable too.  This possible race is harmful in parallel
19333 builds when several Make rules call @code{mkdir -p} to
19334 construct directories.  You may use
19335 @code{install-sh -d} as a safe replacement, provided this script is
19336 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19337 OK, but copies from older versions are vulnerable.
19340 @item @command{mkfifo}
19341 @itemx @command{mknod}
19342 @c -------------------
19343 @prindex @command{mkfifo}
19344 @prindex @command{mknod}
19345 The GNU Coding Standards state that @command{mknod} is safe to use on
19346 platforms where it has been tested to exist; but it is generally portable
19347 only for creating named FIFOs, since device numbers are
19348 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19349 testsuites.  Posix states that behavior is unspecified when opening a
19350 named FIFO for both reading and writing; on at least Cygwin, this
19351 results in failure on any attempt to read or write to that file
19352 descriptor.
19354 @item @command{mktemp}
19355 @c -------------------
19356 @prindex @command{mktemp}
19357 @cindex Creating temporary files
19358 Shell scripts can use temporary files safely with @command{mktemp}, but
19359 it does not exist on all systems.  A portable way to create a safe
19360 temporary file name is to create a temporary directory with mode 700 and
19361 use a file inside this directory.  Both methods prevent attackers from
19362 gaining control, though @command{mktemp} is far less likely to fail
19363 gratuitously under attack.
19365 Here is sample code to create a new temporary directory @samp{$dir} safely:
19367 @example
19368 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19369 # Use mktemp if possible; otherwise fall back on mkdir,
19370 # with $RANDOM to make collisions less likely.
19371 : "$@{TMPDIR:=/tmp@}"
19373   dir=`
19374     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19375   ` &&
19376   test -d "$dir"
19377 @} || @{
19378   dir=$TMPDIR/foo$$-$RANDOM
19379 @c $$ restore font-lock
19380   (umask 077 && mkdir "$dir")
19381 @} || exit $?
19382 @end example
19385 @item @command{mv}
19386 @c ---------------
19387 @prindex @command{mv}
19388 @cindex Moving open files
19389 The only portable options are @option{-f} and @option{-i}.
19391 Moving individual files between file systems is portable (it was in Unix
19392 version 6),
19393 but it is not always atomic: when doing @samp{mv new existing}, there's
19394 a critical section where neither the old nor the new version of
19395 @file{existing} actually exists.
19397 On some systems moving files from @file{/tmp} can sometimes cause
19398 undesirable (but perfectly valid) warnings, even if you created these
19399 files.  This is because @file{/tmp} belongs to a group that ordinary
19400 users are not members of, and files created in @file{/tmp} inherit
19401 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19402 a diagnostic without failing:
19404 @smallexample
19405 $ @kbd{touch /tmp/foo}
19406 $ @kbd{mv /tmp/foo .}
19407 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19408 $ @kbd{echo $?}
19410 $ @kbd{ls foo}
19412 @end smallexample
19414 @noindent
19415 This annoying behavior conforms to Posix, unfortunately.
19417 Moving directories across mount points is not portable, use @command{cp}
19418 and @command{rm}.
19420 DOS variants cannot rename or remove open files, and do not
19421 support commands like @samp{mv foo bar >foo}, even though this is
19422 perfectly portable among Posix hosts.
19425 @item @command{od}
19426 @c ---------------
19427 @prindex @command{od}
19429 In Mac OS X 10.3, @command{od} does not support the
19430 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19431 @option{-t}, or the XSI option @option{-s}.  The only
19432 supported Posix option is @option{-v}, and the only supported
19433 XSI options are those in @option{-bcdox}.  The BSD
19434 @command{hexdump} program can be used instead.
19436 This problem no longer exists in Mac OS X 10.4.3.
19439 @item @command{rm}
19440 @c ---------------
19441 @prindex @command{rm}
19442 The @option{-f} and @option{-r} options are portable.
19444 It is not portable to invoke @command{rm} without options or operands.
19445 On the other hand, Posix now requires @command{rm -f} to silently
19446 succeed when there are no operands (useful for constructs like
19447 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19448 was empty).  But this was not always portable; at least NetBSD
19449 @command{rm} built before 2008 would fail with a diagnostic.
19451 A file might not be removed even if its parent directory is writable
19452 and searchable.  Many Posix hosts cannot remove a mount point, a named
19453 stream, a working directory, or a last link to a file that is being
19454 executed.
19456 DOS variants cannot rename or remove open files, and do not
19457 support commands like @samp{rm foo >foo}, even though this is
19458 perfectly portable among Posix hosts.
19460 @item @command{rmdir}
19461 @c ------------------
19462 @prindex @command{rmdir}
19463 Just as with @command{rm}, some platforms refuse to remove a working
19464 directory.
19466 @anchor{sed}
19467 @item @command{sed}
19468 @c ----------------
19469 @prindex @command{sed}
19470 Patterns should not include the separator (unless escaped), even as part
19471 of a character class.  In conformance with Posix, the Cray
19472 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19473 Even when escaped, patterns should not include separators that are also
19474 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19475 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19476 before evaluating the basic regular expression.
19478 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19479 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19480 them.
19482 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19484 Sed scripts should not use branch labels longer than 7 characters and
19485 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19486 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19487 48 labels, which cannot be circumvented by using more than one script
19488 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19489 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19490 about 6000 bytes for the internal representation of commands.
19492 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19493 NetBSD 1.4.2's, incorrectly try to interpret the second
19494 @samp{;} as a command:
19496 @example
19497 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19498 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19499 @end example
19501 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19502 and this limits the size of input lines, output lines, and internal
19503 buffers that can be processed portably.  Likewise,
19504 not all @command{sed} implementations can handle embedded @code{NUL} or
19505 a missing trailing newline.
19507 Remember that ranges within a bracket expression of a regular expression
19508 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19509 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19510 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19511 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19512 than to rely on @samp{[A-Z]}.
19514 Additionally, Posix states that regular expressions are only
19515 well-defined on characters.  Unfortunately, there exist platforms such
19516 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19517 even though that platform has a single-byte @samp{C} locale.  And Posix
19518 allows the existence of a multi-byte @samp{C} locale, although that does
19519 not yet appear to be a common implementation.  At any rate, it means
19520 that not all bytes will be matched by the regular expression @samp{.}:
19522 @example
19523 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19525 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19527 @end example
19529 Portable @command{sed} regular expressions should use @samp{\} only to escape
19530 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19531 alternation, @samp{\|}, is common but Posix does not require its
19532 support, so it should be avoided in portable scripts.  Solaris
19533 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19534 deletes only lines that contain the literal string @samp{a|b}.
19535 Similarly, @samp{\+} and @samp{\?} should be avoided.
19537 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19539 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19540 quite portable to current hosts, but was not supported by some ancient
19541 @command{sed} implementations like SVR3.
19543 Some @command{sed} implementations, e.g., Solaris, restrict the special
19544 role of the asterisk @samp{*} to one-character regular expressions and
19545 back-references, and the special role of interval expressions
19546 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19547 to one-character regular expressions.  This may lead to unexpected behavior:
19549 @example
19550 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19551 x2x4
19552 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19554 @end example
19556 The @option{-e} option is mostly portable.
19557 However, its argument
19558 cannot start with @samp{a}, @samp{c}, or @samp{i},
19559 as this runs afoul of a Tru64 5.1 bug.
19560 Also, its argument cannot be empty, as this fails on AIX 5.3.
19561 Some people prefer to use @samp{-e}:
19563 @example
19564 sed -e '@var{command-1}' \
19565     -e '@var{command-2}'
19566 @end example
19568 @noindent
19569 as opposed to the equivalent:
19571 @example
19572 sed '
19573   @var{command-1}
19574   @var{command-2}
19576 @end example
19578 @noindent
19579 The following usage is sometimes equivalent:
19581 @example
19582 sed '@var{command-1};@var{command-2}'
19583 @end example
19585 but Posix says that this use of a semicolon has undefined effect if
19586 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19587 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19588 should use semicolon only with simple scripts that do not use these
19589 verbs.
19591 Posix up to the 2008 revision requires the argument of the @option{-e}
19592 option to be a syntactically complete script.  GNU @command{sed} allows
19593 to pass multiple script fragments, each as argument of a separate
19594 @option{-e} option, that are then combined, with newlines between the
19595 fragments, and a future Posix revision may allow this as well.  This
19596 approach is not portable with script fragments ending in backslash; for
19597 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19598 don't allow splitting in this case:
19600 @example
19601 $ @kbd{echo a | sed -n -e 'i\}
19602 @kbd{0'}
19604 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19605 Unrecognized command: 0
19606 @end example
19608 @noindent
19609 In practice, however, this technique of joining fragments
19610 through @option{-e} works for multiple @command{sed} functions within
19611 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19613 @example
19614 @c The quote around the closing brace silences interactive zsh.
19615 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19617 @end example
19619 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19620 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19621 each command must be followed immediately by a newline, without any
19622 intervening blanks or semicolons.  The closing bracket must be alone on
19623 a line, other than white space preceding or following it.  However, a
19624 future version of Posix may standardize the use of addresses within brackets.
19626 Contrary to yet another urban legend, you may portably use @samp{&} in
19627 the replacement part of the @code{s} command to mean ``what was
19628 matched''.  All descendants of Unix version 7 @command{sed}
19629 (at least; we
19630 don't have first hand experience with older @command{sed} implementations) have
19631 supported it.
19633 Posix requires that you must not have any white space between
19634 @samp{!} and the following command.  It is OK to have blanks between
19635 the address and the @samp{!}.  For instance, on Solaris:
19637 @example
19638 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19639 @error{}Unrecognized command: /bar/ ! p
19640 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19641 @error{}Unrecognized command: /bar/! p
19642 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19644 @end example
19646 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19647 you use @samp{!}, it is best to put it on a command that is delimited by
19648 newlines rather than @samp{;}.
19650 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19651 @samp{w} commands be followed by exactly one space before their argument.
19652 On the other hand, no white space is allowed between @samp{:} and the
19653 subsequent label name.
19655 If a sed script is specified on the command line and ends in an
19656 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19657 should be followed by a newline.  Otherwise some @command{sed}
19658 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19659 inserted text.
19661 Many @command{sed} implementations (e.g., MacOS X 10.4,
19662 OpenBSD 3.9, Solaris 10
19663 @command{/usr/ucb/sed}) strip leading white space from the text of
19664 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19665 work around this incompatibility with Posix:
19667 @example
19668 $ @kbd{echo flushleft | sed 'a\}
19669 > @kbd{   indented}
19670 > @kbd{'}
19671 flushleft
19672 indented
19673 $ @kbd{echo foo | sed 'a\}
19674 > @kbd{\   indented}
19675 > @kbd{'}
19676 flushleft
19677    indented
19678 @end example
19680 Posix requires that with an empty regular expression, the last non-empty
19681 regular expression from either an address specification or substitution
19682 command is applied.  However, busybox 1.6.1 complains when using a
19683 substitution command with a replacement containing a back-reference to
19684 an empty regular expression; the workaround is repeating the regular
19685 expression.
19687 @example
19688 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19689 sed: No previous regexp.
19690 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19692 @end example
19694 Portable scripts should be aware of the inconsistencies and options for
19695 handling word boundaries, as these are not specified by POSIX.
19697 @example
19698                 \<      \b      [[:<:]]
19699 Solaris 10      yes     no      no
19700 Solaris XPG4    yes     no      error
19701 NetBSD 5.1      no      no      yes
19702 FreeBSD 9.1     no      no      yes
19703 GNU             yes     yes     error
19704 busybox         yes     yes     error
19705 @end example
19707 @item @command{sed} (@samp{t})
19708 @c ---------------------------
19709 @prindex @command{sed} (@samp{t})
19710 Some old systems have @command{sed} that ``forget'' to reset their
19711 @samp{t} flag when starting a new cycle.  For instance on MIPS
19712 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19713 script (the line numbers are not actual part of the texts):
19715 @example
19716 s/keep me/kept/g  # a
19717 t end             # b
19718 s/.*/deleted/g    # c
19719 :end              # d
19720 @end example
19722 @noindent
19725 @example
19726 delete me         # 1
19727 delete me         # 2
19728 keep me           # 3
19729 delete me         # 4
19730 @end example
19732 @noindent
19733 you get
19735 @example
19736 deleted
19737 delete me
19738 kept
19739 deleted
19740 @end example
19742 @noindent
19743 instead of
19745 @example
19746 deleted
19747 deleted
19748 kept
19749 deleted
19750 @end example
19752 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19753 flag, and the output is produced.  When processing
19754 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19755 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19756 flag when a substitution fails.  Command (b) sees that the flag is set,
19757 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19758 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19759 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19760 Finally, since the flag is clear, line 4 is processed properly.
19762 There are two things one should remember about @samp{t} in @command{sed}.
19763 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19764 succeeded, not only the immediately preceding substitution.  Therefore,
19765 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19766 line, to reset the @samp{t} flag where needed.
19768 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19769 cycle.
19771 One portable implementation of the script above is:
19773 @example
19774 t clear
19775 :clear
19776 s/keep me/kept/g
19777 t end
19778 s/.*/deleted/g
19779 :end
19780 @end example
19782 @item @command{sleep}
19783 @c ------------------
19784 @prindex @command{sleep}
19785 Using @command{sleep} is generally portable.  However, remember that
19786 adding a @command{sleep} to work around timestamp issues, with a minimum
19787 granularity of one second, doesn't scale well for parallel builds on
19788 modern machines with sub-second process completion.
19790 @item @command{sort}
19791 @c -----------------
19792 @prindex @command{sort}
19793 Remember that sort order is influenced by the current locale.  Inside
19794 @file{configure}, the C locale is in effect, but in Makefile snippets,
19795 you may need to specify @code{LC_ALL=C sort}.
19797 @item @command{tar}
19798 @c ----------------
19799 @prindex @command{tar}
19800 There are multiple file formats for @command{tar}; if you use Automake,
19801 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19802 level of portability to use.
19804 @anchor{touch}
19805 @item @command{touch}
19806 @c ------------------
19807 @prindex @command{touch}
19808 @cindex timestamp resolution
19809 If you specify the desired timestamp (e.g., with the @option{-r}
19810 option), older @command{touch} implementations use the @code{utime} or
19811 @code{utimes} system call, which can result in the same kind of
19812 timestamp truncation problems that @samp{cp -p} has.
19814 On ancient BSD systems, @command{touch} or any command that
19815 results in an empty file does not update the timestamps, so use a
19816 command like @command{echo} as a workaround.
19817 Also,
19818 GNU @command{touch} 3.16r (and presumably all before that)
19819 fails to work on SunOS 4.1.3 when the empty file is on an
19820 NFS-mounted 4.2 volume.
19821 However, these problems are no longer of practical concern.
19823 @item @command{tr}
19824 @c ---------------
19825 @prindex @command{tr}
19826 @cindex carriage return, deleting
19827 @cindex newline, deleting
19828 @cindex deleting carriage return
19829 Not all versions of @command{tr} handle all backslash character escapes.
19830 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19831 Solaris contains more modern @command{tr} in other locations.
19832 Using octal escapes is more portable for carriage returns, since
19833 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19834 literal carriage returns in scripts causes a number of other problems.
19835 But for other characters, like newline, using octal escapes ties the
19836 operation to ASCII, so it is better to use literal characters.
19838 @example
19839 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19841 light
19842 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19843 moonlight
19844 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19845 moonlight
19846 $ @kbd{nl='}
19847 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19848 moonlight
19849 @end example
19851 Not all versions of @command{tr} recognize direct ranges of characters: at
19852 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19853 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19854 transliterate to themselves).
19856 @example
19857 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19858 HAZy FAntAZy
19859 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19860 HAZY FANTAZY
19861 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19862 HAZY FANTAZY
19863 @end example
19865 When providing two arguments, be sure the second string is at least as
19866 long as the first.
19868 @example
19869 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19871 $ @kbd{echo abc | coreutils/tr bc d}
19873 @end example
19875 Posix requires @command{tr} to operate on binary files.  But at least
19876 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19877 @code{NUL} in the input prior to doing any translation.  When using
19878 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19879 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19880 @command{/usr/xpg6/bin/tr} if that is available.
19882 @example
19883 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19884  61 62
19885 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19886  61 62
19887 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19888  61 00 62
19889 @end example
19891 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19892 octal escape for @code{NUL}.
19894 @example
19895 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19896  61 62 63
19897 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19898  61 00 64
19899 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19900  61 00 64
19901 @end example
19903 @end table
19906 @node Portable Make
19907 @chapter Portable Make Programming
19908 @prindex @command{make}
19909 @cindex Limitations of @command{make}
19911 Writing portable makefiles is an art.  Since a makefile's commands are
19912 executed by the shell, you must consider the shell portability issues
19913 already mentioned.  However, other issues are specific to @command{make}
19914 itself.
19916 @menu
19917 * $< in Ordinary Make Rules::   $< in ordinary rules
19918 * Failure in Make Rules::       Failing portably in rules
19919 * Special Chars in Names::      Special Characters in Macro Names
19920 * Backslash-Newline-Empty::     Empty lines after backslash-newline
19921 * Backslash-Newline Comments::  Spanning comments across line boundaries
19922 * Long Lines in Makefiles::     Line length limitations
19923 * Macros and Submakes::         @code{make macro=value} and submakes
19924 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19925 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19926 * Parallel Make::               Parallel @command{make} quirks
19927 * Comments in Make Rules::      Other problems with Make comments
19928 * Newlines in Make Rules::      Using literal newlines in rules
19929 * Comments in Make Macros::     Other problems with Make comments in macros
19930 * Trailing whitespace in Make Macros::  Macro substitution problems
19931 * Command-line Macros and whitespace::  Whitespace trimming of values
19932 * obj/ and Make::               Don't name a subdirectory @file{obj}
19933 * make -k Status::              Exit status of @samp{make -k}
19934 * VPATH and Make::              @code{VPATH} woes
19935 * Single Suffix Rules::         Single suffix rules and separated dependencies
19936 * Timestamps and Make::         Subsecond timestamp resolution
19937 @end menu
19939 @node $< in Ordinary Make Rules
19940 @section @code{$<} in Ordinary Make Rules
19942 Posix says that the @samp{$<} construct in makefiles can be
19943 used only in inference rules and in the @samp{.DEFAULT} rule; its
19944 meaning in ordinary rules is unspecified.  Solaris @command{make}
19945 for instance replaces it with the empty string.  OpenBSD (3.0 and
19946 later) @command{make} diagnoses these uses and errors out.
19948 @node Failure in Make Rules
19949 @section Failure in Make Rules
19951 Posix 2008 requires that @command{make} must invoke each command with
19952 the equivalent of a @samp{sh -e -c} subshell, which causes the
19953 subshell to exit immediately if a subsidiary simple-command fails,
19954 although not all @command{make} implementations have historically
19955 followed this rule.  For
19956 example, the command @samp{touch T; rm -f U} may attempt to
19957 remove @file{U} even if the @command{touch} fails, although this is not
19958 permitted with Posix make.  One way to work around failures in simple
19959 commands is to reword them so that they always succeed, e.g., @samp{touch
19960 T || :; rm -f U}.
19961 However, even this approach can run into common bugs in BSD
19962 implementations of the @option{-e} option of @command{sh} and
19963 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19964 are worried
19965 about porting to buggy BSD shells it may be simpler to migrate
19966 complicated @command{make} actions into separate scripts.
19968 @node Special Chars in Names
19969 @section Special Characters in Make Macro Names
19971 Posix limits macro names to nonempty strings containing only
19972 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19973 @command{make} implementations allow a wider variety of characters, but
19974 portable makefiles should avoid them.  It is portable to start a name
19975 with a special character, e.g., @samp{$(.FOO)}.
19977 Some ancient @command{make} implementations don't support leading
19978 underscores in macro names.  An example is NEWS-OS 4.2R.
19980 @example
19981 $ @kbd{cat Makefile}
19982 _am_include = #
19983 _am_quote =
19984 all:; @@echo this is test
19985 $ @kbd{make}
19986 Make: Must be a separator on rules line 2.  Stop.
19987 $ @kbd{cat Makefile2}
19988 am_include = #
19989 am_quote =
19990 all:; @@echo this is test
19991 $ @kbd{make -f Makefile2}
19992 this is test
19993 @end example
19995 @noindent
19996 However, this problem is no longer of practical concern.
19998 @node Backslash-Newline-Empty
19999 @section Backslash-Newline Before Empty Lines
20001 A bug in Bash 2.03 can cause problems if a Make rule contains a
20002 backslash-newline followed by line that expands to nothing.
20003 For example, on Solaris 8:
20005 @example
20006 SHELL = /bin/bash
20007 EMPTY =
20008 foo:
20009         touch foo \
20010         $(EMPTY)
20011 @end example
20013 @noindent
20014 executes
20016 @example
20017 /bin/bash -c 'touch foo \
20019 @end example
20021 @noindent
20022 which fails with a syntax error, due to the Bash bug.  To avoid this
20023 problem, avoid nullable macros in the last line of a multiline command.
20025 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
20026 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
20027 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
20028 On some versions of HP-UX, @command{make} reads multiple newlines
20029 following a backslash, continuing to the next non-empty line.  For
20030 example,
20032 @example
20033 FOO = one \
20035 BAR = two
20037 test:
20038         : FOO is "$(FOO)"
20039         : BAR is "$(BAR)"
20040 @end example
20042 @noindent
20043 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
20044 sensibly let a backslash continue only to the immediately following
20045 line.
20047 @node Backslash-Newline Comments
20048 @section Backslash-Newline in Make Comments
20050 According to Posix, Make comments start with @code{#}
20051 and continue until an unescaped newline is reached.
20053 @example
20054 $ @kbd{cat Makefile}
20055 # A = foo \
20056       bar \
20057       baz
20059 all:
20060         @@echo ok
20061 $ @kbd{make}   # GNU make
20063 @end example
20065 @noindent
20066 However this is not always the case.  Some implementations
20067 discard everything from @code{#} through the end of the line, ignoring any
20068 trailing backslash.
20070 @example
20071 $ @kbd{pmake}  # BSD make
20072 "Makefile", line 3: Need an operator
20073 Fatal errors encountered -- cannot continue
20074 @end example
20076 @noindent
20077 Therefore, if you want to comment out a multi-line definition, prefix each
20078 line with @code{#}, not only the first.
20080 @example
20081 # A = foo \
20082 #     bar \
20083 #     baz
20084 @end example
20086 @node Long Lines in Makefiles
20087 @section Long Lines in Makefiles
20089 Tru64 5.1's @command{make} has been reported to crash when given a
20090 makefile with lines longer than around 20 kB.  Earlier versions are
20091 reported to exit with @code{Line too long} diagnostics.
20093 @node Macros and Submakes
20094 @section @code{make macro=value} and Submakes
20096 A command-line variable definition such as @code{foo=bar} overrides any
20097 definition of @code{foo} in a makefile.  Some @command{make}
20098 implementations (such as GNU @command{make}) propagate this
20099 override to subsidiary invocations of @command{make}.  Some other
20100 implementations do not pass the substitution along to submakes.
20102 @example
20103 $ @kbd{cat Makefile}
20104 foo = foo
20105 one:
20106         @@echo $(foo)
20107         $(MAKE) two
20108 two:
20109         @@echo $(foo)
20110 $ @kbd{make foo=bar}            # GNU make 3.79.1
20112 make two
20113 make[1]: Entering directory `/home/adl'
20115 make[1]: Leaving directory `/home/adl'
20116 $ @kbd{pmake foo=bar}           # BSD make
20118 pmake two
20120 @end example
20122 You have a few possibilities if you do want the @code{foo=bar} override
20123 to propagate to submakes.  One is to use the @option{-e}
20124 option, which causes all environment variables to have precedence over
20125 the makefile macro definitions, and declare foo as an environment
20126 variable:
20128 @example
20129 $ @kbd{env foo=bar make -e}
20130 @end example
20132 The @option{-e} option is propagated to submakes automatically,
20133 and since the environment is inherited between @command{make}
20134 invocations, the @code{foo} macro is overridden in
20135 submakes as expected.
20137 This syntax (@code{foo=bar make -e}) is portable only when used
20138 outside of a makefile, for instance from a script or from the
20139 command line.  When run inside a @command{make} rule, GNU
20140 @command{make} 3.80 and prior versions forget to propagate the
20141 @option{-e} option to submakes.
20143 Moreover, using @option{-e} could have unexpected side effects if your
20144 environment contains some other macros usually defined by the
20145 makefile.  (See also the note about @code{make -e} and @code{SHELL}
20146 below.)
20148 If you can foresee all macros that a user might want to override, then
20149 you can propagate them to submakes manually, from your makefile:
20151 @example
20152 foo = foo
20153 one:
20154         @@echo $(foo)
20155         $(MAKE) foo=$(foo) two
20156 two:
20157         @@echo $(foo)
20158 @end example
20160 Another way to propagate a variable to submakes in a portable way is to
20161 expand an extra variable in every invocation of @samp{$(MAKE)} within
20162 your makefile:
20164 @example
20165 foo = foo
20166 one:
20167         @@echo $(foo)
20168         $(MAKE) $(SUBMAKEFLAGS) two
20169 two:
20170         @@echo $(foo)
20171 @end example
20173 Users must be aware that this technique is in use to take advantage of
20174 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20175 allows any macro to be overridden.  Makefiles generated by
20176 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20177 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20178 automake, GNU Automake}).
20180 @node The Make Macro MAKEFLAGS
20181 @section The Make Macro MAKEFLAGS
20182 @cindex @code{MAKEFLAGS} and @command{make}
20183 @cindex @command{make} and @code{MAKEFLAGS}
20185 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20186 current and recursive invocations of make, but allows implementations
20187 several formats for the variable.  It is tricky to parse
20188 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20189 or @option{-k} for continued execution are in effect.  For example, you
20190 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20191 contains single-letter options, since in the Cygwin version of
20192 GNU @command{make} it is either @option{--unix} or
20193 @option{--win32} with the second word containing single-letter options.
20195 @example
20196 $ @kbd{cat Makefile}
20197 all:
20198         @@echo MAKEFLAGS = $(MAKEFLAGS)
20199 $ @kbd{make}
20200 MAKEFLAGS = --unix
20201 $ @kbd{make -k}
20202 MAKEFLAGS = --unix -k
20203 @end example
20205 @node The Make Macro SHELL
20206 @section The Make Macro @code{SHELL}
20207 @cindex @code{SHELL} and @command{make}
20208 @cindex @command{make} and @code{SHELL}
20210 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20211 macro to spawn shell processes and execute Make rules.  This
20212 is a builtin macro supplied by @command{make}, but it can be modified
20213 by a makefile or by a command-line argument.
20215 Not all @command{make} implementations define this @code{SHELL} macro.
20216 Tru64
20217 @command{make} is an example; this implementation always uses
20218 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20219 your makefiles.  If you use Autoconf, do
20221 @example
20222 SHELL = @@SHELL@@
20223 @end example
20225 @noindent
20226 If you use Automake, this is done for you.
20228 Do not force @code{SHELL = /bin/sh} because that is not correct
20229 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20230 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20231 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20232 GNU @command{make} port sees such a setting it enters a
20233 special emulation mode where features like pipes and redirections are
20234 emulated on top of DOS's @command{command.com}.  Unfortunately this
20235 emulation is incomplete; for instance it does not handle command
20236 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20237 benefit from the same improved shell, such as @command{bash} or
20238 @command{ksh}, that was discovered during @command{configure}, so that
20239 you aren't fighting two different sets of shell bugs between the two
20240 contexts.
20242 Posix-compliant @command{make} should never acquire the value of
20243 $(SHELL) from the environment, even when @code{make -e} is used
20244 (otherwise, think about what would happen to your rules if
20245 @code{SHELL=/bin/tcsh}).
20247 However not all @command{make} implementations have this exception.
20248 For instance it's not surprising that Tru64 @command{make} doesn't
20249 protect @code{SHELL}, since it doesn't use it.
20251 @example
20252 $ @kbd{cat Makefile}
20253 SHELL = /bin/sh
20254 FOO = foo
20255 all:
20256         @@echo $(SHELL)
20257         @@echo $(FOO)
20258 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20259 /bin/tcsh
20261 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20262 /bin/sh
20264 @end example
20266 Conversely, @command{make} is not supposed to export any changes to the
20267 macro @code{SHELL} to child processes.  Again, many implementations
20268 break this rule:
20270 @example
20271 $ @kbd{cat Makefile}
20272 all:
20273         @@echo $(SHELL)
20274         @@printenv SHELL
20275 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20276 /bin/ksh
20277 /bin/ksh
20278 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20279 /bin/ksh
20281 @end example
20283 @node Parallel Make
20284 @section Parallel Make
20285 @cindex Parallel @command{make}
20287 Support for parallel execution in @command{make} implementation varies.
20288 Generally, using GNU make is your best bet.
20290 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20291 reuse the same shell for multiple commands within one recipe.  This can
20292 have various unexpected consequences.  For example, changes of directories
20293 or variables persist between recipes, so that:
20295 @example
20296 all:
20297         @@var=value; cd /; pwd; echo $$var; echo $$$$
20298         @@pwd; echo $$var; echo $$$$
20299 @end example
20301 @noindent
20302 may output the following with @code{make -j1}, at least on NetBSD up to
20303 5.1 and FreeBSD up to 8.2:
20305 @example
20307 value
20308 32235
20310 value
20311 32235
20312 @end example
20314 @noindent
20315 while without @option{-j1}, or with @option{-B}, the output looks less
20316 surprising:
20318 @example
20320 value
20321 32238
20322 /tmp
20324 32239
20325 @end example
20327 @noindent
20328 Another consequence is that, if one command in a recipe uses @code{exit 0}
20329 to indicate a successful exit, the shell will be gone and the remaining
20330 commands of this recipe will not be executed.
20332 The BSD @command{make} implementations, when run in parallel mode,
20333 will also pass the @command{Makefile} recipes to the shell through
20334 its standard input, thus making it unusable from the recipes:
20336 @example
20337 $ @kbd{cat Makefile}
20338 read:
20339         @@read line; echo LINE: $$line
20340 @c $$ @c restore font-lock
20341 $ @kbd{echo foo | make read}
20342 LINE: foo
20343 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20344 LINE:
20345 @end example
20347 @noindent
20348 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20349 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20350 modifiers'' by dynamically modifying the active shell flags.  This
20351 behavior has the effects of potentially clobbering the exit status
20352 of recipes silenced with the @code{@@} modifier if they also unset
20353 the @option{errexit} shell flag, and of mangling the output in
20354 unexpected ways:
20356 @example
20357 $ @kbd{cat Makefile}
20359         @@echo $$-; set +e; false
20361         -echo $$-; false; echo set -
20362 $ @kbd{make a; echo status: $?}
20363 ehBc
20364 *** Error code 1
20365 status: 1
20366 $ @kbd{make -j1 a; echo status: $?}
20368 status: 0
20369 $ @kbd{make b}
20370 echo $-; echo set -
20372 set -
20373 $ @kbd{make -j1 b}
20374 echo $-; echo hvB
20375 @end example
20377 @noindent
20378 You can avoid all these issues by using the @option{-B} option to enable
20379 compatibility semantics.  However, that will effectively also disable
20380 all parallelism as that will cause prerequisites to be updated in the
20381 order they are listed in a rule.
20383 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20384 @command{make}, and Solaris @command{dmake}), when invoked with a
20385 @option{-j@var{N}} option, connect the standard output and standard
20386 error of all their child processes to pipes or temporary regular
20387 files.  This can lead to subtly different semantics in the behavior
20388 of the spawned processes.  For example, even if the @command{make}
20389 standard output is connected to a tty, the recipe command will not be:
20391 @example
20392 $ @kbd{cat Makefile}
20393 all:
20394         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20395 $ @kbd{make -j 2} # FreeBSD 8.2 make
20396 Is not a tty
20397 $ @kbd{make -j 2} # NetBSD 5.1 make
20398 --- all ---
20399 Is not a tty
20400 $ @kbd{dmake -j 2} # Solaris 10 dmake
20401 @var{hostname} --> 1 job
20402 @var{hostname} --> Job output
20403 Is not a tty
20404 @end example
20406 @noindent
20407 On the other hand:
20409 @example
20410 $ @kbd{make -j 2} # GNU make, Heirloom make
20411 Is a tty
20412 @end example
20414 @noindent
20415 The above examples also show additional status output produced in parallel
20416 mode for targets being updated by Solaris @command{dmake} and NetBSD
20417 @command{make} (but @emph{not} by FreeBSD @command{make}).
20419 Furthermore, parallel runs of those @command{make} implementations will
20420 route standard error from commands that they spawn into their own
20421 standard output, and may remove leading whitespace from output lines.
20424 @node Comments in Make Rules
20425 @section Comments in Make Rules
20426 @cindex Comments in @file{Makefile} rules
20427 @cindex @file{Makefile} rules and comments
20429 Never put comments in a rule.
20431 Some @command{make} treat anything starting with a tab as a command for
20432 the current rule, even if the tab is immediately followed by a @code{#}.
20433 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20434 makefile runs @code{# foo} through the shell.
20436 @example
20437 all:
20438         # foo
20439 @end example
20441 As a workaround, you can use the @command{:} no-op command with a string
20442 argument that gets ignored:
20444 @example
20445 all:
20446         : "foo"
20447 @end example
20449 Conversely, if you want to use the @samp{#} character in some command,
20450 you can only do so by expanding it inside a rule (@pxref{Comments in
20451 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20452 @command{config.status} as @samp{#}, then the following substitutes
20453 @samp{@@COMMENT_CHAR@@} in a generated header:
20455 @example
20456 foo.h: foo.h.in
20457         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20458             $(srcdir)/foo.h.in > $@@
20459 @end example
20461 The funny shell quoting avoids a substitution at @command{config.status}
20462 run time of the left-hand side of the @command{sed} @samp{s} command.
20464 @node Newlines in Make Rules
20465 @section Newlines in Make Rules
20466 @cindex Newlines in @file{Makefile} rules
20467 @cindex @file{Makefile} rules and newlines
20469 In shell scripts, newlines can be used inside string literals.  But in
20470 the shell statements of @file{Makefile} rules, this is not possible:
20471 A newline not preceded by a backslash is a separator between shell
20472 statements.  Whereas a newline that is preceded by a backslash becomes
20473 part of the shell statement according to POSIX, but gets replaced,
20474 together with the backslash that precedes it, by a space in GNU
20475 @command{make} 3.80 and older.  So, how can a newline be used in a string
20476 literal?
20478 The trick is to set up a shell variable that contains a newline:
20480 @example
20481 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20482 @end example
20484 For example, in order to create a multiline @samp{sed} expression that
20485 inserts a blank line after every line of a file, this code can be used:
20487 @example
20488 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20489 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20490 @end example
20492 @node Comments in Make Macros
20493 @section Comments in Make Macros
20494 @cindex Comments in @file{Makefile} macros
20495 @cindex @file{Makefile} macros and comments
20497 Avoid putting comments in macro values as far as possible.  Posix
20498 specifies that the text starting from the @samp{#} sign until the end of
20499 the line is to be ignored, which has the unfortunate effect of
20500 disallowing them even within quotes.  Thus, the following might lead to
20501 a syntax error at compile time:
20503 @example
20504 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20505 @end example
20507 @noindent
20508 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20510 Most @command{make} implementations disregard this and treat single and
20511 double quotes specially here.  Also, GNU @command{make} lets you put
20512 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20513 @samp{\#}.  However, neither of these usages are portable.
20514 @xref{Comments in Make Rules}, for a portable alternative.
20516 Even without quoting involved, comments can have surprising effects,
20517 because the whitespace before them is part of the variable value:
20519 @example
20520 foo = bar # trailing comment
20521 print: ; @@echo "$(foo)."
20522 @end example
20524 @noindent
20525 prints @samp{bar .}, which is usually not intended, and can expose
20526 @command{make} bugs as described below.
20528 @node Trailing whitespace in Make Macros
20529 @section Trailing whitespace in Make Macros
20530 @cindex whitespace in @file{Makefile} macros
20531 @cindex @file{Makefile} macros and whitespace
20533 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20534 substitutions and appends another spurious suffix:
20536 @example
20537 empty =
20538 foo = bar $(empty)
20539 print: ; @@echo $(foo:=.test)
20540 @end example
20542 @noindent
20543 prints @samp{bar.test .test}.
20545 BSD and Solaris @command{make} implementations do not honor trailing
20546 whitespace in macro definitions as Posix requires:
20548 @example
20549 foo = bar # Note the space after "bar".
20550 print: ; @@echo $(foo)t
20551 @end example
20553 @noindent
20554 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20555 can use a helper macro as in the previous example.
20558 @node Command-line Macros and whitespace
20559 @section Command-line Macros and whitespace
20560 @cindex whitespace in command-line macros
20561 @cindex command-line, macros set on
20562 @cindex environment, macros set from
20564 Some @command{make} implementations may strip trailing whitespace off
20565 of macros set on the command line in addition to leading whitespace.
20566 Further, some may strip leading whitespace off of macros set from
20567 environment variables:
20569 @example
20570 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20571   foo=' f f ' make -f - bar=' b b '}
20572 x f f xb b x  # AIX, BSD, GNU make
20573 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20574 x f f xb bx   # Solaris make
20575 @end example
20578 @node obj/ and Make
20579 @section The @file{obj/} Subdirectory and Make
20580 @cindex @file{obj/}, subdirectory
20581 @cindex BSD @command{make} and @file{obj/}
20583 Never name one of your subdirectories @file{obj/} if you don't like
20584 surprises.
20586 If an @file{obj/} directory exists, BSD @command{make} enters it
20587 before reading the makefile.  Hence the makefile in the
20588 current directory is not read.
20590 @example
20591 $ @kbd{cat Makefile}
20592 all:
20593         echo Hello
20594 $ @kbd{cat obj/Makefile}
20595 all:
20596         echo World
20597 $ @kbd{make}      # GNU make
20598 echo Hello
20599 Hello
20600 $ @kbd{pmake}     # BSD make
20601 echo World
20602 World
20603 @end example
20605 @node make -k Status
20606 @section Exit Status of @code{make -k}
20607 @cindex @code{make -k}
20609 Do not rely on the exit status of @code{make -k}.  Some implementations
20610 reflect whether they encountered an error in their exit status; other
20611 implementations always succeed.
20613 @example
20614 $ @kbd{cat Makefile}
20615 all:
20616         false
20617 $ @kbd{make -k; echo exit status: $?}    # GNU make
20618 false
20619 make: *** [all] Error 1
20620 exit status: 2
20621 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20622 false
20623 *** Error code 1 (continuing)
20624 exit status: 0
20625 @end example
20627 @node VPATH and Make
20628 @section @code{VPATH} and Make
20629 @cindex @code{VPATH}
20631 Posix does not specify the semantics of @code{VPATH}.  Typically,
20632 @command{make} supports @code{VPATH}, but its implementation is not
20633 consistent.
20635 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20636 portable to recent-enough popular implementations of @command{make}, but
20637 to keep the resulting makefiles portable, a package's makefile
20638 prototypes must take the following issues into account.  These issues
20639 are complicated and are often poorly understood, and installers who use
20640 @code{VPATH} should expect to find many bugs in this area.  If you use
20641 @code{VPATH}, the simplest way to avoid these portability bugs is to
20642 stick with GNU @command{make}, since it is the most
20643 commonly-used @command{make} among Autoconf users.
20645 Here are some known issues with some @code{VPATH}
20646 implementations.
20648 @menu
20649 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20650 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20651 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20652 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20653 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20654 * Make Target Lookup::          More details about @code{VPATH} lookup
20655 @end menu
20657 @node Variables listed in VPATH
20658 @subsection Variables listed in @code{VPATH}
20659 @cindex @code{VPATH} and variables
20660 @cindex variables and @code{VPATH}
20662 Do not set @code{VPATH} to the value of another variable, for example
20663 @samp{VPATH = $(srcdir)}, because some ancient versions of
20664 @command{make} do not do variable substitutions on the value of
20665 @code{VPATH}.  For example, use this
20667 @example
20668 srcdir = @@srcdir@@
20669 VPATH = @@srcdir@@
20670 @end example
20672 @noindent
20673 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20674 Automake, there is no need to set this yourself.
20676 @node VPATH and Double-colon
20677 @subsection @code{VPATH} and Double-colon Rules
20678 @cindex @code{VPATH} and double-colon rules
20679 @cindex double-colon rules and @code{VPATH}
20681 With ancient versions of Sun @command{make},
20682 any assignment to @code{VPATH} causes @command{make} to execute only
20683 the first set of double-colon rules.
20684 However, this problem is no longer of practical concern.
20686 @node $< in Explicit Rules
20687 @subsection @code{$<} Not Supported in Explicit Rules
20688 @cindex explicit rules, @code{$<}, and @code{VPATH}
20689 @cindex @code{$<}, explicit rules, and @code{VPATH}
20690 @cindex @code{VPATH}, explicit rules, and @code{$<}
20692 Using @code{$<} in explicit rules is not portable.
20693 The prerequisite file must be named explicitly in the rule.  If you want
20694 to find the prerequisite via a @code{VPATH} search, you have to code the
20695 whole thing manually.  @xref{Build Directories}.
20697 @node Automatic Rule Rewriting
20698 @subsection Automatic Rule Rewriting
20699 @cindex @code{VPATH} and automatic rule rewriting
20700 @cindex automatic rule rewriting and @code{VPATH}
20702 Some @command{make} implementations, such as Solaris and Tru64,
20703 search for prerequisites in @code{VPATH} and
20704 then rewrite each occurrence as a plain word in the rule.
20705 For instance:
20707 @example
20708 # This isn't portable to GNU make.
20709 VPATH = ../pkg/src
20710 f.c: if.c
20711         cp if.c f.c
20712 @end example
20714 @noindent
20715 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20716 found in @file{../pkg/src}.
20718 However, this rule leads to real problems in practice.  For example, if
20719 the source directory contains an ordinary file named @file{test} that is
20720 used in a dependency, Solaris @command{make} rewrites commands like
20721 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20722 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20723 completely unaware of shell syntax used in the rules, so the VPATH
20724 rewrite can potentially apply to @emph{any} whitespace-separated word
20725 in a rule, including shell variables, functions, and keywords.
20727 @example
20728 $ @kbd{mkdir build}
20729 $ @kbd{cd build}
20730 $ @kbd{cat > Makefile <<'END'}
20731 VPATH = ..
20732 all: arg func for echo
20733         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20734         func "hello world"
20736 $ @kbd{touch ../arg ../func ../for ../echo}
20737 $ @kbd{make}
20738 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20739 ../func "hello world"
20740 sh: syntax error at line 1: `do' unexpected
20741 *** Error code 2
20742 @end example
20744 @noindent
20745 To avoid this problem, portable makefiles should never mention a source
20746 file or dependency whose name is that of a shell keyword like @file{for}
20747 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20748 @command{test}, or a shell function or variable used in the corresponding
20749 @command{Makefile} recipe.
20751 Because of these problems GNU @command{make} and many other @command{make}
20752 implementations do not rewrite commands, so portable makefiles should
20753 search @code{VPATH} manually.  It is tempting to write this:
20755 @smallexample
20756 # This isn't portable to Solaris make.
20757 VPATH = ../pkg/src
20758 f.c: if.c
20759         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20760 @end smallexample
20762 @noindent
20763 However, the ``prerequisite rewriting'' still applies here.  So if
20764 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20765 execute
20767 @smallexample
20768 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20769 @end smallexample
20771 @noindent
20772 which reduces to
20774 @example
20775 cp if.c f.c
20776 @end example
20778 @noindent
20779 and thus fails.  Oops.
20781 A simple workaround, and good practice anyway, is to use @samp{$?} and
20782 @samp{$@@} when possible:
20784 @smallexample
20785 VPATH = ../pkg/src
20786 f.c: if.c
20787         cp $? $@@
20788 @end smallexample
20790 @noindent
20791 but this does not generalize well to commands with multiple
20792 prerequisites.  A more general workaround is to rewrite the rule so that
20793 the prerequisite @file{if.c} never appears as a plain word.  For
20794 example, these three rules would be safe, assuming @file{if.c} is in
20795 @file{../pkg/src} and the other files are in the working directory:
20797 @smallexample
20798 VPATH = ../pkg/src
20799 f.c: if.c f1.c
20800         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20801 g.c: if.c g1.c
20802         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20803 h.c: if.c h1.c
20804         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20805 @end smallexample
20807 Things get worse when your prerequisites are in a macro.
20809 @example
20810 VPATH = ../pkg/src
20811 HEADERS = f.h g.h h.h
20812 install-HEADERS: $(HEADERS)
20813         for i in $(HEADERS); do \
20814           $(INSTALL) -m 644 \
20815             `test -f $$i || echo $(VPATH)/`$$i \
20816             $(DESTDIR)$(includedir)/$$i; \
20817 @c $$ restore font-lock
20818         done
20819 @end example
20821 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20822 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20823 where @code{f.h} and @code{g.h} are plain words and are hence
20824 subject to @code{VPATH} adjustments.
20826 If the three files are in @file{../pkg/src}, the rule is run as:
20828 @example
20829 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20830   install -m 644 \
20831      `test -f $i || echo ../pkg/src/`$i \
20832      /usr/local/include/$i; \
20833 done
20834 @end example
20836 where the two first @command{install} calls fail.  For instance,
20837 consider the @code{f.h} installation:
20839 @example
20840 install -m 644 \
20841   `test -f ../pkg/src/f.h || \
20842     echo ../pkg/src/ \
20843   `../pkg/src/f.h \
20844   /usr/local/include/../pkg/src/f.h;
20845 @end example
20847 @noindent
20848 It reduces to:
20850 @example
20851 install -m 644 \
20852   ../pkg/src/f.h \
20853   /usr/local/include/../pkg/src/f.h;
20854 @end example
20856 Note that the manual @code{VPATH} search did not cause any problems here;
20857 however this command installs @file{f.h} in an incorrect directory.
20859 Trying to quote @code{$(HEADERS)} in some way, as we did for
20860 @code{foo.c} a few makefiles ago, does not help:
20862 @example
20863 install-HEADERS: $(HEADERS)
20864         headers='$(HEADERS)'; \
20865         for i in $$headers; do \
20866           $(INSTALL) -m 644 \
20867             `test -f $$i || echo $(VPATH)/`$$i \
20868             $(DESTDIR)$(includedir)/$$i; \
20869         done
20870 @end example
20872 Now, @code{headers='$(HEADERS)'} macro-expands to:
20874 @example
20875 headers='f.h g.h h.h'
20876 @end example
20878 @noindent
20879 but @code{g.h} is still a plain word.  (As an aside, the idiom
20880 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20881 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20882 syntax error on @code{for i in;}.)
20884 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20886 @example
20887 VPATH = ../pkg/src
20888 HEADERS = f.h g.h h.h
20889 install-HEADERS: $(HEADERS)
20890         headers='$(HEADERS)'; \
20891         for i in $$headers; do \
20892           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20893           $(INSTALL) -m 644 \
20894             `test -f $$i || echo $(VPATH)/`$$i \
20895             $(DESTDIR)$(includedir)/$$i; \
20896 @c $$ restore font-lock
20897         done
20898 @end example
20900 Automake does something similar.  However the above hack works only if
20901 the files listed in @code{HEADERS} are in the current directory or a
20902 subdirectory; they should not be in an enclosing directory.  If we had
20903 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20904 build with Tru64 @command{make}.  The reason is that not only does
20905 Tru64 @command{make} rewrite dependencies, but it also simplifies
20906 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20907 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20908 a leading @file{../pkg/src/} component.
20910 The following example makes the behavior of Tru64 @command{make}
20911 more apparent.
20913 @example
20914 $ @kbd{cat Makefile}
20915 VPATH = sub
20916 all: ../foo
20917         echo ../foo
20918 $ @kbd{ls}
20919 Makefile foo
20920 $ @kbd{make}
20921 echo foo
20923 @end example
20925 @noindent
20926 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20927 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20928 directory does not even exist, this just means that the simplification
20929 occurred before the file was checked for.)
20931 For the record here is how SunOS 4 @command{make} behaves on this
20932 example.
20934 @smallexample
20935 $ @kbd{make}
20936 make: Fatal error: Don't know how to make target `../foo'
20937 $ @kbd{mkdir sub}
20938 $ @kbd{make}
20939 echo sub/../foo
20940 sub/../foo
20941 @end smallexample
20944 @node Tru64 Directory Magic
20945 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20946 @cindex @code{VPATH} and prerequisite directories
20947 @cindex prerequisite directories and @code{VPATH}
20949 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20950 @command{make} creates it in the current directory.
20952 @example
20953 $ @kbd{mkdir -p foo/bar build}
20954 $ @kbd{cd build}
20955 $ @kbd{cat >Makefile <<END
20956 VPATH = ..
20957 all: foo/bar
20958 END}
20959 $ @kbd{make}
20960 mkdir foo
20961 mkdir foo/bar
20962 @end example
20964 This can yield unexpected results if a rule uses a manual @code{VPATH}
20965 search as presented before.
20967 @example
20968 VPATH = ..
20969 all : foo/bar
20970         command `test -d foo/bar || echo ../`foo/bar
20971 @end example
20973 The above @command{command} is run on the empty @file{foo/bar}
20974 directory that was created in the current directory.
20976 @node Make Target Lookup
20977 @subsection Make Target Lookup
20978 @cindex @code{VPATH}, resolving target pathnames
20980 GNU @command{make} uses a complex algorithm to decide when it
20981 should use files found via a @code{VPATH} search.  @xref{Search
20982 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20983 Manual}.
20985 If a target needs to be rebuilt, GNU @command{make} discards the
20986 file name found during the @code{VPATH} search for this target, and
20987 builds the file locally using the file name given in the makefile.
20988 If a target does not need to be rebuilt, GNU @command{make} uses the
20989 file name found during the @code{VPATH} search.
20991 Other @command{make} implementations, like NetBSD @command{make}, are
20992 easier to describe: the file name found during the @code{VPATH} search
20993 is used whether the target needs to be rebuilt or not.  Therefore
20994 new files are created locally, but existing files are updated at their
20995 @code{VPATH} location.
20997 OpenBSD and FreeBSD @command{make}, however,
20998 never perform a
20999 @code{VPATH} search for a dependency that has an explicit rule.
21000 This is extremely annoying.
21002 When attempting a @code{VPATH} build for an autoconfiscated package
21003 (e.g., @code{mkdir build && cd build && ../configure}), this means
21005 @command{make} builds everything locally in the @file{build}
21006 directory, while BSD @command{make} builds new files locally and
21007 updates existing files in the source directory.
21009 @example
21010 $ @kbd{cat Makefile}
21011 VPATH = ..
21012 all: foo.x bar.x
21013 foo.x bar.x: newer.x
21014         @@echo Building $@@
21015 $ @kbd{touch ../bar.x}
21016 $ @kbd{touch ../newer.x}
21017 $ @kbd{make}        # GNU make
21018 Building foo.x
21019 Building bar.x
21020 $ @kbd{pmake}       # NetBSD make
21021 Building foo.x
21022 Building ../bar.x
21023 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21024 Building foo.x
21025 Building bar.x
21026 $ @kbd{tmake}       # Tru64 make
21027 Building foo.x
21028 Building bar.x
21029 $ @kbd{touch ../bar.x}
21030 $ @kbd{make}        # GNU make
21031 Building foo.x
21032 $ @kbd{pmake}       # NetBSD make
21033 Building foo.x
21034 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21035 Building foo.x
21036 Building bar.x
21037 $ @kbd{tmake}       # Tru64 make
21038 Building foo.x
21039 Building bar.x
21040 @end example
21042 Note how NetBSD @command{make} updates @file{../bar.x} in its
21043 VPATH location, and how FreeBSD, OpenBSD, and Tru64
21044 @command{make} always
21045 update @file{bar.x}, even when @file{../bar.x} is up to date.
21047 Another point worth mentioning is that once GNU @command{make} has
21048 decided to ignore a @code{VPATH} file name (e.g., it ignored
21049 @file{../bar.x} in the above example) it continues to ignore it when
21050 the target occurs as a prerequisite of another rule.
21052 The following example shows that GNU @command{make} does not look up
21053 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
21054 because it ignored the @code{VPATH} result of @file{bar.x} while running
21055 the @code{bar.x: newer.x} rule.
21057 @example
21058 $ @kbd{cat Makefile}
21059 VPATH = ..
21060 all: bar.y
21061 bar.x: newer.x
21062         @@echo Building $@@
21063 .SUFFIXES: .x .y
21064 .x.y:
21065         cp $< $@@
21066 $ @kbd{touch ../bar.x}
21067 $ @kbd{touch ../newer.x}
21068 $ @kbd{make}        # GNU make
21069 Building bar.x
21070 cp bar.x bar.y
21071 cp: cannot stat `bar.x': No such file or directory
21072 make: *** [bar.y] Error 1
21073 $ @kbd{pmake}       # NetBSD make
21074 Building ../bar.x
21075 cp ../bar.x bar.y
21076 $ @kbd{rm bar.y}
21077 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21078 echo Building bar.x
21079 cp bar.x bar.y
21080 cp: cannot stat `bar.x': No such file or directory
21081 *** Error code 1
21082 $ @kbd{tmake}       # Tru64 make
21083 Building bar.x
21084 cp: bar.x: No such file or directory
21085 *** Exit 1
21086 @end example
21088 Note that if you drop away the command from the @code{bar.x: newer.x}
21089 rule, GNU @command{make} magically starts to work: it
21090 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21091 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21092 uses.  Tru64 also works, but FreeBSD and OpenBSD
21093 still don't.
21095 @example
21096 $ @kbd{cat Makefile}
21097 VPATH = ..
21098 all: bar.y
21099 bar.x: newer.x
21100 .SUFFIXES: .x .y
21101 .x.y:
21102         cp $< $@@
21103 $ @kbd{touch ../bar.x}
21104 $ @kbd{touch ../newer.x}
21105 $ @kbd{make}        # GNU make
21106 cp ../bar.x bar.y
21107 $ @kbd{rm bar.y}
21108 $ @kbd{pmake}       # NetBSD make
21109 cp ../bar.x bar.y
21110 $ @kbd{rm bar.y}
21111 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21112 cp bar.x bar.y
21113 cp: cannot stat `bar.x': No such file or directory
21114 *** Error code 1
21115 $ @kbd{tmake}       # Tru64 make
21116 cp ../bar.x bar.y
21117 @end example
21119 It seems the sole solution that would please every @command{make}
21120 implementation is to never rely on @code{VPATH} searches for targets.
21121 In other words, @code{VPATH} should be reserved to unbuilt sources.
21124 @node Single Suffix Rules
21125 @section Single Suffix Rules and Separated Dependencies
21126 @cindex Single Suffix Inference Rule
21127 @cindex Rule, Single Suffix Inference
21128 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21129 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21130 (@samp{.from:}).
21132 @cindex Separated Dependencies
21133 @dfn{Separated dependencies} simply refers to listing the prerequisite
21134 of a target, without defining a rule.  Usually one can list on the one
21135 hand side, the rules, and on the other hand side, the dependencies.
21137 Solaris @command{make} does not support separated dependencies for
21138 targets defined by single suffix rules:
21140 @example
21141 $ @kbd{cat Makefile}
21142 .SUFFIXES: .in
21143 foo: foo.in
21144 .in:
21145         cp $< $@@
21146 $ @kbd{touch foo.in}
21147 $ @kbd{make}
21148 $ @kbd{ls}
21149 Makefile  foo.in
21150 @end example
21152 @noindent
21153 while GNU Make does:
21155 @example
21156 $ @kbd{gmake}
21157 cp foo.in foo
21158 $ @kbd{ls}
21159 Makefile  foo       foo.in
21160 @end example
21162 Note it works without the @samp{foo: foo.in} dependency.
21164 @example
21165 $ @kbd{cat Makefile}
21166 .SUFFIXES: .in
21167 .in:
21168         cp $< $@@
21169 $ @kbd{make foo}
21170 cp foo.in foo
21171 @end example
21173 @noindent
21174 and it works with double suffix inference rules:
21176 @example
21177 $ @kbd{cat Makefile}
21178 foo.out: foo.in
21179 .SUFFIXES: .in .out
21180 .in.out:
21181         cp $< $@@
21182 $ @kbd{make}
21183 cp foo.in foo.out
21184 @end example
21186 As a result, in such a case, you have to write target rules.
21188 @node Timestamps and Make
21189 @section Timestamp Resolution and Make
21190 @cindex timestamp resolution
21191 Traditionally, file timestamps had 1-second resolution, and
21192 @command{make} used those timestamps to determine whether one file was
21193 newer than the other.  However, many modern file systems have
21194 timestamps with 1-nanosecond resolution.  Some @command{make}
21195 implementations look at the entire timestamp; others ignore the
21196 fractional part, which can lead to incorrect results.  Normally this
21197 is not a problem, but in some extreme cases you may need to use tricks
21198 like @samp{sleep 1} to work around timestamp truncation bugs.
21200 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21201 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21202 Tools}).  Hence you should be wary of rules like this:
21204 @example
21205 dest: src
21206         cp -p src dest
21207 @end example
21209 as @file{dest} often appears to be older than @file{src} after the
21210 timestamp is truncated, and this can cause @command{make} to do
21211 needless rework the next time it is invoked.  To work around this
21212 problem, you can use a timestamp file, e.g.:
21214 @example
21215 dest-stamp: src
21216         cp -p src dest
21217         date >dest-stamp
21218 @end example
21220 Apart from timestamp resolution, there are also differences in handling
21221 equal timestamps.  HP-UX @command{make} updates targets if it has the
21222 same time stamp as one of its prerequisites, in violation of Posix rules.
21224 This can cause spurious rebuilds for repeated runs of @command{make}.
21225 This in turn can cause @command{make} to fail if it tries to rebuild
21226 generated files in a possibly read-only source tree with tools not
21227 present on the end-user machine.  Use GNU @command{make} instead.
21231 @c ======================================== Portable C and C++ Programming
21233 @node Portable C and C++
21234 @chapter Portable C and C++ Programming
21235 @cindex Portable C and C++ programming
21237 C and C++ programs often use low-level features of the underlying
21238 system, and therefore are often more difficult to make portable to other
21239 platforms.
21241 Several standards have been developed to help make your programs more
21242 portable.  If you write programs with these standards in mind, you can
21243 have greater confidence that your programs work on a wide variety
21244 of systems.
21245 @ifhtml
21246 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21247 Standards Supported by GCC}
21248 @end ifhtml
21249 @ifnothtml
21250 @xref{Standards, , Language Standards Supported by
21251 GCC, gcc, Using the GNU Compiler Collection
21252 (GCC)},
21253 @end ifnothtml
21254 for a list of C-related standards.  Many programs also assume the
21255 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
21257 Some old code is written to be portable to K&R C, which predates any C
21258 standard.  K&R C compilers are no longer of practical interest, though,
21259 and the rest of section assumes at least C89, the first C standard.
21261 Program portability is a huge topic, and this section can only briefly
21262 introduce common pitfalls.  @xref{System Portability, , Portability
21263 between System Types, standards, The GNU Coding Standards}, for
21264 more information.
21266 @menu
21267 * Varieties of Unportability::  How to make your programs unportable
21268 * Integer Overflow::            When integers get too large
21269 * Preprocessor Arithmetic::     @code{#if} expression problems
21270 * Null Pointers::               Properties of null pointers
21271 * Buffer Overruns::             Subscript errors and the like
21272 * Volatile Objects::            @code{volatile} and signals
21273 * Floating Point Portability::  Portable floating-point arithmetic
21274 * Exiting Portably::            Exiting and the exit status
21275 @end menu
21277 @node Varieties of Unportability
21278 @section Varieties of Unportability
21279 @cindex portability
21281 Autoconf tests and ordinary programs often need to test what is allowed
21282 on a system, and therefore they may need to deliberately exceed the
21283 boundaries of what the standards allow, if only to see whether an
21284 optional feature is present.  When you write such a program, you should
21285 keep in mind the difference between constraints, unspecified behavior,
21286 and undefined behavior.
21288 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21289 example constraint is that C programs must not declare a bit-field with
21290 negative width.  Tests can therefore reliably assume that programs with
21291 negative-width bit-fields are rejected by a compiler that conforms
21292 to the standard.
21294 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21295 multiple possibilities.  For example, the order of evaluation of
21296 function arguments is unspecified.  Some unspecified behavior is
21297 @dfn{implementation-defined}, i.e., documented by the implementation,
21298 but since Autoconf tests cannot read the documentation they cannot
21299 distinguish between implementation-defined and other unspecified
21300 behavior.  It is common for Autoconf tests to probe implementations to
21301 determine otherwise-unspecified behavior.
21303 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21304 the implementation to do anything it pleases.  For example,
21305 dereferencing a null pointer leads to undefined behavior.  If possible,
21306 test programs should avoid undefined behavior, since a program with
21307 undefined behavior might succeed on a test that should fail.
21309 The above rules apply to programs that are intended to conform to the
21310 standard.  However, strictly-conforming programs are quite rare, since
21311 the standards are so limiting.  A major goal of Autoconf is to support
21312 programs that use implementation features not described by the standard,
21313 and it is fairly common for test programs to violate the above rules, if
21314 the programs work well enough in practice.
21316 @node Integer Overflow
21317 @section Integer Overflow
21318 @cindex integer overflow
21319 @cindex overflow, signed integer
21320 @cindex signed integer overflow
21321 @cindex wraparound arithmetic
21323 In practice many portable C programs assume that signed integer overflow wraps
21324 around reliably using two's complement arithmetic.  Yet the C standard
21325 says that program behavior is undefined on overflow, and in a few cases
21326 C programs do not work on some modern implementations because their
21327 overflows do not wrap around as their authors expected.  Conversely, in
21328 signed integer remainder, the C standard requires overflow
21329 behavior that is commonly not implemented.
21331 @menu
21332 * Integer Overflow Basics::     Why integer overflow is a problem
21333 * Signed Overflow Examples::    Examples of code assuming wraparound
21334 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21335 * Signed Overflow Advice::      Practical advice for signed overflow issues
21336 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21337 @end menu
21339 @node Integer Overflow Basics
21340 @subsection Basics of Integer Overflow
21341 @cindex integer overflow
21342 @cindex overflow, signed integer
21343 @cindex signed integer overflow
21344 @cindex wraparound arithmetic
21346 In languages like C, unsigned integer overflow reliably wraps around;
21347 e.g., @code{UINT_MAX + 1} yields zero.
21348 This is guaranteed by the C standard and is
21349 portable in practice, unless you specify aggressive,
21350 nonstandard optimization options
21351 suitable only for special applications.
21353 In contrast, the C standard says that signed integer overflow leads to
21354 undefined behavior where a program can do anything, including dumping
21355 core or overrunning a buffer.  The misbehavior can even precede the
21356 overflow.  Such an overflow can occur during addition, subtraction,
21357 multiplication, division, and left shift.
21359 Despite this requirement of the standard, many C programs and Autoconf
21360 tests assume that signed integer overflow silently wraps around modulo a
21361 power of two, using two's complement arithmetic, so long as you cast the
21362 resulting value to a signed integer type or store it into a signed
21363 integer variable.  If you use conservative optimization flags, such
21364 programs are generally portable to the vast majority of modern
21365 platforms, with a few exceptions discussed later.
21367 For historical reasons the C standard also allows implementations with
21368 ones' complement or signed magnitude arithmetic, but it is safe to
21369 assume two's complement nowadays.
21371 Also, overflow can occur when converting an out-of-range value to a
21372 signed integer type.  Here a standard implementation must define what
21373 happens, but this might include raising an exception.  In practice all
21374 known implementations support silent wraparound in this case, so you need
21375 not worry about other possibilities.
21377 @node Signed Overflow Examples
21378 @subsection Examples of Code Assuming Wraparound Overflow
21379 @cindex integer overflow
21380 @cindex overflow, signed integer
21381 @cindex signed integer overflow
21382 @cindex wraparound arithmetic
21384 There has long been a tension between what the C standard requires for
21385 signed integer overflow, and what C programs commonly assume.  The
21386 standard allows aggressive optimizations based on assumptions that
21387 overflow never occurs, but many practical C programs rely on overflow
21388 wrapping around.  These programs do not conform to the standard, but
21389 they commonly work in practice because compiler writers are
21390 understandably reluctant to implement optimizations that would break
21391 many programs, unless perhaps a user specifies aggressive optimization.
21393 The C Standard says that if a program has signed integer overflow its
21394 behavior is undefined, and the undefined behavior can even precede the
21395 overflow.  To take an extreme example:
21397 @c Inspired by Robert Dewar's example in
21398 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21399 @example
21400 if (password == expected_password)
21401   allow_superuser_privileges ();
21402 else if (counter++ == INT_MAX)
21403   abort ();
21404 else
21405   printf ("%d password mismatches\n", counter);
21406 @end example
21408 @noindent
21409 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21410 @code{counter++} must overflow and the behavior is undefined, so the C
21411 standard allows the compiler to optimize away the test against
21412 @code{INT_MAX} and the @code{abort} call.
21413 Worse, if an earlier bug in the program lets the compiler deduce that
21414 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21415 the C standard allows the compiler to optimize away the password test
21416 and generate code that allows superuser privileges unconditionally.
21418 Despite this requirement by the standard, it has long been common for C
21419 code to assume wraparound arithmetic after signed overflow, and all
21420 known practical C implementations support some C idioms that assume
21421 wraparound signed arithmetic, even if the idioms do not conform
21422 strictly to the standard.  If your code looks like the following
21423 examples it will almost surely work with real-world compilers.
21425 Here is an example derived from the 7th Edition Unix implementation of
21426 @code{atoi} (1979-01-10):
21428 @example
21429 char *p;
21430 int f, n;
21431 @dots{}
21432 while (*p >= '0' && *p <= '9')
21433   n = n * 10 + *p++ - '0';
21434 return (f ? -n : n);
21435 @end example
21437 @noindent
21438 Even if the input string is in range, on most modern machines this has
21439 signed overflow when computing the most negative integer (the @code{-n}
21440 overflows) or a value near an extreme integer (the first @code{+}
21441 overflows).
21443 Here is another example, derived from the 7th Edition implementation of
21444 @code{rand} (1979-01-10).  Here the programmer expects both
21445 multiplication and addition to wrap on overflow:
21447 @example
21448 static long int randx = 1;
21449 @dots{}
21450 randx = randx * 1103515245 + 12345;
21451 return (randx >> 16) & 077777;
21452 @end example
21454 In the following example, derived from the GNU C Library 2.5
21455 implementation of @code{mktime} (2006-09-09), the code assumes
21456 wraparound arithmetic in @code{+} to detect signed overflow:
21458 @example
21459 time_t t, t1, t2;
21460 int sec_requested, sec_adjustment;
21461 @dots{}
21462 t1 = t + sec_requested;
21463 t2 = t1 + sec_adjustment;
21464 if (((t1 < t) != (sec_requested < 0))
21465     | ((t2 < t1) != (sec_adjustment < 0)))
21466   return -1;
21467 @end example
21469 If your code looks like these examples, it is probably safe even though
21470 it does not strictly conform to the C standard.  This might lead one to
21471 believe that one can generally assume wraparound on overflow, but that
21472 is not always true, as can be seen in the next section.
21474 @node Optimization and Wraparound
21475 @subsection Optimizations That Break Wraparound Arithmetic
21476 @cindex loop induction
21478 Compilers sometimes generate code that is incompatible with wraparound
21479 integer arithmetic.  A simple example is an algebraic simplification: a
21480 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21481 because it assumes that @code{i * 2000} does not overflow.  The
21482 translation is not equivalent to the original when overflow occurs:
21483 e.g., in the typical case of 32-bit signed two's complement wraparound
21484 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21485 the original expression returns @minus{}2147483 but the optimized
21486 version returns the mathematically correct value 2147484.
21488 More subtly, loop induction optimizations often exploit the undefined
21489 behavior of signed overflow.  Consider the following contrived function
21490 @code{sumc}:
21492 @example
21494 sumc (int lo, int hi)
21496   int sum = 0;
21497   int i;
21498   for (i = lo; i <= hi; i++)
21499     sum ^= i * 53;
21500   return sum;
21502 @end example
21504 @noindent
21505 To avoid multiplying by 53 each time through the loop, an optimizing
21506 compiler might internally transform @code{sumc} to the equivalent of the
21507 following:
21509 @example
21511 transformed_sumc (int lo, int hi)
21513   int sum = 0;
21514   int hic = hi * 53;
21515   int ic;
21516   for (ic = lo * 53; ic <= hic; ic += 53)
21517     sum ^= ic;
21518   return sum;
21520 @end example
21522 @noindent
21523 This transformation is allowed by the C standard, but it is invalid for
21524 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21525 overflow in computing expressions like @code{hi * 53} can cause the
21526 expression @code{i <= hi} to yield a different value from the
21527 transformed expression @code{ic <= hic}.
21529 For this reason, compilers that use loop induction and similar
21530 techniques often do not support reliable wraparound arithmetic when a
21531 loop induction variable like @code{ic} is involved.  Since loop
21532 induction variables are generated by the compiler, and are not visible
21533 in the source code, it is not always trivial to say whether the problem
21534 affects your code.
21536 Hardly any code actually depends on wraparound arithmetic in cases like
21537 these, so in practice these loop induction optimizations are almost
21538 always useful.  However, edge cases in this area can cause problems.
21539 For example:
21541 @example
21542 int j;
21543 for (j = 1; 0 < j; j *= 2)
21544   test (j);
21545 @end example
21547 @noindent
21548 Here, the loop attempts to iterate through all powers of 2 that
21549 @code{int} can represent, but the C standard allows a compiler to
21550 optimize away the comparison and generate an infinite loop,
21551 under the argument that behavior is undefined on overflow.  As of this
21552 writing this optimization is not done by any production version of
21553 GCC with @option{-O2}, but it might be performed by other
21554 compilers, or by more aggressive GCC optimization options,
21555 and the GCC developers have not decided whether it will
21556 continue to work with GCC and @option{-O2}.
21558 @node Signed Overflow Advice
21559 @subsection Practical Advice for Signed Overflow Issues
21560 @cindex integer overflow
21561 @cindex overflow, signed integer
21562 @cindex signed integer overflow
21563 @cindex wraparound arithmetic
21565 Ideally the safest approach is to avoid signed integer overflow
21566 entirely.  For example, instead of multiplying two signed integers, you
21567 can convert them to unsigned integers, multiply the unsigned values,
21568 then test whether the result is in signed range.
21570 Rewriting code in this way will be inconvenient, though, particularly if
21571 the signed values might be negative.  Also, it may hurt
21572 performance.  Using unsigned arithmetic to check for overflow is
21573 particularly painful to do portably and efficiently when dealing with an
21574 integer type like @code{uid_t} whose width and signedness vary from
21575 platform to platform.
21577 Furthermore, many C applications pervasively assume wraparound behavior
21578 and typically it is not easy to find and remove all these assumptions.
21579 Hence it is often useful to maintain nonstandard code that assumes
21580 wraparound on overflow, instead of rewriting the code.  The rest of this
21581 section attempts to give practical advice for this situation.
21583 If your code wants to detect signed integer overflow in @code{sum = a +
21584 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21585 < 0)}.
21587 If your code uses a signed loop index, make sure that the index cannot
21588 overflow, along with all signed expressions derived from the index.
21589 Here is a contrived example of problematic code with two instances of
21590 overflow.
21592 @example
21593 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21594   if (i + 1 < 0)
21595     @{
21596       report_overflow ();
21597       break;
21598     @}
21599 @end example
21601 @noindent
21602 Because of the two overflows, a compiler might optimize away or
21603 transform the two comparisons in a way that is incompatible with the
21604 wraparound assumption.
21606 If your code uses an expression like @code{(i * 2000) / 1000} and you
21607 actually want the multiplication to wrap around on overflow, use
21608 unsigned arithmetic
21609 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21611 If your code assumes wraparound behavior and you want to insulate it
21612 against any GCC optimizations that would fail to support that
21613 behavior, you should use GCC's @option{-fwrapv} option, which
21614 causes signed overflow to wrap around reliably (except for division and
21615 remainder, as discussed in the next section).
21617 If you need to port to platforms where signed integer overflow does not
21618 reliably wrap around (e.g., due to hardware overflow checking, or to
21619 highly aggressive optimizations), you should consider debugging with
21620 GCC's @option{-ftrapv} option, which causes signed overflow to
21621 raise an exception.
21623 @node Signed Integer Division
21624 @subsection Signed Integer Division and Integer Overflow
21625 @cindex division, integer
21627 Overflow in signed
21628 integer division is not always harmless: for example, on CPUs of the
21629 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21630 which by default terminates the program.  Worse, taking the remainder
21631 of these two values typically yields the same signal on these CPUs,
21632 even though the C standard requires @code{INT_MIN % -1} to yield zero
21633 because the expression does not overflow.
21635 @node Preprocessor Arithmetic
21636 @section Preprocessor Arithmetic
21637 @cindex preprocessor arithmetic
21639 In C99 and later, preprocessor arithmetic, used for @code{#if}
21640 expressions, must
21641 be evaluated as if all signed values are of type @code{intmax_t} and all
21642 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21643 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21644 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21645 @code{long long int}.  Also, some older preprocessors mishandle
21646 constants ending in @code{LL}.  To work around these problems, you can
21647 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21648 @code{configure}-time rather than at @code{#if}-time.
21650 @node Null Pointers
21651 @section Properties of Null Pointers
21652 @cindex null pointers
21654 Most modern hosts reliably fail when you attempt to dereference a null
21655 pointer.
21657 On almost all modern hosts, null pointers use an all-bits-zero internal
21658 representation, so you can reliably use @code{memset} with 0 to set all
21659 the pointers in an array to null values.
21661 If @code{p} is a null pointer to an object type, the C expression
21662 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21663 the standard says that it has undefined behavior.
21665 @node Buffer Overruns
21666 @section Buffer Overruns and Subscript Errors
21667 @cindex buffer overruns
21669 Buffer overruns and subscript errors are the most common dangerous
21670 errors in C programs.  They result in undefined behavior because storing
21671 outside an array typically modifies storage that is used by some other
21672 object, and most modern systems lack runtime checks to catch these
21673 errors.  Programs should not rely on buffer overruns being caught.
21675 There is one exception to the usual rule that a portable program cannot
21676 address outside an array.  In C, it is valid to compute the address just
21677 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21678 so long as you do not dereference the resulting pointer.  But it is not
21679 valid to compute the address just before an object, e.g., @code{&a[-1]};
21680 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21681 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21682 reliable in general, and it is usually easy enough to avoid the
21683 potential portability problem, e.g., by allocating an extra unused array
21684 element at the start or end.
21686 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21688 users might also consider using the @option{-fmudflap} option to catch
21689 overruns.
21691 Buffer overruns are usually caused by off-by-one errors, but there are
21692 more subtle ways to get them.
21694 Using @code{int} values to index into an array or compute array sizes
21695 causes problems on typical 64-bit hosts where an array index might
21696 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21697 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21698 are signed, and are wide enough in practice.
21700 If you add or multiply two numbers to calculate an array size, e.g.,
21701 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21702 multiplication overflows.
21704 Many implementations of the @code{alloca} function silently misbehave
21705 and can generate buffer overflows if given sizes that are too large.
21706 The size limits are implementation dependent, but are at least 4000
21707 bytes on all platforms that we know about.
21709 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21710 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21711 portable code should not use them unless the inputs are known to be
21712 within certain limits.  The time-related functions can overflow their
21713 buffers if given timestamps out of range (e.g., a year less than -999
21714 or greater than 9999).  Time-related buffer overflows cannot happen with
21715 recent-enough versions of the GNU C library, but are possible
21716 with other
21717 implementations.  The @code{gets} function is the worst, since it almost
21718 invariably overflows its buffer when presented with an input line larger
21719 than the buffer.
21721 @node Volatile Objects
21722 @section Volatile Objects
21723 @cindex volatile objects
21725 The keyword @code{volatile} is often misunderstood in portable code.
21726 Its use inhibits some memory-access optimizations, but programmers often
21727 wish that it had a different meaning than it actually does.
21729 @code{volatile} was designed for code that accesses special objects like
21730 memory-mapped device registers whose contents spontaneously change.
21731 Such code is inherently low-level, and it is difficult to specify
21732 portably what @code{volatile} means in these cases.  The C standard
21733 says, ``What constitutes an access to an object that has
21734 volatile-qualified type is implementation-defined,'' so in theory each
21735 implementation is supposed to fill in the gap by documenting what
21736 @code{volatile} means for that implementation.  In practice, though,
21737 this documentation is usually absent or incomplete.
21739 One area of confusion is the distinction between objects defined with
21740 volatile types, and volatile lvalues.  From the C standard's point of
21741 view, an object defined with a volatile type has externally visible
21742 behavior.  You can think of such objects as having little oscilloscope
21743 probes attached to them, so that the user can observe some properties of
21744 accesses to them, just as the user can observe data written to output
21745 files.  However, the standard does not make it clear whether users can
21746 observe accesses by volatile lvalues to ordinary objects.  For example:
21748 @example
21749 /* Declare and access a volatile object.
21750    Accesses to X are "visible" to users.  */
21751 static int volatile x;
21752 x = 1;
21754 /* Access two ordinary objects via a volatile lvalue.
21755    It's not clear whether accesses to *P are "visible".  */
21756 int y;
21757 int *z = malloc (sizeof (int));
21758 int volatile *p;
21759 p = &y;
21760 *p = 1;
21761 p = z;
21762 *p = 1;
21763 @end example
21765 Programmers often wish that @code{volatile} meant ``Perform the memory
21766 access here and now, without merging several memory accesses, without
21767 changing the memory word size, and without reordering.''  But the C
21768 standard does not require this.  For objects defined with a volatile
21769 type, accesses must be done before the next sequence point; but
21770 otherwise merging, reordering, and word-size change is allowed.  Worse,
21771 it is not clear from the standard whether volatile lvalues provide more
21772 guarantees in general than nonvolatile lvalues, if the underlying
21773 objects are ordinary.
21775 Even when accessing objects defined with a volatile type,
21776 the C standard allows only
21777 extremely limited signal handlers: in C99 the behavior is undefined if a signal
21778 handler reads any nonlocal object, or writes to any nonlocal object
21779 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21780 library function other than @code{abort}, @code{signal}, and
21781 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21782 disturbing ordinary computation.  C11 and Posix allow some additional
21783 behavior in a portable signal handler, but are still quite restrictive.
21785 Some C implementations allow memory-access optimizations within each
21786 translation unit, such that actual behavior agrees with the behavior
21787 required by the standard only when calling a function in some other
21788 translation unit, and a signal handler acts like it was called from a
21789 different translation unit.  The C99 standard hints that in these
21790 implementations, objects referred to by signal handlers ``would require
21791 explicit specification of @code{volatile} storage, as well as other
21792 implementation-defined restrictions.''  But unfortunately even for this
21793 special case these other restrictions are often not documented well.
21794 This area was significantly changed in C11, and eventually implementations
21795 will probably head in the C11 direction, but this will take some time.
21796 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21797 GNU Compiler Collection (GCC)}, for some
21798 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21799 Defining Signal Handlers, libc, The GNU C Library}, for some
21800 restrictions imposed by the GNU C library.  Restrictions
21801 differ on other platforms.
21803 If possible, it is best to use a signal handler that fits within the
21804 limits imposed by the C and Posix standards.
21806 If this is not practical, you can try the following rules of thumb.  A
21807 signal handler should access only volatile lvalues, preferably lvalues
21808 that refer to objects defined with a volatile type, and should not
21809 assume that the accessed objects have an internally consistent state
21810 if they are larger than a machine word.  Furthermore, installers
21811 should employ compilers and compiler options that are commonly used
21812 for building operating system kernels, because kernels often need more
21813 from @code{volatile} than the C Standard requires, and installers who
21814 compile an application in a similar environment can sometimes benefit
21815 from the extra constraints imposed by kernels on compilers.
21816 Admittedly we are handwaving somewhat here, as there are few
21817 guarantees in this area; the rules of thumb may help to fix some bugs
21818 but there is a good chance that they will not fix them all.
21820 For @code{volatile}, C++ has the same problems that C does.
21821 Multithreaded applications have even more problems with @code{volatile},
21822 but they are beyond the scope of this section.
21824 The bottom line is that using @code{volatile} typically hurts
21825 performance but should not hurt correctness.  In some cases its use
21826 does help correctness, but these cases are often so poorly understood
21827 that all too often adding @code{volatile} to a data structure merely
21828 alleviates some symptoms of a bug while not fixing the bug in general.
21830 @node Floating Point Portability
21831 @section Floating Point Portability
21832 @cindex floating point
21834 Almost all modern systems use IEEE-754 floating point, and it is safe to
21835 assume IEEE-754 in most portable code these days.  For more information,
21836 please see David Goldberg's classic paper
21837 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21838 Scientist Should Know About Floating-Point Arithmetic}.
21840 @node Exiting Portably
21841 @section Exiting Portably
21842 @cindex exiting portably
21844 A C or C++ program can exit with status @var{N} by returning
21845 @var{N} from the @code{main} function.  Portable programs are supposed
21846 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21847 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21848 fail by exiting with status 1, and test programs that assume Posix can
21849 fail by exiting with status values from 1 through 255.  Programs on
21850 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21851 status when @code{main} returned nonzero, but ancient systems like these
21852 are no longer of practical concern.
21854 A program can also exit with status @var{N} by passing @var{N} to the
21855 @code{exit} function, and a program can fail by calling the @code{abort}
21856 function.  If a program is specialized to just some platforms, it can fail
21857 by calling functions specific to those platforms, e.g., @code{_exit}
21858 (Posix).  However, like other functions, an exit
21859 function should be declared, typically by including a header.  For
21860 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21861 either directly or via the default includes (@pxref{Default Includes}).
21863 A program can fail due to undefined behavior such as dereferencing a null
21864 pointer, but this is not recommended as undefined behavior allows an
21865 implementation to do whatever it pleases and this includes exiting
21866 successfully.
21869 @c ================================================== Manual Configuration
21871 @node Manual Configuration
21872 @chapter Manual Configuration
21874 A few kinds of features can't be guessed automatically by running test
21875 programs.  For example, the details of the object-file format, or
21876 special options that need to be passed to the compiler or linker.  You
21877 can check for such features using ad-hoc means, such as having
21878 @command{configure} check the output of the @code{uname} program, or
21879 looking for libraries that are unique to particular systems.  However,
21880 Autoconf provides a uniform method for handling unguessable features.
21882 @menu
21883 * Specifying Target Triplets::  Specifying target triplets
21884 * Canonicalizing::              Getting the canonical system type
21885 * Using System Type::           What to do with the system type
21886 @end menu
21888 @node Specifying Target Triplets
21889 @section Specifying target triplets
21890 @cindex System type
21891 @cindex Target triplet
21892 @c This node used to be named Specifying Names.  The @anchor allows old
21893 @c links to still work.
21894 @anchor{Specifying Names}
21896 Autoconf-generated
21897 @command{configure} scripts can make decisions based on a canonical name
21898 for the system type, or @dfn{target triplet}, which has the form:
21899 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21900 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21902 @command{configure} can usually guess the canonical name for the type of
21903 system it's running on.  To do so it runs a script called
21904 @command{config.guess}, which infers the name using the @code{uname}
21905 command or symbols predefined by the C preprocessor.
21907 Alternately, the user can specify the system type with command line
21908 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21909 necessary when
21910 cross-compiling.  In the most complex case of cross-compiling, three
21911 system types are involved.  The options to specify them are:
21913 @table @option
21914 @item --build=@var{build-type}
21915 the type of system on which the package is being configured and
21916 compiled.  It defaults to the result of running @command{config.guess}.
21917 Specifying a @var{build-type} that differs from @var{host-type} enables
21918 cross-compilation mode.
21920 @item --host=@var{host-type}
21921 the type of system on which the package runs.  By default it is the
21922 same as the build machine.  Specifying a @var{host-type} that differs
21923 from @var{build-type}, when @var{build-type} was also explicitly
21924 specified, enables cross-compilation mode.
21926 @item --target=@var{target-type}
21927 the type of system for which any compiler tools in the package
21928 produce code (rarely needed).  By default, it is the same as host.
21929 @end table
21931 If you mean to override the result of @command{config.guess}, use
21932 @option{--build}, not @option{--host}, since the latter enables
21933 cross-compilation.  For historical reasons,
21934 whenever you specify @option{--host},
21935 be sure to specify @option{--build} too; this will be fixed in the
21936 future.  So, to enter cross-compilation mode, use a command like this
21938 @example
21939 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21940 @end example
21942 @noindent
21943 Note that if you do not specify @option{--host}, @command{configure}
21944 fails if it can't run the code generated by the specified compiler.  For
21945 example, configuring as follows fails:
21947 @example
21948 ./configure CC=m68k-coff-gcc
21949 @end example
21951 When cross-compiling, @command{configure} will warn about any tools
21952 (compilers, linkers, assemblers) whose name is not prefixed with the
21953 host type.  This is an aid to users performing cross-compilation.
21954 Continuing the example above, if a cross-compiler named @command{cc} is
21955 used with a native @command{pkg-config}, then libraries found by
21956 @command{pkg-config} will likely cause subtle build failures; but using
21957 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21958 avoids any confusion.  Avoiding the warning is as simple as creating the
21959 correct symlinks naming the cross tools.
21961 @cindex @command{config.sub}
21962 @command{configure} recognizes short aliases for many system types; for
21963 example, @samp{decstation} can be used instead of
21964 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21965 @command{config.sub} to canonicalize system type aliases.
21967 This section deliberately omits the description of the obsolete
21968 interface; see @ref{Hosts and Cross-Compilation}.
21971 @node Canonicalizing
21972 @section Getting the Canonical System Type
21973 @cindex System type
21974 @cindex Canonical system type
21976 The following macros make the system type available to @command{configure}
21977 scripts.
21979 @ovindex build_alias
21980 @ovindex host_alias
21981 @ovindex target_alias
21983 The variables @samp{build_alias}, @samp{host_alias}, and
21984 @samp{target_alias} are always exactly the arguments of @option{--build},
21985 @option{--host}, and @option{--target}; in particular, they are left empty
21986 if the user did not use them, even if the corresponding
21987 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21988 variables anywhere.  These are the variables that should be used when in
21989 interaction with the user.
21991 If you need to recognize some special environments based on their system
21992 type, run the following macros to get canonical system names.  These
21993 variables are not set before the macro call.
21995 If you use these macros, you must distribute @command{config.guess} and
21996 @command{config.sub} along with your source code.  @xref{Output}, for
21997 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21998 to control in which directory @command{configure} looks for those scripts.
22001 @defmac AC_CANONICAL_BUILD
22002 @acindex{CANONICAL_BUILD}
22003 @ovindex build
22004 @ovindex build_cpu
22005 @ovindex build_vendor
22006 @ovindex build_os
22007 Compute the canonical build-system type variable, @code{build}, and its
22008 three individual parts @code{build_cpu}, @code{build_vendor}, and
22009 @code{build_os}.
22011 If @option{--build} was specified, then @code{build} is the
22012 canonicalization of @code{build_alias} by @command{config.sub},
22013 otherwise it is determined by the shell script @command{config.guess}.
22014 @end defmac
22016 @defmac AC_CANONICAL_HOST
22017 @acindex{CANONICAL_HOST}
22018 @ovindex host
22019 @ovindex host_cpu
22020 @ovindex host_vendor
22021 @ovindex host_os
22022 Compute the canonical host-system type variable, @code{host}, and its
22023 three individual parts @code{host_cpu}, @code{host_vendor}, and
22024 @code{host_os}.
22026 If @option{--host} was specified, then @code{host} is the
22027 canonicalization of @code{host_alias} by @command{config.sub},
22028 otherwise it defaults to @code{build}.
22029 @end defmac
22031 @defmac AC_CANONICAL_TARGET
22032 @acindex{CANONICAL_TARGET}
22033 @ovindex target
22034 @ovindex target_cpu
22035 @ovindex target_vendor
22036 @ovindex target_os
22037 Compute the canonical target-system type variable, @code{target}, and its
22038 three individual parts @code{target_cpu}, @code{target_vendor}, and
22039 @code{target_os}.
22041 If @option{--target} was specified, then @code{target} is the
22042 canonicalization of @code{target_alias} by @command{config.sub},
22043 otherwise it defaults to @code{host}.
22044 @end defmac
22046 Note that there can be artifacts due to the backward compatibility
22047 code.  @xref{Hosts and Cross-Compilation}, for more.
22049 @node Using System Type
22050 @section Using the System Type
22052 In @file{configure.ac} the system type is generally used by one or more
22053 @code{case} statements to select system-specifics.  Shell wildcards can
22054 be used to match a group of system types.
22056 For example, an extra assembler code object file could be chosen, giving
22057 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
22058 following would be used in a makefile to add the object to a
22059 program or library.
22061 @example
22062 AS_CASE([$host],
22063   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
22064   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
22065   [CYCLE_OBJ=""]
22067 AC_SUBST([CYCLE_OBJ])
22068 @end example
22070 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22071 to select variant source files, for example optimized code for some
22072 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
22073 so some runtime capability checks may be necessary too.
22075 @example
22076 case $host in
22077   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
22078   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
22079   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
22080 esac
22081 @end example
22083 The host system type can also be used to find cross-compilation tools
22084 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22086 The above examples all show @samp{$host}, since this is where the code
22087 is going to run.  Only rarely is it necessary to test @samp{$build}
22088 (which is where the build is being done).
22090 Whenever you're tempted to use @samp{$host} it's worth considering
22091 whether some sort of probe would be better.  New system types come along
22092 periodically or previously missing features are added.  Well-written
22093 probes can adapt themselves to such things, but hard-coded lists of
22094 names can't.  Here are some guidelines,
22096 @itemize @bullet
22097 @item
22098 Availability of libraries and library functions should always be checked
22099 by probing.
22100 @item
22101 Variant behavior of system calls is best identified with runtime tests
22102 if possible, but bug workarounds or obscure difficulties might have to
22103 be driven from @samp{$host}.
22104 @item
22105 Assembler code is inevitably highly CPU-specific and is best selected
22106 according to @samp{$host_cpu}.
22107 @item
22108 Assembler variations like underscore prefix on globals or ELF versus
22109 COFF type directives are however best determined by probing, perhaps
22110 even examining the compiler output.
22111 @end itemize
22113 @samp{$target} is for use by a package creating a compiler or similar.
22114 For ordinary packages it's meaningless and should not be used.  It
22115 indicates what the created compiler should generate code for, if it can
22116 cross-compile.  @samp{$target} generally selects various hard-coded CPU
22117 and system conventions, since usually the compiler or tools under
22118 construction themselves determine how the target works.
22121 @c ===================================================== Site Configuration.
22123 @node Site Configuration
22124 @chapter Site Configuration
22126 @command{configure} scripts support several kinds of local configuration
22127 decisions.  There are ways for users to specify where external software
22128 packages are, include or exclude optional features, install programs
22129 under modified names, and set default values for @command{configure}
22130 options.
22132 @menu
22133 * Help Formatting::             Customizing @samp{configure --help}
22134 * External Software::           Working with other optional software
22135 * Package Options::             Selecting optional features
22136 * Pretty Help Strings::         Formatting help string
22137 * Option Checking::             Controlling checking of @command{configure} options
22138 * Site Details::                Configuring site details
22139 * Transforming Names::          Changing program names when installing
22140 * Site Defaults::               Giving @command{configure} local defaults
22141 @end menu
22143 @node Help Formatting
22144 @section Controlling Help Output
22146 Users consult @samp{configure --help} to learn of configuration
22147 decisions specific to your package.  By default, @command{configure}
22148 breaks this output into sections for each type of option; within each
22149 section, help strings appear in the order @file{configure.ac} defines
22150 them:
22152 @example
22153 Optional Features:
22154   @dots{}
22155   --enable-bar            include bar
22157 Optional Packages:
22158   @dots{}
22159   --with-foo              use foo
22160 @end example
22162 @defmac AC_PRESERVE_HELP_ORDER
22163 @acindex{PRESERVE_HELP_ORDER}
22165 Request an alternate @option{--help} format, in which options of all
22166 types appear together, in the order defined.  Call this macro before any
22167 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22169 @example
22170 Optional Features and Packages:
22171   @dots{}
22172   --enable-bar            include bar
22173   --with-foo              use foo
22174 @end example
22176 @end defmac
22178 @node External Software
22179 @section Working With External Software
22180 @cindex External software
22182 Some packages require, or can optionally use, other software packages
22183 that are already installed.  The user can give @command{configure}
22184 command line options to specify which such external software to use.
22185 The options have one of these forms:
22187 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22188 @c awful.
22189 @example
22190 --with-@var{package}@r{[}=@var{arg}@r{]}
22191 --without-@var{package}
22192 @end example
22194 For example, @option{--with-gnu-ld} means work with the GNU linker
22195 instead of some other linker.  @option{--with-x} means work with The X
22196 Window System.
22198 The user can give an argument by following the package name with
22199 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22200 packages that are used by default; it says to @emph{not} use the
22201 package.  An argument that is neither @samp{yes} nor @samp{no} could
22202 include a name or number of a version of the other package, to specify
22203 more precisely which other package this program is supposed to work
22204 with.  If no argument is given, it defaults to @samp{yes}.
22205 @option{--without-@var{package}} is equivalent to
22206 @option{--with-@var{package}=no}.
22208 Normally @command{configure} scripts complain about
22209 @option{--with-@var{package}} options that they do not support.
22210 @xref{Option Checking}, for details, and for how to override the
22211 defaults.
22213 For each external software package that may be used, @file{configure.ac}
22214 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22215 user asked to use it.  Whether each package is used or not by default,
22216 and which arguments are valid, is up to you.
22218 @anchor{AC_ARG_WITH}
22219 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22220   @ovar{action-if-given}, @ovar{action-if-not-given})
22221 @acindex{ARG_WITH}
22222 If the user gave @command{configure} the option @option{--with-@var{package}}
22223 or @option{--without-@var{package}}, run shell commands
22224 @var{action-if-given}.  If neither option was given, run shell commands
22225 @var{action-if-not-given}.  The name @var{package} indicates another
22226 software package that this program should work with.  It should consist
22227 only of alphanumeric characters, dashes, plus signs, and dots.
22229 The option's argument is available to the shell commands
22230 @var{action-if-given} in the shell variable @code{withval}, which is
22231 actually just the value of the shell variable named
22232 @code{with_@var{package}}, with any non-alphanumeric characters in
22233 @var{package} changed into @samp{_}.  You may use that variable instead,
22234 if you wish.
22236 Note that @var{action-if-not-given} is not expanded until the point that
22237 @code{AC_ARG_WITH} was expanded.  If you need the value of
22238 @code{with_@var{package}} set to a default value by the time argument
22239 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22240 diversion (@pxref{m4_divert_text}) (if done as an argument to
22241 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22242 syntax error).
22244 The argument @var{help-string} is a description of the option that
22245 looks like this:
22246 @example
22247   --with-readline         support fancy command line editing
22248 @end example
22250 @noindent
22251 @var{help-string} may be more than one line long, if more detail is
22252 needed.  Just make sure the columns line up in @samp{configure
22253 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22254 proper leading whitespace is to format your @var{help-string} with the macro
22255 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22257 The following example shows how to use the @code{AC_ARG_WITH} macro in
22258 a common situation.  You want to let the user decide whether to enable
22259 support for an external library (e.g., the readline library); if the user
22260 specified neither @option{--with-readline} nor @option{--without-readline},
22261 you want to enable support for readline only if the library is available
22262 on the system.
22264 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22265 @example
22266 AC_ARG_WITH([readline],
22267   [AS_HELP_STRING([--with-readline],
22268     [support fancy command line editing @@<:@@default=check@@:>@@])],
22269   [],
22270   [: m4_divert_text([DEFAULTS], [with_readline=check])])
22272 LIBREADLINE=
22273 AS_IF([test "x$with_readline" != xno],
22274   [AC_CHECK_LIB([readline], [main],
22275     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22276      AC_DEFINE([HAVE_LIBREADLINE], [1],
22277                [Define if you have libreadline])
22278     ],
22279     [if test "x$with_readline" != xcheck; then
22280        AC_MSG_FAILURE(
22281          [--with-readline was given, but test for readline failed])
22282      fi
22283     ], -lncurses)])
22284 @end example
22286 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22287 possibility to enable support for the readline library, in case it is still
22288 experimental and not well tested, and is therefore disabled by default.
22290 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22291 @example
22292 AC_ARG_WITH([readline],
22293   [AS_HELP_STRING([--with-readline],
22294     [enable experimental support for readline])],
22295   [],
22296   [with_readline=no])
22298 LIBREADLINE=
22299 AS_IF([test "x$with_readline" != xno],
22300   [AC_CHECK_LIB([readline], [main],
22301     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22302      AC_DEFINE([HAVE_LIBREADLINE], [1],
22303                [Define if you have libreadline])
22304     ],
22305     [AC_MSG_FAILURE(
22306        [--with-readline was given, but test for readline failed])],
22307     [-lncurses])])
22308 @end example
22310 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22311 possibility to disable support for the readline library, given that it is
22312 an important feature and that it should be enabled by default.
22314 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22315 @example
22316 AC_ARG_WITH([readline],
22317   [AS_HELP_STRING([--without-readline],
22318     [disable support for readline])],
22319   [],
22320   [with_readline=yes])
22322 LIBREADLINE=
22323 AS_IF([test "x$with_readline" != xno],
22324   [AC_CHECK_LIB([readline], [main],
22325     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22326      AC_DEFINE([HAVE_LIBREADLINE], [1],
22327                [Define if you have libreadline])
22328     ],
22329     [AC_MSG_FAILURE(
22330        [readline test failed (--without-readline to disable)])],
22331     [-lncurses])])
22332 @end example
22334 These three examples can be easily adapted to the case where
22335 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22336 @ref{Package Options}).
22337 @end defmac
22339 @node Package Options
22340 @section Choosing Package Options
22341 @cindex Package options
22342 @cindex Options, package
22344 If a software package has optional compile-time features, the user can
22345 give @command{configure} command line options to specify whether to
22346 compile them.  The options have one of these forms:
22348 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22349 @c awful.
22350 @example
22351 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22352 --disable-@var{feature}
22353 @end example
22355 These options allow users to choose which optional features to build and
22356 install.  @option{--enable-@var{feature}} options should never make a
22357 feature behave differently or cause one feature to replace another.
22358 They should only cause parts of the program to be built rather than left
22359 out.
22361 The user can give an argument by following the feature name with
22362 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22363 that the feature @emph{not} be made available.  A feature with an
22364 argument looks like @option{--enable-debug=stabs}.  If no argument is
22365 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22366 equivalent to @option{--enable-@var{feature}=no}.
22368 Normally @command{configure} scripts complain about
22369 @option{--enable-@var{package}} options that they do not support.
22370 @xref{Option Checking}, for details, and for how to override the
22371 defaults.
22373 For each optional feature, @file{configure.ac} should call
22374 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22375 to include it.  Whether each feature is included or not by default, and
22376 which arguments are valid, is up to you.
22378 @anchor{AC_ARG_ENABLE}
22379 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22380   @ovar{action-if-given}, @ovar{action-if-not-given})
22381 @acindex{ARG_ENABLE}
22382 If the user gave @command{configure} the option
22383 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22384 shell commands @var{action-if-given}.  If neither option was given, run
22385 shell commands @var{action-if-not-given}.  The name @var{feature}
22386 indicates an optional user-level facility.  It should consist only of
22387 alphanumeric characters, dashes, plus signs, and dots.
22389 The option's argument is available to the shell commands
22390 @var{action-if-given} in the shell variable @code{enableval}, which is
22391 actually just the value of the shell variable named
22392 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22393 @var{feature} changed into @samp{_}.  You may use that variable instead,
22394 if you wish.  The @var{help-string} argument is like that of
22395 @code{AC_ARG_WITH} (@pxref{External Software}).
22397 Note that @var{action-if-not-given} is not expanded until the point that
22398 @code{AC_ARG_ENABLE} was expanded.  If you need the value of
22399 @code{enable_@var{feature}} set to a default value by the time argument
22400 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22401 diversion (@pxref{m4_divert_text}) (if done as an argument to
22402 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22403 syntax error).
22405 You should format your @var{help-string} with the macro
22406 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22408 See the examples suggested with the definition of @code{AC_ARG_WITH}
22409 (@pxref{External Software}) to get an idea of possible applications of
22410 @code{AC_ARG_ENABLE}.
22411 @end defmac
22413 @node Pretty Help Strings
22414 @section Making Your Help Strings Look Pretty
22415 @cindex Help strings
22417 Properly formatting the @samp{help strings} which are used in
22418 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22419 (@pxref{Package Options}) can be challenging.  Specifically, you want
22420 your own @samp{help strings} to line up in the appropriate columns of
22421 @samp{configure --help} just like the standard Autoconf @samp{help
22422 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22424 @anchor{AS_HELP_STRING}
22425 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22426   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22427 @asindex{HELP_STRING}
22429 Expands into a help string that looks pretty when the user executes
22430 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22431 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22432 Options}).  The following example makes this clearer.
22434 @example
22435 AC_ARG_WITH([foo],
22436   [AS_HELP_STRING([--with-foo],
22437      [use foo (default is no)])],
22438   [use_foo=$withval],
22439   [use_foo=no])
22440 @end example
22442 Then the last few lines of @samp{configure --help} appear like
22443 this:
22445 @example
22446 --enable and --with options recognized:
22447   --with-foo              use foo (default is no)
22448 @end example
22450 Macro expansion is performed on the first argument.  However, the second
22451 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22452 list of text to be reformatted, and is not subject to macro expansion.
22453 Since it is not expanded, it should not be double quoted.
22454 @xref{Autoconf Language}, for a more detailed explanation.
22456 The @code{AS_HELP_STRING} macro is particularly helpful when the
22457 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22458 arguments, as shown in the following example.  Be aware that
22459 @var{left-hand-side} may not expand to unbalanced quotes,
22460 although quadrigraphs can be used.
22462 @example
22463 AC_DEFUN([MY_ARG_WITH],
22464   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22465      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22466                      [use $1 (default is $2)])],
22467      [use_[]$1=$withval],
22468      [use_[]$1=$2])])
22469 MY_ARG_WITH([a_b], [no])
22470 @end example
22471 @noindent
22472 Here, the last few lines of @samp{configure --help} will include:
22474 @example
22475 --enable and --with options recognized:
22476   --with-a-b              use a_b (default is no)
22477 @end example
22479 The parameters @var{indent-column} and @var{wrap-column} were introduced
22480 in Autoconf 2.62.  Generally, they should not be specified; they exist
22481 for fine-tuning of the wrapping.
22482 @example
22483 AS_HELP_STRING([--option], [description of option])
22484 @result{}  --option                description of option
22485 AS_HELP_STRING([--option], [description of option], [15], [30])
22486 @result{}  --option     description of
22487 @result{}               option
22488 @end example
22489 @end defmac
22492 @node Option Checking
22493 @section Controlling Checking of @command{configure} Options
22494 @cindex Options, Package
22496 The @command{configure} script checks its command-line options against a
22497 list of known options, like @option{--help} or @option{--config-cache}.
22498 An unknown option ordinarily indicates a mistake by the user and
22499 @command{configure} halts with an error.  However, by default unknown
22500 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22501 options elicit only a warning, to support configuring entire source
22502 trees.
22504 Source trees often contain multiple packages with a top-level
22505 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22506 (@pxref{Subdirectories}).  Because the packages generally support
22507 different @option{--with-@var{package}} and
22508 @option{--enable-@var{feature}} options, the GNU Coding
22509 Standards say they must accept unrecognized options without halting.
22510 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22511 automatically disables the warnings.
22513 This default behavior may be modified in two ways.  First, the installer
22514 can invoke @code{configure --disable-option-checking} to disable
22515 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22516 options to turn them into fatal errors, respectively.  Second, the
22517 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22519 @defmac AC_DISABLE_OPTION_CHECKING
22520 @acindex{DISABLE_OPTION_CHECKING}
22522 By default, disable warnings related to any unrecognized
22523 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22524 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22526 The installer can override this behavior by passing
22527 @option{--enable-option-checking} (enable warnings) or
22528 @option{--enable-option-checking=fatal} (enable errors) to
22529 @command{configure}.
22530 @end defmac
22533 @node Site Details
22534 @section Configuring Site Details
22535 @cindex Site details
22537 Some software packages require complex site-specific information.  Some
22538 examples are host names to use for certain services, company names, and
22539 email addresses to contact.  Since some configuration scripts generated
22540 by Metaconfig ask for such information interactively, people sometimes
22541 wonder how to get that information in Autoconf-generated configuration
22542 scripts, which aren't interactive.
22544 Such site configuration information should be put in a file that is
22545 edited @emph{only by users}, not by programs.  The location of the file
22546 can either be based on the @code{prefix} variable, or be a standard
22547 location such as the user's home directory.  It could even be specified
22548 by an environment variable.  The programs should examine that file at
22549 runtime, rather than at compile time.  Runtime configuration is more
22550 convenient for users and makes the configuration process simpler than
22551 getting the information while configuring.  @xref{Directory Variables, ,
22552 Variables for Installation Directories, standards, The GNU Coding
22553 Standards}, for more information on where to put data files.
22555 @node Transforming Names
22556 @section Transforming Program Names When Installing
22557 @cindex Transforming program names
22558 @cindex Program names, transforming
22560 Autoconf supports changing the names of programs when installing them.
22561 In order to use these transformations, @file{configure.ac} must call the
22562 macro @code{AC_ARG_PROGRAM}.
22564 @defmac AC_ARG_PROGRAM
22565 @acindex{ARG_PROGRAM}
22566 @ovindex program_transform_name
22567 Place in output variable @code{program_transform_name} a sequence of
22568 @code{sed} commands for changing the names of installed programs.
22570 If any of the options described below are given to @command{configure},
22571 program names are transformed accordingly.  Otherwise, if
22572 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22573 is given, the target type followed by a dash is used as a prefix.
22574 Otherwise, no program name transformation is done.
22575 @end defmac
22577 @menu
22578 * Transformation Options::      @command{configure} options to transform names
22579 * Transformation Examples::     Sample uses of transforming names
22580 * Transformation Rules::        Makefile uses of transforming names
22581 @end menu
22583 @node Transformation Options
22584 @subsection Transformation Options
22586 You can specify name transformations by giving @command{configure} these
22587 command line options:
22589 @table @option
22590 @item --program-prefix=@var{prefix}
22591 prepend @var{prefix} to the names;
22593 @item --program-suffix=@var{suffix}
22594 append @var{suffix} to the names;
22596 @item --program-transform-name=@var{expression}
22597 perform @code{sed} substitution @var{expression} on the names.
22598 @end table
22600 @node Transformation Examples
22601 @subsection Transformation Examples
22603 These transformations are useful with programs that can be part of a
22604 cross-compilation development environment.  For example, a
22605 cross-assembler running on a Sun 4 configured with
22606 @option{--target=i960-vxworks} is normally installed as
22607 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22608 with a native Sun 4 assembler.
22610 You can force a program name to begin with @file{g}, if you don't want
22611 GNU programs installed on your system to shadow other programs with
22612 the same name.  For example, if you configure GNU @code{diff} with
22613 @option{--program-prefix=g}, then when you run @samp{make install} it is
22614 installed as @file{/usr/local/bin/gdiff}.
22616 As a more sophisticated example, you could use
22618 @example
22619 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22620 @end example
22621 @noindent
22623 to prepend @samp{g} to most of the program names in a source tree,
22624 excepting those like @code{gdb} that already have one and those like
22625 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22626 assuming that you have a source tree containing those programs that is
22627 set up to use this feature.)
22629 One way to install multiple versions of some programs simultaneously is
22630 to append a version number to the name of one or both.  For example, if
22631 you want to keep Autoconf version 1 around for awhile, you can configure
22632 Autoconf version 2 using @option{--program-suffix=2} to install the
22633 programs as @file{/usr/local/bin/autoconf2},
22634 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22635 that only the binaries are renamed, therefore you'd have problems with
22636 the library files which might overlap.
22638 @node Transformation Rules
22639 @subsection Transformation Rules
22641 Here is how to use the variable @code{program_transform_name} in a
22642 @file{Makefile.in}:
22644 @example
22645 PROGRAMS = cp ls rm
22646 transform = @@program_transform_name@@
22647 install:
22648         for p in $(PROGRAMS); do \
22649           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22650                                               sed '$(transform)'`; \
22651         done
22653 uninstall:
22654         for p in $(PROGRAMS); do \
22655           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22656 @c $$ restore font-lock
22657         done
22658 @end example
22660 It is guaranteed that @code{program_transform_name} is never empty, and
22661 that there are no useless separators.  Therefore you may safely embed
22662 @code{program_transform_name} within a sed program using @samp{;}:
22664 @example
22665 transform = @@program_transform_name@@
22666 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22667 @end example
22669 Whether to do the transformations on documentation files (Texinfo or
22670 @code{man}) is a tricky question; there seems to be no perfect answer,
22671 due to the several reasons for name transforming.  Documentation is not
22672 usually particular to a specific architecture, and Texinfo files do not
22673 conflict with system documentation.  But they might conflict with
22674 earlier versions of the same files, and @code{man} pages sometimes do
22675 conflict with system documentation.  As a compromise, it is probably
22676 best to do name transformations on @code{man} pages but not on Texinfo
22677 manuals.
22679 @node Site Defaults
22680 @section Setting Site Defaults
22681 @cindex Site defaults
22682 @cindex config.site
22684 Autoconf-generated @command{configure} scripts allow your site to provide
22685 default values for some configuration values.  You do this by creating
22686 site- and system-wide initialization files.
22688 @evindex CONFIG_SITE
22689 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22690 uses its value as the name of a shell script to read; it is recommended
22691 that this be an absolute file name.  Otherwise, it
22692 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22693 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22694 settings in machine-specific files override those in machine-independent
22695 ones in case of conflict.
22697 Site files can be arbitrary shell scripts, but only certain kinds of
22698 code are really appropriate to be in them.  Because @command{configure}
22699 reads any cache file after it has read any site files, a site file can
22700 define a default cache file to be shared between all Autoconf-generated
22701 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22702 you set a default cache file in a site file, it is a good idea to also
22703 set the output variable @code{CC} in that site file, because the cache
22704 file is only valid for a particular compiler, but many systems have
22705 several available.
22707 You can examine or override the value set by a command line option to
22708 @command{configure} in a site file; options set shell variables that have
22709 the same names as the options, with any dashes turned into underscores.
22710 The exceptions are that @option{--without-} and @option{--disable-} options
22711 are like giving the corresponding @option{--with-} or @option{--enable-}
22712 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22713 sets the variable @code{cache_file} to the value @samp{localcache};
22714 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22715 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22716 variable @code{prefix} to the value @samp{/usr}; etc.
22718 Site files are also good places to set default values for other output
22719 variables, such as @code{CFLAGS}, if you need to give them non-default
22720 values: anything you would normally do, repetitively, on the command
22721 line.  If you use non-default values for @var{prefix} or
22722 @var{exec_prefix} (wherever you locate the site file), you can set them
22723 in the site file if you specify it with the @code{CONFIG_SITE}
22724 environment variable.
22726 You can set some cache values in the site file itself.  Doing this is
22727 useful if you are cross-compiling, where it is impossible to check features
22728 that require running a test program.  You could ``prime the cache'' by
22729 setting those values correctly for that system in
22730 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22731 variables you need to set, see the documentation of the respective
22732 Autoconf macro.  If the variables or their semantics are undocumented,
22733 you may need to look for shell variables with @samp{_cv_} in their names
22734 in the affected @command{configure} scripts, or in the Autoconf M4
22735 source code for those macros; but in that case, their name or semantics
22736 may change in a future Autoconf version.
22738 The cache file is careful to not override any variables set in the site
22739 files.  Similarly, you should not override command-line options in the
22740 site files.  Your code should check that variables such as @code{prefix}
22741 and @code{cache_file} have their default values (as set near the top of
22742 @command{configure}) before changing them.
22744 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22745 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22746 file (if @code{CONFIG_SITE} is not set to a different file).
22748 @example
22749 # /usr/share/local/gnu/share/config.site for configure
22751 # Change some defaults.
22752 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22753 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22754 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22755 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22756 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
22758 # Give Autoconf 2.x generated configure scripts a shared default
22759 # cache file for feature test results, architecture-specific.
22760 if test "$cache_file" = /dev/null; then
22761   cache_file="$prefix/var/config.cache"
22762   # A cache file is only valid for one C compiler.
22763   CC=gcc
22765 @end example
22767 @c Leave this use of "File system" rendered as one word, but
22768 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22769 @cindex File@/system Hierarchy Standard
22770 @cindex FHS
22772 Another use of @file{config.site} is for priming the directory variables
22773 @c "File system", but slightly obfuscated, as above.
22774 in a manner consistent with the File@/system Hierarchy Standard
22775 (FHS).  Once the following file is installed at
22776 @file{/usr/share/config.site}, a user can execute simply
22777 @code{./configure --prefix=/usr} to get all the directories chosen in
22778 the locations recommended by FHS.
22780 @example
22781 # /usr/share/config.site for FHS defaults when installing below /usr,
22782 # and the respective settings were not changed on the command line.
22783 if test "$prefix" = /usr; then
22784   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22785   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22786   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22788 @end example
22790 @cindex @file{lib64}
22791 @cindex 64-bit libraries
22792 Likewise, on platforms where 64-bit libraries are built by default, then
22793 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22794 it is appropriate to install @file{/usr/local/@/share/config.site}:
22796 @example
22797 # /usr/local/share/config.site for platforms that prefer
22798 # the directory /usr/local/lib64 over /usr/local/lib.
22799 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22800 @end example
22803 @c ============================================== Running configure Scripts.
22805 @node Running configure Scripts
22806 @chapter Running @command{configure} Scripts
22807 @cindex @command{configure}
22809 Below are instructions on how to configure a package that uses a
22810 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22811 file in the package.  A plain-text version of @file{INSTALL} which you
22812 may use comes with Autoconf.
22814 @menu
22815 * Basic Installation::          Instructions for typical cases
22816 * Compilers and Options::       Selecting compilers and optimization
22817 * Multiple Architectures::      Compiling for multiple architectures at once
22818 * Installation Names::          Installing in different directories
22819 * Optional Features::           Selecting optional features
22820 * Particular Systems::          Particular systems
22821 * System Type::                 Specifying the system type
22822 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22823 * Defining Variables::          Specifying the compiler etc.
22824 * configure Invocation::        Changing how @command{configure} runs
22825 @end menu
22827 @set autoconf
22828 @include install.texi
22831 @c ============================================== config.status Invocation
22833 @node config.status Invocation
22834 @chapter config.status Invocation
22835 @cindex @command{config.status}
22837 The @command{configure} script creates a file named @file{config.status},
22838 which actually configures, @dfn{instantiates}, the template files.  It
22839 also records the configuration options that were specified when the
22840 package was last configured in case reconfiguring is needed.
22842 Synopsis:
22843 @example
22844 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22845 @end example
22847 It configures each @var{tag}; if none are specified, all the templates
22848 are instantiated.  A @var{tag} refers to a file or other tag associated
22849 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22850 macro (@pxref{Configuration Actions}).  The files must be specified
22851 without their dependencies, as in
22853 @example
22854 ./config.status foobar
22855 @end example
22857 @noindent
22860 @example
22861 ./config.status foobar:foo.in:bar.in
22862 @end example
22864 The supported options are:
22866 @table @option
22867 @item --help
22868 @itemx -h
22869 Print a summary of the command line options, the list of the template
22870 files, and exit.
22872 @item --version
22873 @itemx -V
22874 Print the version number of Autoconf and the configuration settings,
22875 and exit.
22877 @item --config
22878 Print the configuration settings in reusable way, quoted for the shell,
22879 and exit.  For example, for a debugging build that otherwise reuses the
22880 configuration from a different build directory @var{build-dir} of a
22881 package in @var{src-dir}, you could use the following:
22883 @example
22884 args=`@var{build-dir}/config.status --config`
22885 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22886 @end example
22888 @noindent
22889 Note that it may be necessary to override a @option{--srcdir} setting
22890 that was saved in the configuration, if the arguments are used in a
22891 different build directory.
22893 @item --silent
22894 @itemx --quiet
22895 @itemx -q
22896 Do not print progress messages.
22898 @item --debug
22899 @itemx -d
22900 Don't remove the temporary files.
22902 @item --file=@var{file}[:@var{template}]
22903 Require that @var{file} be instantiated as if
22904 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22905 @var{file} and @var{template} may be @samp{-} in which case the standard
22906 output and/or standard input, respectively, is used.  If a
22907 @var{template} file name is relative, it is first looked for in the build
22908 tree, and then in the source tree.  @xref{Configuration Actions}, for
22909 more details.
22911 This option and the following ones provide one way for separately
22912 distributed packages to share the values computed by @command{configure}.
22913 Doing so can be useful if some of the packages need a superset of the
22914 features that one of them, perhaps a common library, does.  These
22915 options allow a @file{config.status} file to create files other than the
22916 ones that its @file{configure.ac} specifies, so it can be used for a
22917 different package, or for extracting a subset of values.  For example,
22919 @example
22920 echo '@@CC@@' | ./config.status --file=-
22921 @end example
22923 @noindent
22924 provides the value of @code{@@CC@@} on standard output.
22926 @item --header=@var{file}[:@var{template}]
22927 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22929 @item --recheck
22930 Ask @file{config.status} to update itself and exit (no instantiation).
22931 This option is useful if you change @command{configure}, so that the
22932 results of some tests might be different from the previous run.  The
22933 @option{--recheck} option reruns @command{configure} with the same arguments
22934 you used before, plus the @option{--no-create} option, which prevents
22935 @command{configure} from running @file{config.status} and creating
22936 @file{Makefile} and other files, and the @option{--no-recursion} option,
22937 which prevents @command{configure} from running other @command{configure}
22938 scripts in subdirectories.  (This is so other Make rules can
22939 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22940 for an example).
22941 @end table
22943 @file{config.status} checks several optional environment variables that
22944 can alter its behavior:
22946 @anchor{CONFIG_SHELL}
22947 @defvar CONFIG_SHELL
22948 @evindex CONFIG_SHELL
22949 The shell with which to run @command{configure}.  It must be
22950 Bourne-compatible, and the absolute name of the shell should be passed.
22951 The default is a shell that supports @code{LINENO} if available, and
22952 @file{/bin/sh} otherwise.
22953 @end defvar
22955 @defvar CONFIG_STATUS
22956 @evindex CONFIG_STATUS
22957 The file name to use for the shell script that records the
22958 configuration.  The default is @file{./config.status}.  This variable is
22959 useful when one package uses parts of another and the @command{configure}
22960 scripts shouldn't be merged because they are maintained separately.
22961 @end defvar
22963 You can use @file{./config.status} in your makefiles.  For example, in
22964 the dependencies given above (@pxref{Automatic Remaking}),
22965 @file{config.status} is run twice when @file{configure.ac} has changed.
22966 If that bothers you, you can make each run only regenerate the files for
22967 that rule:
22968 @example
22969 @group
22970 config.h: stamp-h
22971 stamp-h: config.h.in config.status
22972         ./config.status config.h
22973         echo > stamp-h
22975 Makefile: Makefile.in config.status
22976         ./config.status Makefile
22977 @end group
22978 @end example
22980 The calling convention of @file{config.status} has changed; see
22981 @ref{Obsolete config.status Use}, for details.
22984 @c =================================================== Obsolete Constructs
22986 @node Obsolete Constructs
22987 @chapter Obsolete Constructs
22988 @cindex Obsolete constructs
22990 Autoconf changes, and throughout the years some constructs have been
22991 obsoleted.  Most of the changes involve the macros, but in some cases
22992 the tools themselves, or even some concepts, are now considered
22993 obsolete.
22995 You may completely skip this chapter if you are new to Autoconf.  Its
22996 intention is mainly to help maintainers updating their packages by
22997 understanding how to move to more modern constructs.
22999 @menu
23000 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
23001 * acconfig Header::             Additional entries in @file{config.h.in}
23002 * autoupdate Invocation::       Automatic update of @file{configure.ac}
23003 * Obsolete Macros::             Backward compatibility macros
23004 * Autoconf 1::                  Tips for upgrading your files
23005 * Autoconf 2.13::               Some fresher tips
23006 @end menu
23008 @node Obsolete config.status Use
23009 @section Obsolete @file{config.status} Invocation
23011 @file{config.status} now supports arguments to specify the files to
23012 instantiate; see @ref{config.status Invocation}, for more details.
23013 Before, environment variables had to be used.
23015 @defvar CONFIG_COMMANDS
23016 @evindex CONFIG_COMMANDS
23017 The tags of the commands to execute.  The default is the arguments given
23018 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
23019 @file{configure.ac}.
23020 @end defvar
23022 @defvar CONFIG_FILES
23023 @evindex CONFIG_FILES
23024 The files in which to perform @samp{@@@var{variable}@@} substitutions.
23025 The default is the arguments given to @code{AC_OUTPUT} and
23026 @code{AC_CONFIG_FILES} in @file{configure.ac}.
23027 @end defvar
23029 @defvar CONFIG_HEADERS
23030 @evindex CONFIG_HEADERS
23031 The files in which to substitute C @code{#define} statements.  The
23032 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
23033 macro was not called, @file{config.status} ignores this variable.
23034 @end defvar
23036 @defvar CONFIG_LINKS
23037 @evindex CONFIG_LINKS
23038 The symbolic links to establish.  The default is the arguments given to
23039 @code{AC_CONFIG_LINKS}; if that macro was not called,
23040 @file{config.status} ignores this variable.
23041 @end defvar
23043 In @ref{config.status Invocation}, using this old interface, the example
23044 would be:
23046 @example
23047 @group
23048 config.h: stamp-h
23049 stamp-h: config.h.in config.status
23050         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
23051           CONFIG_HEADERS=config.h ./config.status
23052         echo > stamp-h
23054 Makefile: Makefile.in config.status
23055         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23056           CONFIG_FILES=Makefile ./config.status
23057 @end group
23058 @end example
23060 @noindent
23061 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23062 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
23063 for @code{CONFIG_COMMANDS}, etc.)
23066 @node acconfig Header
23067 @section @file{acconfig.h}
23069 @cindex @file{acconfig.h}
23070 @cindex @file{config.h.top}
23071 @cindex @file{config.h.bot}
23073 In order to produce @file{config.h.in}, @command{autoheader} needs to
23074 build or to find templates for each symbol.  Modern releases of Autoconf
23075 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23076 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23077 list of needed templates.  @command{autoheader} copied comments and
23078 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23079 the current directory, if present.  This file used to be mandatory if
23080 you @code{AC_DEFINE} any additional symbols.
23082 Modern releases of Autoconf also provide @code{AH_TOP} and
23083 @code{AH_BOTTOM} if you need to prepend/append some information to
23084 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
23085 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23086 @command{autoheader} copies the lines before the line containing
23087 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
23088 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23089 @command{autoheader} copies the lines after that line to the end of the
23090 file it generates.  Either or both of those strings may be omitted.  An
23091 even older alternate way to produce the same effect in ancient versions
23092 of Autoconf is to create the files @file{@var{file}.top} (typically
23093 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23094 directory.  If they exist, @command{autoheader} copies them to the
23095 beginning and end, respectively, of its output.
23097 In former versions of Autoconf, the files used in preparing a software
23098 package for distribution were:
23099 @example
23100 @group
23101 configure.ac --.   .------> autoconf* -----> configure
23102                +---+
23103 [aclocal.m4] --+   `---.
23104 [acsite.m4] ---'       |
23105                        +--> [autoheader*] -> [config.h.in]
23106 [acconfig.h] ----.     |
23107                  +-----'
23108 [config.h.top] --+
23109 [config.h.bot] --'
23110 @end group
23111 @end example
23113 Using only the @code{AH_} macros, @file{configure.ac} should be
23114 self-contained, and should not depend upon @file{acconfig.h} etc.
23117 @node autoupdate Invocation
23118 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23119 @cindex @command{autoupdate}
23121 The @command{autoupdate} program updates a @file{configure.ac} file that
23122 calls Autoconf macros by their old names to use the current macro names.
23123 In version 2 of Autoconf, most of the macros were renamed to use a more
23124 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
23125 description of the new scheme.  Although the old names still work
23126 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23127 new names), you can make your @file{configure.ac} files more readable
23128 and make it easier to use the current Autoconf documentation if you
23129 update them to use the new macro names.
23131 @evindex SIMPLE_BACKUP_SUFFIX
23132 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23133 backing up the original version with the suffix @file{~} (or the value
23134 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23135 set).  If you give @command{autoupdate} an argument, it reads that file
23136 instead of @file{configure.ac} and writes the updated file to the
23137 standard output.
23139 @noindent
23140 @command{autoupdate} accepts the following options:
23142 @table @option
23143 @item --help
23144 @itemx -h
23145 Print a summary of the command line options and exit.
23147 @item --version
23148 @itemx -V
23149 Print the version number of Autoconf and exit.
23151 @item --verbose
23152 @itemx -v
23153 Report processing steps.
23155 @item --debug
23156 @itemx -d
23157 Don't remove the temporary files.
23159 @item --force
23160 @itemx -f
23161 Force the update even if the file has not changed.  Disregard the cache.
23163 @item --include=@var{dir}
23164 @itemx -I @var{dir}
23165 Also look for input files in @var{dir}.  Multiple invocations accumulate.
23166 Directories are browsed from last to first.
23168 @item --prepend-include=@var{dir}
23169 @itemx -B @var{dir}
23170 Prepend directory @var{dir} to the search path.  This is used to include
23171 the language-specific files before any third-party macros.
23172 @end table
23174 @node Obsolete Macros
23175 @section Obsolete Macros
23177 Several macros are obsoleted in Autoconf, for various reasons (typically
23178 they failed to quote properly, couldn't be extended for more recent
23179 issues, etc.).  They are still supported, but deprecated: their use
23180 should be avoided.
23182 During the jump from Autoconf version 1 to version 2, most of the
23183 macros were renamed to use a more uniform and descriptive naming scheme,
23184 but their signature did not change.  @xref{Macro Names}, for a
23185 description of the new naming scheme.  Below, if there is just the mapping
23186 from old names to new names for these macros, the reader is invited to
23187 refer to the definition of the new macro for the signature and the
23188 description.
23190 @defmac AC_AIX
23191 @acindex{AIX}
23192 @cvindex _ALL_SOURCE
23193 This macro is a platform-specific subset of
23194 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23195 @end defmac
23197 @defmac AC_ALLOCA
23198 @acindex{ALLOCA}
23199 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23200 @end defmac
23202 @defmac AC_ARG_ARRAY
23203 @acindex{ARG_ARRAY}
23204 Removed because of limited usefulness.
23205 @end defmac
23207 @defmac AC_C_CROSS
23208 @acindex{C_CROSS}
23209 This macro is obsolete; it does nothing.
23210 @end defmac
23212 @defmac AC_C_LONG_DOUBLE
23213 @acindex{C_LONG_DOUBLE}
23214 @cvindex HAVE_LONG_DOUBLE
23215 If the C compiler supports a working @code{long double} type with more
23216 range or precision than the @code{double} type, define
23217 @code{HAVE_LONG_DOUBLE}.
23219 You should use @code{AC_TYPE_LONG_DOUBLE} or
23220 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23221 @end defmac
23223 @defmac AC_CANONICAL_SYSTEM
23224 @acindex{CANONICAL_SYSTEM}
23225 Determine the system type and set output variables to the names of the
23226 canonical system types.  @xref{Canonicalizing}, for details about the
23227 variables this macro sets.
23229 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23230 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23231 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23232 other macros (@pxref{Canonicalizing}).
23233 @end defmac
23235 @defmac AC_CHAR_UNSIGNED
23236 @acindex{CHAR_UNSIGNED}
23237 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23238 @end defmac
23240 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23241 @acindex{CHECK_TYPE}
23242 Autoconf, up to 2.13, used to provide this version of
23243 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23244 it is a member of the @code{CHECK} clan, it does
23245 more than just checking.  Secondly, missing types are defined
23246 using @code{#define}, not @code{typedef}, and this can lead to
23247 problems in the case of pointer types.
23249 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23250 @ref{Generic Types}, for the description of the current macro.
23252 If the type @var{type} is not defined, define it to be the C (or C++)
23253 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23255 This macro is equivalent to:
23257 @example
23258 AC_CHECK_TYPE([@var{type}], [],
23259   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23260      [Define to `@var{default}'
23261       if <sys/types.h> does not define.])])
23262 @end example
23264 In order to keep backward compatibility, the two versions of
23265 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23267 @enumerate
23268 @item
23269 If there are three or four arguments, the modern version is used.
23271 @item
23272 If the second argument appears to be a C or C++ type, then the
23273 obsolete version is used.  This happens if the argument is a C or C++
23274 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23275 followed by one of @samp{[(* } and then by a string of zero or more
23276 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23278 @item
23279 If the second argument is spelled with the alphabet of valid C and C++
23280 types, the user is warned and the modern version is used.
23282 @item
23283 Otherwise, the modern version is used.
23284 @end enumerate
23286 @noindent
23287 You are encouraged either to use a valid builtin type, or to use the
23288 equivalent modern code (see above), or better yet, to use
23289 @code{AC_CHECK_TYPES} together with
23291 @example
23292 #ifndef HAVE_LOFF_T
23293 typedef loff_t off_t;
23294 #endif
23295 @end example
23296 @end defmac
23297 @c end of AC_CHECK_TYPE
23299 @defmac AC_CHECKING (@var{feature-description})
23300 @acindex{CHECKING}
23301 Same as
23303 @example
23304 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23305 @end example
23307 @noindent
23308 @xref{AC_MSG_NOTICE}.
23309 @end defmac
23311 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23312   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23313 @acindex{COMPILE_CHECK}
23314 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23315 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23316 addition that it prints @samp{checking for @var{echo-text}} to the
23317 standard output first, if @var{echo-text} is non-empty.  Use
23318 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23319 messages (@pxref{Printing Messages}).
23320 @end defmac
23322 @defmac AC_CONST
23323 @acindex{CONST}
23324 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23325 @end defmac
23327 @defmac AC_CROSS_CHECK
23328 @acindex{CROSS_CHECK}
23329 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23330 @code{:-)}.
23331 @end defmac
23333 @defmac AC_CYGWIN
23334 @acindex{CYGWIN}
23335 @evindex CYGWIN
23336 Check for the Cygwin environment in which case the shell variable
23337 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23338 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23339 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23341 @example
23342 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23343 case $host_os in
23344   *cygwin* ) CYGWIN=yes;;
23345          * ) CYGWIN=no;;
23346 esac
23347 @end example
23349 Beware that the variable @env{CYGWIN} has a special meaning when
23350 running Cygwin, and should not be changed.  That's yet another reason
23351 not to use this macro.
23352 @end defmac
23354 @defmac AC_DECL_SYS_SIGLIST
23355 @acindex{DECL_SYS_SIGLIST}
23356 @cvindex SYS_SIGLIST_DECLARED
23357 Same as:
23359 @example
23360 AC_CHECK_DECLS([sys_siglist], [], [],
23361 [#include <signal.h>
23362 /* NetBSD declares sys_siglist in unistd.h.  */
23363 #ifdef HAVE_UNISTD_H
23364 # include <unistd.h>
23365 #endif
23367 @end example
23369 @noindent
23370 @xref{AC_CHECK_DECLS}.
23371 @end defmac
23373 @defmac AC_DECL_YYTEXT
23374 @acindex{DECL_YYTEXT}
23375 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23376 @end defmac
23378 @defmac AC_DIR_HEADER
23379 @acindex{DIR_HEADER}
23380 @cvindex DIRENT
23381 @cvindex SYSNDIR
23382 @cvindex SYSDIR
23383 @cvindex NDIR
23384 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23385 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23386 (@pxref{AC_HEADER_DIRENT}),
23387 but defines a different set of C preprocessor macros to indicate which
23388 header file is found:
23390 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23391 @item Header            @tab Old Symbol     @tab New Symbol
23392 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23393 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23394 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23395 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23396 @end multitable
23397 @end defmac
23399 @defmac AC_DYNIX_SEQ
23400 @acindex{DYNIX_SEQ}
23401 If on DYNIX/ptx, add @option{-lseq} to output variable
23402 @code{LIBS}.  This macro used to be defined as
23404 @example
23405 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23406 @end example
23408 @noindent
23409 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23410 @end defmac
23412 @defmac AC_EXEEXT
23413 @acindex{EXEEXT}
23414 @ovindex EXEEXT
23415 Defined the output variable @code{EXEEXT} based on the output of the
23416 compiler, which is now done automatically.  Typically set to empty
23417 string if Posix and @samp{.exe} if a DOS variant.
23418 @end defmac
23420 @defmac AC_EMXOS2
23421 @acindex{EMXOS2}
23422 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23423 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23424 check the nature of the host is using @code{AC_CANONICAL_HOST}
23425 (@pxref{Canonicalizing}).
23426 @end defmac
23428 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23429   @ovar{action-if-not-given})
23430 @acindex{ENABLE}
23431 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23432 support providing a help string (@pxref{AC_ARG_ENABLE}).
23433 @end defmac
23435 @defmac AC_ERROR
23436 @acindex{ERROR}
23437 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23438 @end defmac
23440 @defmac AC_FIND_X
23441 @acindex{FIND_X}
23442 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23443 @end defmac
23445 @defmac AC_FIND_XTRA
23446 @acindex{FIND_XTRA}
23447 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23448 @end defmac
23450 @defmac AC_FOREACH
23451 @acindex{FOREACH}
23452 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23453 @end defmac
23455 @defmac AC_FUNC_CHECK
23456 @acindex{FUNC_CHECK}
23457 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23458 @end defmac
23460 @anchor{AC_FUNC_SETVBUF_REVERSED}
23461 @defmac AC_FUNC_SETVBUF_REVERSED
23462 @acindex{FUNC_SETVBUF_REVERSED}
23463 @cvindex SETVBUF_REVERSED
23464 @c @fuindex setvbuf
23465 @prindex @code{setvbuf}
23466 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23467 the buffering type as its second argument and the buffer pointer as the
23468 third, instead of the other way around, and defined
23469 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23470 were those based on SVR2, which became obsolete in 1987, and the macro
23471 is no longer needed.
23472 @end defmac
23474 @defmac AC_FUNC_WAIT3
23475 @acindex{FUNC_WAIT3}
23476 @cvindex HAVE_WAIT3
23477 @c @fuindex wait3
23478 @prindex @code{wait3}
23479 If @code{wait3} is found and fills in the contents of its third argument
23480 (a @samp{struct rusage *}), which HP-UX does not do, define
23481 @code{HAVE_WAIT3}.
23483 These days portable programs should use @code{waitpid}, not
23484 @code{wait3}, as @code{wait3} has been removed from Posix.
23485 @end defmac
23487 @defmac AC_GCC_TRADITIONAL
23488 @acindex{GCC_TRADITIONAL}
23489 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23490 @end defmac
23492 @defmac AC_GETGROUPS_T
23493 @acindex{GETGROUPS_T}
23494 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23495 @end defmac
23497 @defmac AC_GETLOADAVG
23498 @acindex{GETLOADAVG}
23499 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23500 @end defmac
23502 @defmac AC_GNU_SOURCE
23503 @acindex{GNU_SOURCE}
23504 @cvindex _GNU_SOURCE
23505 This macro is a platform-specific subset of
23506 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23507 @end defmac
23509 @defmac AC_HAVE_FUNCS
23510 @acindex{HAVE_FUNCS}
23511 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23512 @end defmac
23514 @defmac AC_HAVE_HEADERS
23515 @acindex{HAVE_HEADERS}
23516 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23517 @end defmac
23519 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23520   @ovar{action-if-not-found}, @ovar{other-libraries})
23521 @acindex{HAVE_LIBRARY}
23522 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23523 @var{function} argument of @code{main}.  In addition, @var{library} can
23524 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23525 all of those cases, the compiler is passed @option{-lfoo}.  However,
23526 @var{library} cannot be a shell variable; it must be a literal name.
23527 @xref{AC_CHECK_LIB}.
23528 @end defmac
23530 @defmac AC_HAVE_POUNDBANG
23531 @acindex{HAVE_POUNDBANG}
23532 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23533 @end defmac
23535 @defmac AC_HEADER_CHECK
23536 @acindex{HEADER_CHECK}
23537 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23538 @end defmac
23540 @defmac AC_HEADER_EGREP
23541 @acindex{HEADER_EGREP}
23542 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23543 @end defmac
23545 @anchor{AC_HEADER_TIME}
23546 @defmac AC_HEADER_TIME
23547 @acindex{HEADER_TIME}
23548 @cvindex TIME_WITH_SYS_TIME
23549 @hdrindex{time.h}
23550 @hdrindex{sys/time.h}
23551 @caindex header_time
23552 This macro used to check whether it was possible to include
23553 @file{time.h} and @file{sys/time.h} in the same source file,
23554 defining @code{TIME_WITH_SYS_TIME} if so.
23556 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23557 although it does still define @code{TIME_WITH_SYS_TIME} for
23558 compatibility's sake.  @file{time.h} is universally present, and the
23559 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23560 obsolete.
23561 @end defmac
23563 @defmac AC_HELP_STRING
23564 @acindex{HELP_STRING}
23565 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23566 @end defmac
23568 @defmac AC_INIT (@var{unique-file-in-source-dir})
23569 @acindex{INIT}
23570 Formerly @code{AC_INIT} used to have a single argument, and was
23571 equivalent to:
23573 @example
23574 AC_INIT
23575 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23576 @end example
23577 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23578 @end defmac
23580 @defmac AC_INLINE
23581 @acindex{INLINE}
23582 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23583 @end defmac
23585 @defmac AC_INT_16_BITS
23586 @acindex{INT_16_BITS}
23587 @cvindex INT_16_BITS
23588 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23589 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23590 @end defmac
23592 @defmac AC_IRIX_SUN
23593 @acindex{IRIX_SUN}
23594 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23595 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23596 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23597 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23598 getpwnam)}.  Up to Autoconf 2.13, it used to be
23600 @example
23601 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23602 @end example
23604 @noindent
23605 now it is defined as
23607 @example
23608 AC_FUNC_GETMNTENT
23609 AC_CHECK_LIB([sun], [getpwnam])
23610 @end example
23612 @noindent
23613 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23614 @end defmac
23616 @defmac AC_ISC_POSIX
23617 @acindex{ISC_POSIX}
23618 @ovindex LIBS
23619 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23620 necessary for Posix facilities.  Sun dropped support for the obsolete
23621 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23622 need not use this macro.  It is implemented as
23623 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23624 @end defmac
23626 @defmac AC_LANG_C
23627 @acindex{LANG_C}
23628 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23629 @end defmac
23631 @defmac AC_LANG_CPLUSPLUS
23632 @acindex{LANG_CPLUSPLUS}
23633 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23634 @end defmac
23636 @defmac AC_LANG_FORTRAN77
23637 @acindex{LANG_FORTRAN77}
23638 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23639 @end defmac
23641 @defmac AC_LANG_RESTORE
23642 @acindex{LANG_RESTORE}
23643 Select the @var{language} that is saved on the top of the stack, as set
23644 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23645 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23646 preferred way to change languages.
23647 @end defmac
23649 @defmac AC_LANG_SAVE
23650 @acindex{LANG_SAVE}
23651 Remember the current language (as set by @code{AC_LANG}) on a stack.
23652 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23653 (@pxref{AC_LANG_PUSH}).
23654 @end defmac
23656 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23657 @acindex{LINK_FILES}
23658 This is an obsolete version of @code{AC_CONFIG_LINKS}
23659 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23661 @example
23662 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23663               host.h            object.h)
23664 @end example
23666 @noindent
23669 @example
23670 AC_CONFIG_LINKS([host.h:config/$machine.h
23671                 object.h:config/$obj_format.h])
23672 @end example
23673 @end defmac
23675 @defmac AC_LN_S
23676 @acindex{LN_S}
23677 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23678 @end defmac
23680 @defmac AC_LONG_64_BITS
23681 @acindex{LONG_64_BITS}
23682 @cvindex LONG_64_BITS
23683 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23684 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23685 (@pxref{AC_CHECK_SIZEOF}).
23686 @end defmac
23688 @defmac AC_LONG_DOUBLE
23689 @acindex{LONG_DOUBLE}
23690 If the C compiler supports a working @code{long double} type with more
23691 range or precision than the @code{double} type, define
23692 @code{HAVE_LONG_DOUBLE}.
23694 You should use @code{AC_TYPE_LONG_DOUBLE} or
23695 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23696 @end defmac
23698 @defmac AC_LONG_FILE_NAMES
23699 @acindex{LONG_FILE_NAMES}
23700 Replaced by
23701 @example
23702 AC_SYS_LONG_FILE_NAMES
23703 @end example
23704 @noindent
23705 @xref{AC_SYS_LONG_FILE_NAMES}.
23706 @end defmac
23708 @defmac AC_MAJOR_HEADER
23709 @acindex{MAJOR_HEADER}
23710 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23711 @end defmac
23713 @defmac AC_MEMORY_H
23714 @acindex{MEMORY_H}
23715 @cvindex NEED_MEMORY_H
23716 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23717 defined in @file{memory.h}.  Today it is equivalent to
23718 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23719 your code to get the @code{mem} functions from @file{string.h} instead.
23720 @end defmac
23722 @defmac AC_MINGW32
23723 @acindex{MINGW32}
23724 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23725 environment and sets @code{MINGW32}.  Don't use this macro, the
23726 dignified means to check the nature of the host is using
23727 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23728 @end defmac
23730 @defmac AC_MINIX
23731 @acindex{MINIX}
23732 @cvindex _MINIX
23733 @cvindex _POSIX_SOURCE
23734 @cvindex _POSIX_1_SOURCE
23735 This macro is a platform-specific subset of
23736 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23737 @end defmac
23739 @defmac AC_MINUS_C_MINUS_O
23740 @acindex{MINUS_C_MINUS_O}
23741 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23742 @end defmac
23744 @defmac AC_MMAP
23745 @acindex{MMAP}
23746 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23747 @end defmac
23749 @defmac AC_MODE_T
23750 @acindex{MODE_T}
23751 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23752 @end defmac
23754 @defmac AC_OBJEXT
23755 @acindex{OBJEXT}
23756 @ovindex OBJEXT
23757 Defined the output variable @code{OBJEXT} based on the output of the
23758 compiler, after .c files have been excluded.  Typically set to @samp{o}
23759 if Posix, @samp{obj} if a DOS variant.
23760 Now the compiler checking macros handle
23761 this automatically.
23762 @end defmac
23764 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23765 @acindex{OBSOLETE}
23766 Make M4 print a message to the standard error output warning that
23767 @var{this-macro-name} is obsolete, and giving the file and line number
23768 where it was called.  @var{this-macro-name} should be the name of the
23769 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23770 it is printed at the end of the warning message; for example, it can be
23771 a suggestion for what to use instead of @var{this-macro-name}.
23773 For instance
23775 @example
23776 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23777 @end example
23779 @noindent
23780 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23781 services to the user (@pxref{AU_DEFUN}).
23782 @end defmac
23784 @defmac AC_OFF_T
23785 @acindex{OFF_T}
23786 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23787 @end defmac
23789 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23790 @acindex{OUTPUT}
23791 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23792 interface is equivalent to:
23794 @example
23795 @group
23796 AC_CONFIG_FILES(@var{file}@dots{})
23797 AC_CONFIG_COMMANDS([default],
23798                    @var{extra-cmds}, @var{init-cmds})
23799 AC_OUTPUT
23800 @end group
23801 @end example
23803 @noindent
23804 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23805 @end defmac
23807 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23808 @acindex{OUTPUT_COMMANDS}
23809 Specify additional shell commands to run at the end of
23810 @file{config.status}, and shell commands to initialize any variables
23811 from @command{configure}.  This macro may be called multiple times.  It is
23812 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23814 Here is an unrealistic example:
23816 @example
23817 fubar=27
23818 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23819                    [fubar=$fubar])
23820 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23821                    [echo init bit])
23822 @end example
23824 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23825 additional key, an important difference is that
23826 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23827 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23828 can safely be given macro calls as arguments:
23830 @example
23831 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23832 @end example
23834 @noindent
23835 Conversely, where one level of quoting was enough for literal strings
23836 with @code{AC_OUTPUT_COMMANDS}, you need two with
23837 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23839 @example
23840 @group
23841 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23842 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23843 @end group
23844 @end example
23845 @end defmac
23847 @defmac AC_PID_T
23848 @acindex{PID_T}
23849 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23850 @end defmac
23852 @defmac AC_PREFIX
23853 @acindex{PREFIX}
23854 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23855 @end defmac
23857 @defmac AC_PROG_CC_C89
23858 @acindex{PROG_CC_C89}
23859 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23860 @end defmac
23862 @defmac AC_PROG_CC_C99
23863 @acindex{PROG_CC_C99}
23864 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23865 @end defmac
23867 @defmac AC_PROG_CC_STDC
23868 @acindex{PROG_CC_STDC}
23869 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23870 @end defmac
23872 @defmac AC_PROGRAMS_CHECK
23873 @acindex{PROGRAMS_CHECK}
23874 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23875 @end defmac
23877 @defmac AC_PROGRAMS_PATH
23878 @acindex{PROGRAMS_PATH}
23879 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23880 @end defmac
23882 @defmac AC_PROGRAM_CHECK
23883 @acindex{PROGRAM_CHECK}
23884 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23885 @end defmac
23887 @defmac AC_PROGRAM_EGREP
23888 @acindex{PROGRAM_EGREP}
23889 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23890 @end defmac
23892 @defmac AC_PROGRAM_PATH
23893 @acindex{PROGRAM_PATH}
23894 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23895 @end defmac
23897 @defmac AC_REMOTE_TAPE
23898 @acindex{REMOTE_TAPE}
23899 Removed because of limited usefulness.
23900 @end defmac
23902 @defmac AC_RESTARTABLE_SYSCALLS
23903 @acindex{RESTARTABLE_SYSCALLS}
23904 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23905 these days portable programs should use @code{sigaction} with
23906 @code{SA_RESTART} if they want restartable system calls.  They should
23907 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23908 system call is restartable is a dynamic issue, not a configuration-time
23909 issue.
23910 @end defmac
23912 @defmac AC_RETSIGTYPE
23913 @acindex{RETSIGTYPE}
23914 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23915 is obsolete when assuming C89 or better.
23916 @end defmac
23918 @defmac AC_RSH
23919 @acindex{RSH}
23920 Removed because of limited usefulness.
23921 @end defmac
23923 @defmac AC_SCO_INTL
23924 @acindex{SCO_INTL}
23925 @ovindex LIBS
23926 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23927 macro used to do this:
23929 @example
23930 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23931 @end example
23933 @noindent
23934 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23935 @end defmac
23937 @defmac AC_SETVBUF_REVERSED
23938 @acindex{SETVBUF_REVERSED}
23939 Replaced by
23940 @example
23941 AC_FUNC_SETVBUF_REVERSED
23942 @end example
23943 @noindent
23944 @xref{AC_FUNC_SETVBUF_REVERSED}.
23945 @end defmac
23947 @defmac AC_SET_MAKE
23948 @acindex{SET_MAKE}
23949 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23950 @end defmac
23952 @defmac AC_SIZEOF_TYPE
23953 @acindex{SIZEOF_TYPE}
23954 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23955 @end defmac
23957 @defmac AC_SIZE_T
23958 @acindex{SIZE_T}
23959 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23960 @end defmac
23962 @defmac AC_STAT_MACROS_BROKEN
23963 @acindex{STAT_MACROS_BROKEN}
23964 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23965 @end defmac
23967 @defmac AC_STDC_HEADERS
23968 @acindex{STDC_HEADERS}
23969 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
23970 is itself obsolete.  Nowadays it is safe to assume the facilities of C90
23971 exist.
23972 @end defmac
23974 @defmac AC_STRCOLL
23975 @acindex{STRCOLL}
23976 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23977 @end defmac
23979 @defmac AC_STRUCT_ST_BLKSIZE
23980 @acindex{STRUCT_ST_BLKSIZE}
23981 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23982 @cvindex HAVE_ST_BLKSIZE
23983 If @code{struct stat} contains an @code{st_blksize} member, define
23984 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23985 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23986 the future.  This macro is obsoleted, and should be replaced by
23988 @example
23989 AC_CHECK_MEMBERS([struct stat.st_blksize])
23990 @end example
23991 @noindent
23992 @xref{AC_CHECK_MEMBERS}.
23993 @end defmac
23995 @defmac AC_STRUCT_ST_RDEV
23996 @acindex{STRUCT_ST_RDEV}
23997 @cvindex HAVE_ST_RDEV
23998 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23999 If @code{struct stat} contains an @code{st_rdev} member, define
24000 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
24001 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
24002 in the future.  Actually, even the new macro is obsolete and should be
24003 replaced by:
24004 @example
24005 AC_CHECK_MEMBERS([struct stat.st_rdev])
24006 @end example
24007 @noindent
24008 @xref{AC_CHECK_MEMBERS}.
24009 @end defmac
24011 @defmac AC_ST_BLKSIZE
24012 @acindex{ST_BLKSIZE}
24013 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24014 @end defmac
24016 @defmac AC_ST_BLOCKS
24017 @acindex{ST_BLOCKS}
24018 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
24019 @end defmac
24021 @defmac AC_ST_RDEV
24022 @acindex{ST_RDEV}
24023 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
24024 @end defmac
24026 @defmac AC_SYS_RESTARTABLE_SYSCALLS
24027 @acindex{SYS_RESTARTABLE_SYSCALLS}
24028 @cvindex HAVE_RESTARTABLE_SYSCALLS
24029 If the system automatically restarts a system call that is interrupted
24030 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
24031 not check whether system calls are restarted in general---it checks whether a
24032 signal handler installed with @code{signal} (but not @code{sigaction})
24033 causes system calls to be restarted.  It does not check whether system calls
24034 can be restarted when interrupted by signals that have no handler.
24036 These days portable programs should use @code{sigaction} with
24037 @code{SA_RESTART} if they want restartable system calls.  They should
24038 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
24039 system call is restartable is a dynamic issue, not a configuration-time
24040 issue.
24041 @end defmac
24043 @defmac AC_SYS_SIGLIST_DECLARED
24044 @acindex{SYS_SIGLIST_DECLARED}
24045 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
24046 name is obsolete, as the same functionality is now achieved via
24047 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
24048 @end defmac
24050 @defmac AC_TEST_CPP
24051 @acindex{TEST_CPP}
24052 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
24053 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
24054 @end defmac
24056 @defmac AC_TEST_PROGRAM
24057 @acindex{TEST_PROGRAM}
24058 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24059 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24060 @end defmac
24062 @defmac AC_TIMEZONE
24063 @acindex{TIMEZONE}
24064 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24065 @end defmac
24067 @defmac AC_TIME_WITH_SYS_TIME
24068 @acindex{TIME_WITH_SYS_TIME}
24069 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24070 itself obsolete; nowadays one need only do
24071 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24072 @end defmac
24074 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24075   @ovar{action-if-true}, @ovar{action-if-false})
24076 @acindex{TRY_COMPILE}
24077 Same as:
24079 @example
24080 AC_COMPILE_IFELSE(
24081   [AC_LANG_PROGRAM([[@var{includes}]],
24082      [[@var{function-body}]])],
24083   [@var{action-if-true}],
24084   [@var{action-if-false}])
24085 @end example
24087 @noindent
24088 @xref{Running the Compiler}.
24090 This macro double quotes both @var{includes} and @var{function-body}.
24092 For C and C++, @var{includes} is any @code{#include} statements needed
24093 by the code in @var{function-body} (@var{includes} is ignored if
24094 the currently selected language is Fortran or Fortran 77).  The compiler
24095 and compilation flags are determined by the current language
24096 (@pxref{Language Choice}).
24097 @end defmac
24099 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24100 @acindex{TRY_CPP}
24101 Same as:
24103 @example
24104 AC_PREPROC_IFELSE(
24105   [AC_LANG_SOURCE([[@var{input}]])],
24106   [@var{action-if-true}],
24107   [@var{action-if-false}])
24108 @end example
24110 @noindent
24111 @xref{Running the Preprocessor}.
24113 This macro double quotes the @var{input}.
24114 @end defmac
24116 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24117   @ovar{action-if-true}, @ovar{action-if-false})
24118 @acindex{TRY_LINK}
24119 Same as:
24121 @example
24122 AC_LINK_IFELSE(
24123   [AC_LANG_PROGRAM([[@var{includes}]],
24124      [[@var{function-body}]])],
24125   [@var{action-if-true}],
24126   [@var{action-if-false}])
24127 @end example
24129 @noindent
24130 @xref{Running the Compiler}.
24132 This macro double quotes both @var{includes} and @var{function-body}.
24134 Depending on the current language (@pxref{Language Choice}), create a
24135 test program to see whether a function whose body consists of
24136 @var{function-body} can be compiled and linked.  If the file compiles
24137 and links successfully, run shell commands @var{action-if-found},
24138 otherwise run @var{action-if-not-found}.
24140 This macro double quotes both @var{includes} and @var{function-body}.
24142 For C and C++, @var{includes} is any @code{#include} statements needed
24143 by the code in @var{function-body} (@var{includes} is ignored if
24144 the currently selected language is Fortran or Fortran 77).  The compiler
24145 and compilation flags are determined by the current language
24146 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24147 @code{LIBS} are used for linking.
24148 @end defmac
24150 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24151   @ovar{action-if-not-found})
24152 @acindex{TRY_LINK_FUNC}
24153 This macro is equivalent to
24154 @example
24155 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24156   [@var{action-if-found}], [@var{action-if-not-found}])
24157 @end example
24158 @noindent
24159 @xref{AC_LINK_IFELSE}.
24160 @end defmac
24162 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24163   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24164 @acindex{TRY_RUN}
24165 Same as:
24167 @example
24168 AC_RUN_IFELSE(
24169   [AC_LANG_SOURCE([[@var{program}]])],
24170   [@var{action-if-true}],
24171   [@var{action-if-false}],
24172   [@var{action-if-cross-compiling}])
24173 @end example
24175 @noindent
24176 @xref{Runtime}.
24177 @end defmac
24179 @anchor{AC_TYPE_SIGNAL}
24180 @defmac AC_TYPE_SIGNAL
24181 @acindex{TYPE_SIGNAL}
24182 @cvindex RETSIGTYPE
24183 @hdrindex{signal.h}
24184 If @file{signal.h} declares @code{signal} as returning a pointer to a
24185 function returning @code{void}, define @code{RETSIGTYPE} to be
24186 @code{void}; otherwise, define it to be @code{int}.  These days, it is
24187 portable to assume C89, and that signal handlers return @code{void},
24188 without needing to use this macro or @code{RETSIGTYPE}.
24190 When targeting older K&R C, it is possible to define signal handlers as
24191 returning type @code{RETSIGTYPE}, and omit a return statement:
24193 @example
24194 @group
24195 RETSIGTYPE
24196 hup_handler ()
24198 @dots{}
24200 @end group
24201 @end example
24202 @end defmac
24204 @defmac AC_UID_T
24205 @acindex{UID_T}
24206 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24207 @end defmac
24209 @defmac AC_UNISTD_H
24210 @acindex{UNISTD_H}
24211 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24212 which is one of the tests done as a side effect by
24213 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24214 unnecessary to write explicitly.
24215 @end defmac
24217 @defmac AC_USG
24218 @acindex{USG}
24219 @cvindex USG
24220 Define @code{USG} if the BSD string functions (@code{bcopy},
24221 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24222 in @file{strings.h}.  Modern code should assume @file{string.h} exists
24223 and should use the ISO C string functions (@code{memmove}, @code{memset},
24224 @code{strchr}, @code{strrchr}, etc) unconditionally.
24226 @file{strings.h} may be the only header that declares @code{strcasecmp},
24227 @code{strncasecmp}, and @code{ffs}.  @code{AC_INCLUDES_DEFAULT} checks
24228 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24229 @end defmac
24231 @defmac AC_UTIME_NULL
24232 @acindex{UTIME_NULL}
24233 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24234 @end defmac
24236 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24237 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24238 If the cache file is inconsistent with the current host, target and
24239 build system types, it used to execute @var{cmd} or print a default
24240 error message.  This is now handled by default.
24241 @end defmac
24243 @defmac AC_VERBOSE (@var{result-description})
24244 @acindex{VERBOSE}
24245 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24246 @end defmac
24248 @defmac AC_VFORK
24249 @acindex{VFORK}
24250 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24251 @end defmac
24253 @defmac AC_VPRINTF
24254 @acindex{VPRINTF}
24255 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24256 @end defmac
24258 @defmac AC_WAIT3
24259 @acindex{WAIT3}
24260 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24261 portable programs should use @code{waitpid}, not @code{wait3}, as
24262 @code{wait3} has been removed from Posix.
24263 @end defmac
24265 @defmac AC_WARN
24266 @acindex{WARN}
24267 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24268 @end defmac
24270 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24271   @ovar{action-if-not-given})
24272 @acindex{WITH}
24273 This is an obsolete version of @code{AC_ARG_WITH} that does not
24274 support providing a help string (@pxref{AC_ARG_WITH}).
24275 @end defmac
24277 @defmac AC_WORDS_BIGENDIAN
24278 @acindex{WORDS_BIGENDIAN}
24279 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24280 @end defmac
24282 @defmac AC_XENIX_DIR
24283 @acindex{XENIX_DIR}
24284 @ovindex LIBS
24285 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24286 Xenix.  Also, if @file{dirent.h} is being checked for, added
24287 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24288 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24289 running XENIX on which you should not depend:
24291 @example
24292 AC_MSG_CHECKING([for Xenix])
24293 AC_EGREP_CPP([yes],
24294 [#if defined M_XENIX && !defined M_UNIX
24295   yes
24296 #endif],
24297              [AC_MSG_RESULT([yes]); XENIX=yes],
24298              [AC_MSG_RESULT([no]); XENIX=])
24299 @end example
24300 @noindent
24301 Don't use this macro, the dignified means to check the nature of the
24302 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24303 @end defmac
24305 @defmac AC_YYTEXT_POINTER
24306 @acindex{YYTEXT_POINTER}
24307 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24308 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24309 @end defmac
24311 @node Autoconf 1
24312 @section Upgrading From Version 1
24313 @cindex Upgrading autoconf
24314 @cindex Autoconf upgrading
24316 Autoconf version 2 is mostly backward compatible with version 1.
24317 However, it introduces better ways to do some things, and doesn't
24318 support some of the ugly things in version 1.  So, depending on how
24319 sophisticated your @file{configure.ac} files are, you might have to do
24320 some manual work in order to upgrade to version 2.  This chapter points
24321 out some problems to watch for when upgrading.  Also, perhaps your
24322 @command{configure} scripts could benefit from some of the new features in
24323 version 2; the changes are summarized in the file @file{NEWS} in the
24324 Autoconf distribution.
24326 @menu
24327 * Changed File Names::          Files you might rename
24328 * Changed Makefiles::           New things to put in @file{Makefile.in}
24329 * Changed Macros::              Macro calls you might replace
24330 * Changed Results::             Changes in how to check test results
24331 * Changed Macro Writing::       Better ways to write your own macros
24332 @end menu
24334 @node Changed File Names
24335 @subsection Changed File Names
24337 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24338 in a particular package's source directory), you must rename it to
24339 @file{acsite.m4}.  @xref{autoconf Invocation}.
24341 If you distribute @file{install.sh} with your package, rename it to
24342 @file{install-sh} so @command{make} builtin rules don't inadvertently
24343 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24344 looks for the script under both names, but it is best to use the new name.
24346 If you were using @file{config.h.top}, @file{config.h.bot}, or
24347 @file{acconfig.h}, you still can, but you have less clutter if you
24348 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24350 @node Changed Makefiles
24351 @subsection Changed Makefiles
24353 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24354 your @file{Makefile.in} files, so they can take advantage of the values
24355 of those variables in the environment when @command{configure} is run.
24356 Doing this isn't necessary, but it's a convenience for users.
24358 Also add @samp{@@configure_input@@} in a comment to each input file for
24359 @code{AC_OUTPUT}, so that the output files contain a comment saying
24360 they were produced by @command{configure}.  Automatically selecting the
24361 right comment syntax for all the kinds of files that people call
24362 @code{AC_OUTPUT} on became too much work.
24364 Add @file{config.log} and @file{config.cache} to the list of files you
24365 remove in @code{distclean} targets.
24367 If you have the following in @file{Makefile.in}:
24369 @example
24370 prefix = /usr/local
24371 exec_prefix = $(prefix)
24372 @end example
24374 @noindent
24375 you must change it to:
24377 @example
24378 prefix = @@prefix@@
24379 exec_prefix = @@exec_prefix@@
24380 @end example
24382 @noindent
24383 The old behavior of replacing those variables without @samp{@@}
24384 characters around them has been removed.
24386 @node Changed Macros
24387 @subsection Changed Macros
24389 Many of the macros were renamed in Autoconf version 2.  You can still
24390 use the old names, but the new ones are clearer, and it's easier to find
24391 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24392 new names for the old macros.  Use the @command{autoupdate} program to
24393 convert your @file{configure.ac} to using the new macro names.
24394 @xref{autoupdate Invocation}.
24396 Some macros have been superseded by similar ones that do the job better,
24397 but are not call-compatible.  If you get warnings about calling obsolete
24398 macros while running @command{autoconf}, you may safely ignore them, but
24399 your @command{configure} script generally works better if you follow
24400 the advice that is printed about what to replace the obsolete macros with.  In
24401 particular, the mechanism for reporting the results of tests has
24402 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24403 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24404 looks better if you switch to @code{AC_MSG_CHECKING} and
24405 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24406 in conjunction with cache variables.  @xref{Caching Results}.
24410 @node Changed Results
24411 @subsection Changed Results
24413 If you were checking the results of previous tests by examining the
24414 shell variable @code{DEFS}, you need to switch to checking the values of
24415 the cache variables for those tests.  @code{DEFS} no longer exists while
24416 @command{configure} is running; it is only created when generating output
24417 files.  This difference from version 1 is because properly quoting the
24418 contents of that variable turned out to be too cumbersome and
24419 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24420 Variable Names}.
24422 For example, here is a @file{configure.ac} fragment written for Autoconf
24423 version 1:
24425 @example
24426 AC_HAVE_FUNCS(syslog)
24427 case "$DEFS" in
24428 *-DHAVE_SYSLOG*) ;;
24429 *) # syslog is not in the default libraries.  See if it's in some other.
24430   saved_LIBS="$LIBS"
24431   for lib in bsd socket inet; do
24432     AC_CHECKING(for syslog in -l$lib)
24433     LIBS="-l$lib $saved_LIBS"
24434     AC_HAVE_FUNCS(syslog)
24435     case "$DEFS" in
24436     *-DHAVE_SYSLOG*) break ;;
24437     *) ;;
24438     esac
24439     LIBS="$saved_LIBS"
24440   done ;;
24441 esac
24442 @end example
24444 Here is a way to write it for version 2:
24446 @example
24447 AC_CHECK_FUNCS([syslog])
24448 if test "x$ac_cv_func_syslog" = xno; then
24449   # syslog is not in the default libraries.  See if it's in some other.
24450   for lib in bsd socket inet; do
24451     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24452       LIBS="-l$lib $LIBS"; break])
24453   done
24455 @end example
24457 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24458 backslashes before quotes, you need to remove them.  It now works
24459 predictably, and does not treat quotes (except back quotes) specially.
24460 @xref{Setting Output Variables}.
24462 All of the Boolean shell variables set by Autoconf macros now use
24463 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24464 though for backward compatibility some use the empty string instead.  If
24465 you were relying on a shell variable being set to something like 1 or
24466 @samp{t} for true, you need to change your tests.
24468 @node Changed Macro Writing
24469 @subsection Changed Macro Writing
24471 When defining your own macros, you should now use @code{AC_DEFUN}
24472 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24473 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24474 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24475 messages on the screen.  There's no actual harm in continuing to use the
24476 older way, but it's less convenient and attractive.  @xref{Macro
24477 Definitions}.
24479 You probably looked at the macros that came with Autoconf as a guide for
24480 how to do things.  It would be a good idea to take a look at the new
24481 versions of them, as the style is somewhat improved and they take
24482 advantage of some new features.
24484 If you were doing tricky things with undocumented Autoconf internals
24485 (macros, variables, diversions), check whether you need to change
24486 anything to account for changes that have been made.  Perhaps you can
24487 even use an officially supported technique in version 2 instead of
24488 kludging.  Or perhaps not.
24490 To speed up your locally written feature tests, add caching to them.
24491 See whether any of your tests are of general enough usefulness to
24492 encapsulate them into macros that you can share.
24495 @node Autoconf 2.13
24496 @section Upgrading From Version 2.13
24497 @cindex Upgrading autoconf
24498 @cindex Autoconf upgrading
24500 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24501 suits this section@enddots{}
24503 @quotation
24504 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24505 However, it introduces better ways to do some things, and doesn't
24506 support some of the ugly things in version 2.13.  So, depending on how
24507 sophisticated your @file{configure.ac} files are, you might have to do
24508 some manual work in order to upgrade to version 2.50.  This chapter
24509 points out some problems to watch for when upgrading.  Also, perhaps
24510 your @command{configure} scripts could benefit from some of the new
24511 features in version 2.50; the changes are summarized in the file
24512 @file{NEWS} in the Autoconf distribution.
24513 @end quotation
24515 @menu
24516 * Changed Quotation::           Broken code which used to work
24517 * New Macros::                  Interaction with foreign macros
24518 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24519 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24520 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24521 @end menu
24523 @node Changed Quotation
24524 @subsection Changed Quotation
24526 The most important changes are invisible to you: the implementation of
24527 most macros have completely changed.  This allowed more factorization of
24528 the code, better error messages, a higher uniformity of the user's
24529 interface etc.  Unfortunately, as a side effect, some construct which
24530 used to (miraculously) work might break starting with Autoconf 2.50.
24531 The most common culprit is bad quotation.
24533 For instance, in the following example, the message is not properly
24534 quoted:
24536 @example
24537 AC_INIT
24538 AC_CHECK_HEADERS(foo.h, ,
24539   AC_MSG_ERROR(cannot find foo.h, bailing out))
24540 AC_OUTPUT
24541 @end example
24543 @noindent
24544 Autoconf 2.13 simply ignores it:
24546 @example
24547 $ @kbd{autoconf-2.13; ./configure --silent}
24548 creating cache ./config.cache
24549 configure: error: cannot find foo.h
24551 @end example
24553 @noindent
24554 while Autoconf 2.50 produces a broken @file{configure}:
24556 @example
24557 $ @kbd{autoconf-2.50; ./configure --silent}
24558 configure: error: cannot find foo.h
24559 ./configure: exit: bad non-numeric arg `bailing'
24560 ./configure: exit: bad non-numeric arg `bailing'
24562 @end example
24564 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24565 too!
24567 @example
24568 AC_INIT([Example], [1.0], [bug-example@@example.org])
24569 AC_CHECK_HEADERS([foo.h], [],
24570   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24571 AC_OUTPUT
24572 @end example
24574 Many many (and many more) Autoconf macros were lacking proper quotation,
24575 including no less than@dots{} @code{AC_DEFUN} itself!
24577 @example
24578 $ @kbd{cat configure.in}
24579 AC_DEFUN([AC_PROG_INSTALL],
24580 [# My own much better version
24582 AC_INIT
24583 AC_PROG_INSTALL
24584 AC_OUTPUT
24585 $ @kbd{autoconf-2.13}
24586 autoconf: Undefined macros:
24587 ***BUG in Autoconf--please report*** AC_FD_MSG
24588 ***BUG in Autoconf--please report*** AC_EPI
24589 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24590 configure.in:5:AC_PROG_INSTALL
24591 $ @kbd{autoconf-2.50}
24593 @end example
24596 @node New Macros
24597 @subsection New Macros
24599 @cindex undefined macro
24600 @cindex @code{_m4_divert_diversion}
24602 While Autoconf was relatively dormant in the late 1990s, Automake
24603 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24604 in 2001, Autoconf provided
24605 versions of these macros, integrated in the @code{AC_} namespace,
24606 instead of @code{AM_}.  But in order to ease the upgrading via
24607 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24609 Unfortunately older versions of Automake (e.g., Automake 1.4)
24610 did not quote the names of these macros.
24611 Therefore, when @command{m4} finds something like
24612 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24613 @code{AM_TYPE_PTRDIFF_T} is
24614 expanded, replaced with its Autoconf definition.
24616 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24617 complains, in its own words:
24619 @example
24620 $ @kbd{cat configure.ac}
24621 AC_INIT([Example], [1.0], [bug-example@@example.org])
24622 AM_TYPE_PTRDIFF_T
24623 $ @kbd{aclocal-1.4}
24624 $ @kbd{autoconf}
24625 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24626 aclocal.m4:17: the top level
24627 autom4te: m4 failed with exit status: 1
24629 @end example
24631 Modern versions of Automake no longer define most of these
24632 macros, and properly quote the names of the remaining macros.
24633 If you must use an old Automake, do not depend upon macros from Automake
24634 as it is simply not its job
24635 to provide macros (but the one it requires itself):
24637 @example
24638 $ @kbd{cat configure.ac}
24639 AC_INIT([Example], [1.0], [bug-example@@example.org])
24640 AM_TYPE_PTRDIFF_T
24641 $ @kbd{rm aclocal.m4}
24642 $ @kbd{autoupdate}
24643 autoupdate: `configure.ac' is updated
24644 $ @kbd{cat configure.ac}
24645 AC_INIT([Example], [1.0], [bug-example@@example.org])
24646 AC_CHECK_TYPES([ptrdiff_t])
24647 $ @kbd{aclocal-1.4}
24648 $ @kbd{autoconf}
24650 @end example
24653 @node Hosts and Cross-Compilation
24654 @subsection Hosts and Cross-Compilation
24655 @cindex Cross compilation
24657 Based on the experience of compiler writers, and after long public
24658 debates, many aspects of the cross-compilation chain have changed:
24660 @itemize @minus
24661 @item
24662 the relationship between the build, host, and target architecture types,
24664 @item
24665 the command line interface for specifying them to @command{configure},
24667 @item
24668 the variables defined in @command{configure},
24670 @item
24671 the enabling of cross-compilation mode.
24672 @end itemize
24674 @sp 1
24676 The relationship between build, host, and target have been cleaned up:
24677 the chain of default is now simply: target defaults to host, host to
24678 build, and build to the result of @command{config.guess}.  Nevertheless,
24679 in order to ease the transition from 2.13 to 2.50, the following
24680 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24681 be completely disabled in a couple of releases (we cannot keep it, as it
24682 proves to cause more problems than it cures).
24684 They all default to the result of running @command{config.guess}, unless
24685 you specify either @option{--build} or @option{--host}.  In this case,
24686 the default becomes the system type you specified.  If you specify both,
24687 and they're different, @command{configure} enters cross compilation
24688 mode, so it doesn't run any tests that require execution.
24690 Hint: if you mean to override the result of @command{config.guess},
24691 prefer @option{--build} over @option{--host}.
24693 @sp 1
24695 For backward compatibility, @command{configure} accepts a system
24696 type as an option by itself.  Such an option overrides the
24697 defaults for build, host, and target system types.  The following
24698 configure statement configures a cross toolchain that runs on
24699 NetBSD/alpha but generates code for GNU Hurd/sparc,
24700 which is also the build platform.
24702 @example
24703 ./configure --host=alpha-netbsd sparc-gnu
24704 @end example
24706 @sp 1
24708 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24709 and @code{target} had a different semantics before and after the
24710 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24711 @option{--build} is strictly copied into @code{build_alias}, and is left
24712 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24713 set to the canonicalized build type.  To ease the transition, before,
24714 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24715 rely on this broken feature.
24717 For consistency with the backward compatibility scheme exposed above,
24718 when @option{--host} is specified but @option{--build} isn't, the build
24719 system is assumed to be the same as @option{--host}, and
24720 @samp{build_alias} is set to that value.  Eventually, this
24721 historically incorrect behavior will go away.
24723 @sp 1
24725 The former scheme to enable cross-compilation proved to cause more harm
24726 than good, in particular, it used to be triggered too easily, leaving
24727 regular end users puzzled in front of cryptic error messages.
24728 @command{configure} could even enter cross-compilation mode only
24729 because the compiler was not functional.  This is mainly because
24730 @command{configure} used to try to detect cross-compilation, instead of
24731 waiting for an explicit flag from the user.
24733 Now, @command{configure} enters cross-compilation mode if and only if
24734 @option{--host} is passed.
24736 That's the short documentation.  To ease the transition between 2.13 and
24737 its successors, a more complicated scheme is implemented.  @emph{Do not
24738 rely on the following}, as it will be removed in the near future.
24740 If you specify @option{--host}, but not @option{--build}, when
24741 @command{configure} performs the first compiler test it tries to run
24742 an executable produced by the compiler.  If the execution fails, it
24743 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24744 the compiler test is performed, it may be too late to modify the
24745 build-system type: other tests may have already been performed.
24746 Therefore, whenever you specify @option{--host}, be sure to specify
24747 @option{--build} too.
24749 @example
24750 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24751 @end example
24753 @noindent
24754 enters cross-compilation mode.  The former interface, which
24755 consisted in setting the compiler to a cross-compiler without informing
24756 @command{configure} is obsolete.  For instance, @command{configure}
24757 fails if it can't run the code generated by the specified compiler if you
24758 configure as follows:
24760 @example
24761 ./configure CC=m68k-coff-gcc
24762 @end example
24765 @node AC_LIBOBJ vs LIBOBJS
24766 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24768 Up to Autoconf 2.13, the replacement of functions was triggered via the
24769 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24770 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24771 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24773 This change is mandated by the unification of the GNU Build System
24774 components.  In particular, the various fragile techniques used to parse
24775 a @file{configure.ac} are all replaced with the use of traces.  As a
24776 consequence, any action must be traceable, which obsoletes critical
24777 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24778 and it can even be handled gracefully (read, ``without your having to
24779 change something'').
24781 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24782 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24784 @sp 1
24786 As for function replacement, the fix is immediate: use
24787 @code{AC_LIBOBJ}.  For instance:
24789 @example
24790 LIBOBJS="$LIBOBJS fnmatch.o"
24791 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24792 @end example
24794 @noindent
24795 should be replaced with:
24797 @example
24798 AC_LIBOBJ([fnmatch])
24799 AC_LIBOBJ([malloc])
24800 @end example
24802 @sp 1
24804 @ovindex LIBOBJDIR
24805 When used with Automake 1.10 or newer, a suitable value for
24806 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24807 can be referenced from any @file{Makefile.am}.  Even without Automake,
24808 arranging for @code{LIBOBJDIR} to be set correctly enables
24809 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24810 The @code{LIBOBJDIR} feature is experimental.
24813 @node AC_ACT_IFELSE vs AC_TRY_ACT
24814 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24815 @c the anchor keeps the old node name, to try to avoid breaking links
24816 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24818 @acindex{@var{ACT}_IFELSE}
24819 @acindex{TRY_@var{ACT}}
24820 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24821 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24822 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24823 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24824 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24825 @code{AC_TRY_RUN}.  The motivations where:
24826 @itemize @minus
24827 @item
24828 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24829 quoting their arguments;
24831 @item
24832 the combinatoric explosion is solved by decomposing on the one hand the
24833 generation of sources, and on the other hand executing the program;
24835 @item
24836 this scheme helps supporting more languages than plain C and C++.
24837 @end itemize
24839 In addition to the change of syntax, the philosophy has changed too:
24840 while emphasis was put on speed at the expense of accuracy, today's
24841 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24842 expense of speed.
24845 As a perfect example of what is @emph{not} to be done, here is how to
24846 find out whether a header file contains a particular declaration, such
24847 as a typedef, a structure, a structure member, or a function.  Use
24848 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24849 header file; on some systems the symbol might be defined in another
24850 header file that the file you are checking includes.
24852 As a (bad) example, here is how you should not check for C preprocessor
24853 symbols, either defined by header files or predefined by the C
24854 preprocessor: using @code{AC_EGREP_CPP}:
24856 @example
24857 @group
24858 AC_EGREP_CPP(yes,
24859 [#ifdef _AIX
24860   yes
24861 #endif
24862 ], is_aix=yes, is_aix=no)
24863 @end group
24864 @end example
24866 The above example, properly written would (i) use
24867 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24869 @example
24870 @group
24871 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24872 [[#ifndef _AIX
24873  error: This isn't AIX!
24874 #endif
24875 ]])],
24876                    [is_aix=yes],
24877                    [is_aix=no])
24878 @end group
24879 @end example
24882 @c ============================= Generating Test Suites with Autotest
24884 @node Using Autotest
24885 @chapter Generating Test Suites with Autotest
24887 @cindex Autotest
24889 @display
24890 @strong{N.B.: This section describes a feature which is still
24891 stabilizing.  Although we believe that Autotest is useful as-is, this
24892 documentation describes an interface which might change in the future:
24893 do not depend upon Autotest without subscribing to the Autoconf mailing
24894 lists.}
24895 @end display
24897 It is paradoxical that portable projects depend on nonportable tools
24898 to run their test suite.  Autoconf by itself is the paragon of this
24899 problem: although it aims at perfectly portability, up to 2.13 its
24900 test suite was using DejaGNU, a rich and complex testing
24901 framework, but which is far from being standard on Posix systems.
24902 Worse yet, it was likely to be missing on the most fragile platforms,
24903 the very platforms that are most likely to torture Autoconf and
24904 exhibit deficiencies.
24906 To circumvent this problem, many package maintainers have developed their
24907 own testing framework, based on simple shell scripts whose sole outputs
24908 are exit status values describing whether the test succeeded.  Most of
24909 these tests share common patterns, and this can result in lots of
24910 duplicated code and tedious maintenance.
24912 Following exactly the same reasoning that yielded to the inception of
24913 Autoconf, Autotest provides a test suite generation framework, based on
24914 M4 macros building a portable shell script.  The suite itself is
24915 equipped with automatic logging and tracing facilities which greatly
24916 diminish the interaction with bug reporters, and simple timing reports.
24918 Autoconf itself has been using Autotest for years, and we do attest that
24919 it has considerably improved the strength of the test suite and the
24920 quality of bug reports.  Other projects are known to use some generation
24921 of Autotest, such as Bison, GNU Wdiff, GNU Tar, each of
24922 them with different needs, and this usage has validated Autotest as a general
24923 testing framework.
24925 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24926 interactive tool testing, which is probably its main limitation.
24928 @menu
24929 * Using an Autotest Test Suite::  Autotest and the user
24930 * Writing Testsuites::          Autotest macros
24931 * testsuite Invocation::        Running @command{testsuite} scripts
24932 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24933 @end menu
24935 @node Using an Autotest Test Suite
24936 @section Using an Autotest Test Suite
24938 @menu
24939 * testsuite Scripts::           The concepts of Autotest
24940 * Autotest Logs::               Their contents
24941 @end menu
24943 @node testsuite Scripts
24944 @subsection @command{testsuite} Scripts
24946 @cindex @command{testsuite}
24948 Generating testing or validation suites using Autotest is rather easy.
24949 The whole validation suite is held in a file to be processed through
24950 @command{autom4te}, itself using GNU M4 under the hood, to
24951 produce a stand-alone Bourne shell script which then gets distributed.
24952 Neither @command{autom4te} nor GNU M4 are needed at
24953 the installer's end.
24955 @cindex test group
24956 Each test of the validation suite should be part of some test group.  A
24957 @dfn{test group} is a sequence of interwoven tests that ought to be
24958 executed together, usually because one test in the group creates data
24959 files that a later test in the same group needs to read.  Complex test
24960 groups make later debugging more tedious.  It is much better to
24961 keep only a few tests per test group.  Ideally there is only one test
24962 per test group.
24964 For all but the simplest packages, some file such as @file{testsuite.at}
24965 does not fully hold all test sources, as these are often easier to
24966 maintain in separate files.  Each of these separate files holds a single
24967 test group, or a sequence of test groups all addressing some common
24968 functionality in the package.  In such cases, @file{testsuite.at}
24969 merely initializes the validation suite, and sometimes does elementary
24970 health checking, before listing include statements for all other test
24971 files.  The special file @file{package.m4}, containing the
24972 identification of the package, is automatically included if found.
24974 A convenient alternative consists in moving all the global issues
24975 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24976 invocation) into the file @code{local.at}, and making
24977 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24978 suites.  In such case, generating the whole test suite or pieces of it
24979 is only a matter of choosing the @command{autom4te} command line
24980 arguments.
24982 The validation scripts that Autotest produces are by convention called
24983 @command{testsuite}.  When run, @command{testsuite} executes each test
24984 group in turn, producing only one summary line per test to say if that
24985 particular test succeeded or failed.  At end of all tests, summarizing
24986 counters get printed.  One debugging directory is left for each test
24987 group which failed, if any: such directories are named
24988 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24989 the test group, and they include:
24991 @itemize @bullet
24992 @item a debugging script named @file{run} which reruns the test in
24993 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24994 of debugging scripts has the purpose of easing the chase for bugs.
24996 @item all the files created with @code{AT_DATA}
24998 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
25000 @item a log of the run, named @file{testsuite.log}
25001 @end itemize
25003 In the ideal situation, none of the tests fail, and consequently no
25004 debugging directory is left behind for validation.
25006 It often happens in practice that individual tests in the validation
25007 suite need to get information coming out of the configuration process.
25008 Some of this information, common for all validation suites, is provided
25009 through the file @file{atconfig}, automatically created by
25010 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
25011 testing environment specifically needs, you might prepare an optional
25012 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
25013 The configuration process produces @file{atconfig} and @file{atlocal}
25014 out of these two input files, and these two produced files are
25015 automatically read by the @file{testsuite} script.
25017 Here is a diagram showing the relationship between files.
25019 @noindent
25020 Files used in preparing a software package for distribution:
25022 @example
25023                 [package.m4] -->.
25024                                  \
25025 subfile-1.at ->.  [local.at] ---->+
25026     ...         \                  \
25027 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
25028     ...         /
25029 subfile-n.at ->'
25030 @end example
25032 @noindent
25033 Files used in configuring a software package:
25035 @example
25036                                      .--> atconfig
25037                                     /
25038 [atlocal.in] -->  config.status* --<
25039                                     \
25040                                      `--> [atlocal]
25041 @end example
25043 @noindent
25044 Files created during test suite execution:
25046 @example
25047 atconfig -->.                    .--> testsuite.log
25048              \                  /
25049               >-- testsuite* --<
25050              /                  \
25051 [atlocal] ->'                    `--> [testsuite.dir]
25052 @end example
25055 @node Autotest Logs
25056 @subsection Autotest Logs
25058 When run, the test suite creates a log file named after itself, e.g., a
25059 test suite named @command{testsuite} creates @file{testsuite.log}.  It
25060 contains a lot of information, usually more than maintainers actually
25061 need, but therefore most of the time it contains all that is needed:
25063 @table @asis
25064 @item command line arguments
25065 A bad but unfortunately widespread habit consists of
25066 setting environment variables before the command, such as in
25067 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
25068 know this change, hence (i) it cannot report it to you, and (ii)
25069 it cannot preserve the value of @code{CC} for subsequent runs.
25070 Autoconf faced exactly the same problem, and solved it by asking
25071 users to pass the variable definitions as command line arguments.
25072 Autotest requires this rule, too, but has no means to enforce it; the log
25073 then contains a trace of the variables that were changed by the user.
25075 @item @file{ChangeLog} excerpts
25076 The topmost lines of all the @file{ChangeLog} files found in the source
25077 hierarchy.  This is especially useful when bugs are reported against
25078 development versions of the package, since the version string does not
25079 provide sufficient information to know the exact state of the sources
25080 the user compiled.  Of course, this relies on the use of a
25081 @file{ChangeLog}.
25083 @item build machine
25084 Running a test suite in a cross-compile environment is not an easy task,
25085 since it would mean having the test suite run on a machine @var{build},
25086 while running programs on a machine @var{host}.  It is much simpler to
25087 run both the test suite and the programs on @var{host}, but then, from
25088 the point of view of the test suite, there remains a single environment,
25089 @var{host} = @var{build}.  The log contains relevant information on the
25090 state of the @var{build} machine, including some important environment
25091 variables.
25092 @c FIXME: How about having an M4sh macro to say `hey, log the value
25093 @c of `@dots{}'?  This would help both Autoconf and Autotest.
25095 @item tested programs
25096 The absolute file name and answers to @option{--version} of the tested
25097 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25099 @item configuration log
25100 The contents of @file{config.log}, as created by @command{configure},
25101 are appended.  It contains the configuration flags and a detailed report
25102 on the configuration itself.
25103 @end table
25106 @node Writing Testsuites
25107 @section Writing @file{testsuite.at}
25109 The @file{testsuite.at} is a Bourne shell script making use of special
25110 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
25111 its beginning followed by one call to @code{m4_include} per source file
25112 for tests.  Each such included file, or the remainder of
25113 @file{testsuite.at} if include files are not used, contain a sequence of
25114 test groups.  Each test group begins with a call to @code{AT_SETUP},
25115 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25116 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
25117 groups can be categorized by a call to @code{AT_BANNER}.
25119 All of the public Autotest macros have all-uppercase names in the
25120 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25121 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25122 internal macros.  All shell variables used in the testsuite for internal
25123 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
25124 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25125 makes use of the file system namespace @samp{^at-}.
25127 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25128 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25129 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
25130 @emph{should not use} the namespace of a package that does not own the
25131 macro or shell code you are writing.
25133 @defmac AT_INIT (@ovar{name})
25134 @atindex{INIT}
25135 @c FIXME: Not clear, plus duplication of the information.
25136 Initialize Autotest.  Giving a @var{name} to the test suite is
25137 encouraged if your package includes several test suites.  Before this
25138 macro is called, @code{AT_PACKAGE_STRING} and
25139 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25140 information about the testsuite to the user.  Typically, these macros
25141 are provided by a file @file{package.m4} built by @command{make}
25142 (@pxref{Making testsuite Scripts}), in order to inherit the package
25143 name, version, and bug reporting address from @file{configure.ac}.
25144 @end defmac
25146 @defmac AT_COPYRIGHT (@var{copyright-notice})
25147 @atindex{COPYRIGHT}
25148 @cindex Copyright Notice
25149 State that, in addition to the Free Software Foundation's copyright on
25150 the Autotest macros, parts of your test suite are covered by
25151 @var{copyright-notice}.
25153 The @var{copyright-notice} shows up in both the head of
25154 @command{testsuite} and in @samp{testsuite --version}.
25155 @end defmac
25157 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25158   @ovar{action-if-given}, @ovar{action-if-not-given})
25159 @atindex{ARG_OPTION}
25160 @vrindex at_arg_@var{option}
25161 Accept options from the space-separated list @var{options}, a list that
25162 has leading dashes removed from the options.  Long options will be
25163 prefixed with @samp{--}, single-character options with @samp{-}.  The
25164 first word in this list is the primary @var{option}, any others are
25165 assumed to be short-hand aliases.  The variable associated with it
25166 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25167 with underscores.
25169 If the user passes @option{--@var{option}} to the @command{testsuite},
25170 the variable will be set to @samp{:}.  If the user does not pass the
25171 option, or passes @option{--no-@var{option}}, then the variable will be
25172 set to @samp{false}.
25174 @vrindex at_optarg
25175 @vrindex at_optarg_@var{option}
25176 @var{action-if-given} is run each time the option is encountered; here,
25177 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25178 appropriate.  @code{at_optarg} is actually just a copy of
25179 @code{at_arg_@var{option}}.
25181 @var{action-if-not-given} will be run once after option parsing is
25182 complete and if no option from @var{options} was used.
25184 @var{help-text} is added to the end of the list of options shown in
25185 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25187 It is recommended that you use a package-specific prefix to @var{options}
25188 names in order to avoid clashes with future Autotest built-in options.
25189 @end defmac
25191 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25192   @ovar{action-if-given}, @ovar{action-if-not-given})
25193 @atindex{ARG_OPTION_ARG}
25194 @vrindex at_arg_@var{option}
25195 Accept options with arguments from the space-separated list
25196 @var{options}, a list that has leading dashes removed from the options.
25197 Long options will be prefixed with @samp{--}, single-character options
25198 with @samp{-}.  The first word in this list is the primary @var{option},
25199 any others are assumed to be short-hand aliases.  The variable associated
25200 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25201 replaced with underscores.
25203 If the user passes @option{--@var{option}=@var{arg}} or
25204 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25205 variable will be set to @samp{@var{arg}}.
25207 @vrindex at_optarg
25208 @var{action-if-given} is run each time the option is encountered; here,
25209 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25210 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25212 @var{action-if-not-given} will be run once after option parsing is
25213 complete and if no option from @var{options} was used.
25215 @var{help-text} is added to the end of the list of options shown in
25216 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25218 It is recommended that you use a package-specific prefix to @var{options}
25219 names in order to avoid clashes with future Autotest built-in options.
25220 @end defmac
25222 @defmac AT_COLOR_TESTS
25223 @atindex{COLOR_TESTS}
25224 Enable colored test results by default when the output is connected to
25225 a terminal.
25226 @end defmac
25228 @defmac AT_TESTED (@var{executables})
25229 @atindex{TESTED}
25230 Log the file name and answer to @option{--version} of each program in
25231 space-separated list @var{executables}.  Several invocations register
25232 new executables, in other words, don't fear registering one program
25233 several times.
25235 Autotest test suites rely on @env{PATH} to find the tested program.
25236 This avoids the need to generate absolute names of the various tools, and
25237 makes it possible to test installed programs.  Therefore, knowing which
25238 programs are being exercised is crucial to understanding problems in
25239 the test suite itself, or its occasional misuses.  It is a good idea to
25240 also subscribe foreign programs you depend upon, to avoid incompatible
25241 diagnostics.
25243 @var{executables} is implicitly wrapped in shell double quotes, but it
25244 will still use shell variable expansion (@samp{$}), command substitution
25245 (@samp{`}), and backslash escaping (@samp{\}).  In particular, the
25246 @env{EXEEXT} variable is available if it is passed to the testsuite
25247 via @file{atlocal} or @file{atconfig}.
25248 @end defmac
25250 @sp 1
25252 @defmac AT_BANNER (@var{test-category-name})
25253 @atindex{BANNER}
25254 This macro identifies the start of a category of related test groups.
25255 When the resulting @file{testsuite} is invoked with more than one test
25256 group to run, its output will include a banner containing
25257 @var{test-category-name} prior to any tests run from that category.  The
25258 banner should be no more than about 40 or 50 characters.  A blank banner
25259 indicates uncategorized tests; an empty line will be inserted after
25260 tests from an earlier category, effectively ending that category.
25261 @end defmac
25263 @defmac AT_SETUP (@var{test-group-name})
25264 @atindex{SETUP}
25265 This macro starts a group of related tests, all to be executed in the
25266 same subshell.  It accepts a single argument, which holds a few words
25267 (no more than about 30 or 40 characters) quickly describing the purpose
25268 of the test group being started.  @var{test-group-name} must not expand
25269 to unbalanced quotes, although quadrigraphs can be used.
25270 @end defmac
25272 @defmac AT_KEYWORDS (@var{keywords})
25273 @atindex{KEYWORDS}
25274 Associate the space-separated list of @var{keywords} to the enclosing
25275 test group.  This makes it possible to run ``slices'' of the test suite.
25276 For instance, if some of your test groups exercise some @samp{foo}
25277 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25278 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25279 @var{test-group-name} of the test group is automatically recorded to
25280 @code{AT_KEYWORDS}.
25282 Several invocations within a test group accumulate new keywords.  In
25283 other words, don't fear registering the same keyword several times in a
25284 test group.
25285 @end defmac
25287 @defmac AT_CAPTURE_FILE (@var{file})
25288 @atindex{CAPTURE_FILE}
25289 If the current test group fails, log the contents of @var{file}.
25290 Several identical calls within one test group have no additional effect.
25291 @end defmac
25293 @defmac AT_FAIL_IF (@var{shell-condition})
25294 @atindex{FAIL_IF}
25295 Make the test group fail and skip the rest of its execution, if
25296 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25297 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25298 will be executed and may still cause the test group to be skipped.
25299 You can instantiate this macro many times from within the same test group.
25301 You should use this macro only for very simple failure conditions.  If the
25302 @var{shell-condition} could emit any kind of output you should instead
25303 use @command{AT_CHECK} like
25304 @example
25305 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25306 @end example
25307 @noindent
25308 so that such output is properly recorded in the @file{testsuite.log}
25309 file.
25310 @end defmac
25312 @defmac AT_SKIP_IF (@var{shell-condition})
25313 @atindex{SKIP_IF}
25314 Determine whether the test should be skipped because it requires
25315 features that are unsupported on the machine under test.
25316 @var{shell-condition} is a shell expression such as a @code{test}
25317 command.  Tests before @command{AT_SKIP_IF} will be executed
25318 and may still cause the test group to fail.  You can instantiate this
25319 macro many times from within the same test group.
25321 You should use this macro only for very simple skip conditions.  If the
25322 @var{shell-condition} could emit any kind of output you should instead
25323 use @command{AT_CHECK} like
25324 @example
25325 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25326 @end example
25327 @noindent
25328 so that such output is properly recorded in the @file{testsuite.log}
25329 file.
25330 @end defmac
25332 @defmac AT_XFAIL_IF (@var{shell-condition})
25333 @atindex{XFAIL_IF}
25334 Determine whether the test is expected to fail because it is a known
25335 bug (for unsupported features, you should skip the test).
25336 @var{shell-condition} is a shell expression such as a @code{test}
25337 command; you can instantiate this macro many times from within the
25338 same test group, and one of the conditions is enough to turn
25339 the test into an expected failure.
25340 @end defmac
25342 @defmac AT_CLEANUP
25343 @atindex{CLEANUP}
25344 End the current test group.
25345 @end defmac
25347 @sp 1
25349 @defmac AT_DATA (@var{file}, @var{contents})
25350 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25351 @atindex{DATA}
25352 Initialize an input data @var{file} with given @var{contents}.  Of
25353 course, the @var{contents} have to be properly quoted between square
25354 brackets to protect against included commas or spurious M4
25355 expansion.  @var{contents} must be empty or end with a newline.
25356 @var{file} must
25357 be a single shell word that expands into a single file name.
25359 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25360 that only the latter performs shell variable expansion (@samp{$}),
25361 command substitution (@samp{`}), and backslash escaping (@samp{\})
25362 on @var{contents}.
25363 @end defmac
25365 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25366   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25367 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25368   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25369 @atindex{CHECK}
25370 @atindex{CHECK_UNQUOTED}
25371 @vrindex at_status
25372 Execute a test by performing given shell @var{commands} in a subshell.
25373 @var{commands} is output as-is, so shell expansions are honored.  These
25374 commands should normally exit with @var{status}, while producing expected
25375 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25376 unexpected status 77, then the rest of the test group is skipped.  If
25377 @var{commands} exit with unexpected status 99, then the test group is
25378 immediately failed.  Otherwise, if this test fails, run shell commands
25379 @var{run-if-fail} or, if this test passes, run shell commands
25380 @var{run-if-pass}, both inside the current shell execution environment.
25381 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25382 @var{commands} is available in the @code{at_status} shell variable.
25384 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25386 If @var{status} is the literal @samp{ignore}, then the corresponding
25387 exit status is not checked, except for the special cases of 77 (skip)
25388 and 99 (hard failure).  The existence of hard failures allows one to
25389 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25390 feature has not yet been implemented, but to still distinguish between
25391 gracefully handling the missing feature and dumping core.  A hard
25392 failure also inhibits post-test actions in @var{run-if-fail}.
25394 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25395 literals in the following table, then the test treats the output
25396 according to the rules of that literal.  Otherwise, the value of the
25397 parameter is treated as text that must exactly match the output given by
25398 @var{commands} on standard output and standard error (including an empty
25399 parameter for no output); any differences are captured in the testsuite
25400 log and the test is failed (unless an unexpected exit status of 77
25401 skipped the test instead).  The difference between @code{AT_CHECK} and
25402 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25403 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25404 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25405 @var{stderr} arguments; if the text includes a trailing newline, this
25406 would be the same as if it were specified via an unquoted
25407 here-document.  (However, there is no difference in the interpretation
25408 of @var{commands}).
25410 @table @samp
25411 @item ignore
25412 The content of the output is ignored, but still captured in the test
25413 group log (if the testsuite is run with option @option{-v}, the test
25414 group log is displayed as the test is run; if the test group later
25415 fails, the test group log is also copied into the overall testsuite
25416 log).  This action is valid for both @var{stdout} and @var{stderr}.
25418 @item ignore-nolog
25419 The content of the output is ignored, and nothing is captured in the log
25420 files.  If @var{commands} are likely to produce binary output (including
25421 long lines) or large amounts of output, then logging the output can make
25422 it harder to locate details related to subsequent tests within the
25423 group, and could potentially corrupt terminal display of a user running
25424 @command{testsuite -v}.
25426 @item stdout
25427 For the @var{stdout} parameter, capture the content of standard output
25428 to both the file @file{stdout} and the test group log.  Subsequent
25429 commands in the test group can then post-process the file.  This action
25430 is often used when it is desired to use @command{grep} to look for a
25431 substring in the output, or when the output must be post-processed to
25432 normalize error messages into a common form.
25434 @item stderr
25435 Like @samp{stdout}, except that it only works for the @var{stderr}
25436 parameter, and the standard error capture file will be named
25437 @file{stderr}.
25439 @item stdout-nolog
25440 @itemx stderr-nolog
25441 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25442 not duplicated into the test group log.  This action is particularly
25443 useful for an intermediate check that produces large amounts of data,
25444 which will be followed by another check that filters down to the
25445 relevant data, as it makes it easier to locate details in the log.
25447 @item expout
25448 For the @var{stdout} parameter, compare standard output contents with
25449 the previously created file @file{expout}, and list any differences in
25450 the testsuite log.
25452 @item experr
25453 Like @samp{expout}, except that it only works for the @var{stderr}
25454 parameter, and the standard error contents are compared with
25455 @file{experr}.
25456 @end table
25457 @end defmac
25459 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25460   @ovar{run-if-fail}, @ovar{run-if-pass})
25461 @atindex{CHECK_EUNIT}
25462 Initialize and execute an Erlang module named @var{module} that performs
25463 tests following the @var{test-spec} EUnit test specification.
25464 @var{test-spec} must be a valid EUnit test specification, as defined in
25465 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25466 Reference Manual}.  @var{erlflags} are optional command-line options
25467 passed to the Erlang interpreter to execute the test Erlang module.
25468 Typically, @var{erlflags} defines at least the paths to directories
25469 containing the compiled Erlang modules under test, as @samp{-pa path1
25470 path2 ...}.
25472 For example, the unit tests associated with Erlang module @samp{testme},
25473 which compiled code is in subdirectory @file{src}, can be performed
25474 with:
25476 @example
25477 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25478                [-pa "$@{abs_top_builddir@}/src"])
25479 @end example
25481 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25483 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25484 must be defined as the path of the Erlang interpreter, the path of the
25485 Erlang compiler, and the command-line flags to pass to the compiler,
25486 respectively.  Those variables should be configured in
25487 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25488 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25489 variables are automatically defined in the testsuite.  If @code{ERL} or
25490 @code{ERLC} is not defined, the test group is skipped.
25492 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25493 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25494 an invalid EUnit test specification, the test group fails.  Otherwise,
25495 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25496 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25497 executed and the test group fails.
25499 Only the generated test Erlang module is automatically compiled and
25500 executed.  If @var{test-spec} involves testing other Erlang modules,
25501 e.g. module @samp{testme} in the example above, those modules must be
25502 already compiled.
25504 If the testsuite is run in verbose mode, with option @option{--verbose},
25505 EUnit is also run in verbose mode to output more details about
25506 individual unit tests.
25507 @end defmac
25510 @node testsuite Invocation
25511 @section Running @command{testsuite} Scripts
25512 @cindex @command{testsuite}
25514 Autotest test suites support the following options:
25516 @table @option
25517 @item --help
25518 @itemx -h
25519 Display the list of options and exit successfully.
25521 @item --version
25522 @itemx -V
25523 Display the version of the test suite and exit successfully.
25525 @item --directory=@var{dir}
25526 @itemx -C @var{dir}
25527 Change the current directory to @var{dir} before creating any files.
25528 Useful for running the testsuite in a subdirectory from a top-level
25529 Makefile.
25531 @item --jobs@r{[}=@var{n}@r{]}
25532 @itemx -j@ovar{n}
25533 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25534 run all given tests in parallel.  Note that there should be no space
25535 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25536 the separate arguments @option{-j} and @option{@var{number}}, see below.
25538 In parallel mode, the standard input device of the testsuite script is
25539 not available to commands inside a test group.  Furthermore, banner
25540 lines are not printed, and the summary line for each test group is
25541 output after the test group completes.  Summary lines may appear
25542 unordered.  If verbose and trace output are enabled (see below), they
25543 may appear intermixed from concurrently running tests.
25545 Parallel mode requires the @command{mkfifo} command to work, and will be
25546 silently disabled otherwise.
25548 @item --clean
25549 @itemx -c
25550 Remove all the files the test suite might have created and exit.  Meant
25551 for @code{clean} Make targets.
25553 @item --list
25554 @itemx -l
25555 List all the tests (or only the selection), including their possible
25556 keywords.
25557 @end table
25559 @sp 1
25561 By default all tests are performed (or described with @option{--list})
25562 silently in the default environment, but the environment, set of tests,
25563 and verbosity level can be tuned:
25565 @table @samp
25566 @item @var{variable}=@var{value}
25567 Set the environment @var{variable} to @var{value}.  Use this rather
25568 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25569 different environment.
25571 @cindex @code{AUTOTEST_PATH}
25572 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25573 to @env{PATH}.  Relative directory names (not starting with
25574 @samp{/}) are considered to be relative to the top level of the
25575 package being built.  All directories are made absolute, first
25576 starting from the top level @emph{build} tree, then from the
25577 @emph{source} tree.  For instance @samp{./testsuite
25578 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25579 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25580 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25581 @env{PATH}.
25583 @item @var{number}
25584 @itemx @var{number}-@var{number}
25585 @itemx @var{number}-
25586 @itemx -@var{number}
25587 Add the corresponding test groups, with obvious semantics, to the
25588 selection.
25590 @item --keywords=@var{keywords}
25591 @itemx -k @var{keywords}
25592 Add to the selection the test groups with title or keywords (arguments
25593 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25594 of the comma separated list @var{keywords}, case-insensitively.  Use
25595 @samp{!} immediately before the keyword to invert the selection for this
25596 keyword.  By default, the keywords match whole words; enclose them in
25597 @samp{.*} to also match parts of words.
25599 For example, running
25601 @example
25602 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25603 @end example
25605 @noindent
25606 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25607 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25608 etc.), while
25610 @example
25611 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25612 @end example
25614 @noindent
25615 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25616 containing @samp{FUNC}.
25618 @item --errexit
25619 @itemx -e
25620 If any test fails, immediately abort testing.  This implies
25621 @option{--debug}: post test group clean up, and top-level logging
25622 are inhibited.  This option is meant for the full test
25623 suite, it is not really useful for generated debugging scripts.
25624 If the testsuite is run in parallel mode using @option{--jobs},
25625 then concurrently running tests will finish before exiting.
25627 @item --verbose
25628 @itemx -v
25629 Force more verbosity in the detailed output of what is being done.  This
25630 is the default for debugging scripts.
25632 @item --color
25633 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25634 Enable colored test results.  Without an argument, or with @samp{always},
25635 test results will be colored.  With @samp{never}, color mode is turned
25636 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25637 the testsuite author, or the argument @samp{auto} is given, then test
25638 results are colored if standard output is connected to a terminal.
25640 @item --debug
25641 @itemx -d
25642 Do not remove the files after a test group was performed---but they are
25643 still removed @emph{before}, therefore using this option is sane when
25644 running several test groups.  Create debugging scripts.  Do not
25645 overwrite the top-level
25646 log (in order to preserve a supposedly existing full log file).  This is
25647 the default for debugging scripts, but it can also be useful to debug
25648 the testsuite itself.
25650 @item --recheck
25651 Add to the selection all test groups that failed or passed unexpectedly
25652 during the last non-debugging test run.
25654 @item --trace
25655 @itemx -x
25656 Trigger shell tracing of the test groups.
25657 @end table
25659 Besides these options accepted by every Autotest testsuite, the
25660 testsuite author might have added package-specific options
25661 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25662 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25663 the package documentation for details.
25666 @node Making testsuite Scripts
25667 @section Making @command{testsuite} Scripts
25669 For putting Autotest into movement, you need some configuration and
25670 makefile machinery.  We recommend, at least if your package uses deep or
25671 shallow hierarchies, that you use @file{tests/} as the name of the
25672 directory holding all your tests and their makefile.  Here is a
25673 check list of things to do, followed by an example, taking into
25674 consideration whether you are also using Automake.
25676 @itemize @minus
25678 @item
25679 @cindex @file{package.m4}
25680 @atindex{PACKAGE_STRING}
25681 @atindex{PACKAGE_BUGREPORT}
25682 @atindex{PACKAGE_NAME}
25683 @atindex{PACKAGE_TARNAME}
25684 @atindex{PACKAGE_VERSION}
25685 @atindex{PACKAGE_URL}
25686 Make sure to create the file @file{package.m4}, which defines the
25687 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25688 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25689 address to which bug reports should be sent.  For sake of completeness,
25690 we suggest that you also define @code{AT_PACKAGE_NAME},
25691 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25692 @code{AT_PACKAGE_URL}.
25693 @xref{Initializing configure}, for a description of these variables.
25694 Be sure to distribute @file{package.m4} and to put it into the source
25695 hierarchy: the test suite ought to be shipped!  See below for an example.
25697 @item
25698 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25700 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25701 @acindex{CONFIG_TESTDIR}
25702 An Autotest test suite is to be configured in @var{directory}.  This
25703 macro causes @file{@var{directory}/atconfig} to be created by
25704 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25705 @var{test-path} (@pxref{testsuite Invocation}).
25706 @end defmac
25708 @item
25709 Still within @file{configure.ac}, as appropriate, ensure that some
25710 @code{AC_CONFIG_FILES} command includes substitution for
25711 @file{tests/atlocal}.
25713 @item
25714 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25715 variable to be set.
25717 @item
25718 The appropriate @file{Makefile} should be modified so the validation in
25719 your package is triggered by @samp{make check}.
25720 @end itemize
25722 The following example demonstrates the above checklist, first by
25723 assuming that you are using Automake (see below for tweaks to make to
25724 get the same results without Automake).  Begin by adding the following
25725 lines to your @file{configure.ac}:
25727 @example
25728 # Initialize the test suite.
25729 AC_CONFIG_TESTDIR([tests])
25730 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25731 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25732 @end example
25734 Next, add the following lines to your @file{tests/Makefile.am}, in order
25735 to link @samp{make check} with a validation suite.
25737 @example
25738 # The `:;' works around a Bash 3.2 bug when the output is not writable.
25739 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25740         :;@{ \
25741           echo '# Signature of the current package.' && \
25742           echo 'm4_define([AT_PACKAGE_NAME],' && \
25743           echo '  [$(PACKAGE_NAME)])' && \
25744           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25745           echo '  [$(PACKAGE_TARNAME)])' && \
25746           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25747           echo '  [$(PACKAGE_VERSION)])' && \
25748           echo 'm4_define([AT_PACKAGE_STRING],' && \
25749           echo '  [$(PACKAGE_STRING)])' && \
25750           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25751           echo '  [$(PACKAGE_BUGREPORT)])'; \
25752           echo 'm4_define([AT_PACKAGE_URL],' && \
25753           echo '  [$(PACKAGE_URL)])'; \
25754         @} >'$(srcdir)/package.m4'
25756 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25757 TESTSUITE = $(srcdir)/testsuite
25759 check-local: atconfig atlocal $(TESTSUITE)
25760         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25762 installcheck-local: atconfig atlocal $(TESTSUITE)
25763         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25764           $(TESTSUITEFLAGS)
25766 clean-local:
25767         test ! -f '$(TESTSUITE)' || \
25768          $(SHELL) '$(TESTSUITE)' --clean
25770 AUTOTEST = $(AUTOM4TE) --language=autotest
25771 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25772         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25773         mv $@@.tmp $@@
25774 @end example
25776 Note that the built testsuite is distributed; this is necessary because
25777 users might not have Autoconf installed, and thus would not be able to
25778 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25779 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25780 provide the user with
25781 a nicer error message if they modify a source file to the testsuite, and
25782 accidentally trigger the rebuild rules.
25784 You might want to list explicitly the dependencies, i.e., the list of
25785 the files @file{testsuite.at} includes.
25787 If you don't use Automake, you should make the following tweaks.  In
25788 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25789 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
25790 welcome to also try using the @command{missing} script from the Automake
25791 project instead of @command{false}, to try to get a nicer error message
25792 when the user modifies prerequisites but did not have Autoconf
25793 installed, but at that point you may be better off using Automake.
25794 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25795 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
25796 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25797 distributed, as well as adding the following additional lines to prepare
25798 the set of needed Makefile variables:
25800 @example
25801 subdir = tests
25802 PACKAGE_NAME = @@PACKAGE_NAME@@
25803 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25804 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25805 PACKAGE_STRING = @@PACKAGE_STRING@@
25806 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25807 PACKAGE_URL = @@PACKAGE_URL@@
25808 AUTOM4TE = @@AUTOM4TE@@
25810 atconfig: $(top_builddir)/config.status
25811         cd $(top_builddir) && \
25812            $(SHELL) ./config.status $(subdir)/$@@
25814 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25815         cd $(top_builddir) && \
25816            $(SHELL) ./config.status $(subdir)/$@@
25817 @end example
25819 Using the above example (with or without Automake), and assuming you
25820 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25821 makefile, you can now fine-tune test suite execution at runtime by
25822 altering this variable, for example:
25824 @example
25825 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25826 @end example
25830 @c =============================== Frequent Autoconf Questions, with answers
25832 @node FAQ
25833 @chapter Frequent Autoconf Questions, with answers
25835 Several questions about Autoconf come up occasionally.  Here some of them
25836 are addressed.
25838 @menu
25839 * Distributing::                Distributing @command{configure} scripts
25840 * Why GNU M4::                  Why not use the standard M4?
25841 * Bootstrapping::               Autoconf and GNU M4 require each other?
25842 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25843 * Defining Directories::        Passing @code{datadir} to program
25844 * Autom4te Cache::              What is it?  Can I remove it?
25845 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25846 * Expanded Before Required::    Expanded Before Required
25847 * Debugging::                   Debugging @command{configure} scripts
25848 @end menu
25850 @node Distributing
25851 @section Distributing @command{configure} Scripts
25852 @cindex License
25854 @display
25855 What are the restrictions on distributing @command{configure}
25856 scripts that Autoconf generates?  How does that affect my
25857 programs that use them?
25858 @end display
25860 There are no restrictions on how the configuration scripts that Autoconf
25861 produces may be distributed or used.  In Autoconf version 1, they were
25862 covered by the GNU General Public License.  We still encourage
25863 software authors to distribute their work under terms like those of the
25864 GPL, but doing so is not required to use Autoconf.
25866 Of the other files that might be used with @command{configure},
25867 @file{config.h.in} is under whatever copyright you use for your
25868 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25869 exception to the GPL when they are used with an Autoconf-generated
25870 @command{configure} script, which permits you to distribute them under the
25871 same terms as the rest of your package.  @file{install-sh} is from the X
25872 Consortium and is not copyrighted.
25874 @node Why GNU M4
25875 @section Why Require GNU M4?
25877 @display
25878 Why does Autoconf require GNU M4?
25879 @end display
25881 Many M4 implementations have hard-coded limitations on the size and
25882 number of macros that Autoconf exceeds.  They also lack several
25883 builtin macros that it would be difficult to get along without in a
25884 sophisticated application like Autoconf, including:
25886 @example
25887 m4_builtin
25888 m4_indir
25889 m4_bpatsubst
25890 __file__
25891 __line__
25892 @end example
25894 Autoconf requires version 1.4.6 or later of GNU M4.
25896 Since only software maintainers need to use Autoconf, and since GNU
25897 M4 is simple to configure and install, it seems reasonable to require
25898 GNU M4 to be installed also.  Many maintainers of GNU and
25899 other free software already have most of the GNU utilities
25900 installed, since they prefer them.
25902 @node Bootstrapping
25903 @section How Can I Bootstrap?
25904 @cindex Bootstrap
25906 @display
25907 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25908 @command{configure} script, how do I bootstrap?  It seems like a chicken
25909 and egg problem!
25910 @end display
25912 This is a misunderstanding.  Although GNU M4 does come with a
25913 @command{configure} script produced by Autoconf, Autoconf is not required
25914 in order to run the script and install GNU M4.  Autoconf is only
25915 required if you want to change the M4 @command{configure} script, which few
25916 people have to do (mainly its maintainer).
25918 @node Why Not Imake
25919 @section Why Not Imake?
25920 @cindex Imake
25922 @display
25923 Why not use Imake instead of @command{configure} scripts?
25924 @end display
25926 Several people have written addressing this question, so
25927 adaptations of their explanations are included here.
25929 The following answer is based on one written by Richard Pixley:
25931 @quotation
25932 Autoconf generated scripts frequently work on machines that it has
25933 never been set up to handle before.  That is, it does a good job of
25934 inferring a configuration for a new system.  Imake cannot do this.
25936 Imake uses a common database of host specific data.  For X11, this makes
25937 sense because the distribution is made as a collection of tools, by one
25938 central authority who has control over the database.
25940 GNU tools are not released this way.  Each GNU tool has a
25941 maintainer; these maintainers are scattered across the world.  Using a
25942 common database would be a maintenance nightmare.  Autoconf may appear
25943 to be this kind of database, but in fact it is not.  Instead of listing
25944 host dependencies, it lists program requirements.
25946 If you view the GNU suite as a collection of native tools, then the
25947 problems are similar.  But the GNU development tools can be
25948 configured as cross tools in almost any host+target permutation.  All of
25949 these configurations can be installed concurrently.  They can even be
25950 configured to share host independent files across hosts.  Imake doesn't
25951 address these issues.
25953 Imake templates are a form of standardization.  The GNU coding
25954 standards address the same issues without necessarily imposing the same
25955 restrictions.
25956 @end quotation
25959 Here is some further explanation, written by Per Bothner:
25961 @quotation
25962 One of the advantages of Imake is that it is easy to generate large
25963 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25964 However, @code{cpp} is not programmable: it has limited conditional
25965 facilities, and no looping.  And @code{cpp} cannot inspect its
25966 environment.
25968 All of these problems are solved by using @code{sh} instead of
25969 @code{cpp}.  The shell is fully programmable, has macro substitution,
25970 can execute (or source) other shell scripts, and can inspect its
25971 environment.
25972 @end quotation
25975 Paul Eggert elaborates more:
25977 @quotation
25978 With Autoconf, installers need not assume that Imake itself is already
25979 installed and working well.  This may not seem like much of an advantage
25980 to people who are accustomed to Imake.  But on many hosts Imake is not
25981 installed or the default installation is not working well, and requiring
25982 Imake to install a package hinders the acceptance of that package on
25983 those hosts.  For example, the Imake template and configuration files
25984 might not be installed properly on a host, or the Imake build procedure
25985 might wrongly assume that all source files are in one big directory
25986 tree, or the Imake configuration might assume one compiler whereas the
25987 package or the installer needs to use another, or there might be a
25988 version mismatch between the Imake expected by the package and the Imake
25989 supported by the host.  These problems are much rarer with Autoconf,
25990 where each package comes with its own independent configuration
25991 processor.
25993 Also, Imake often suffers from unexpected interactions between
25994 @command{make} and the installer's C preprocessor.  The fundamental problem
25995 here is that the C preprocessor was designed to preprocess C programs,
25996 not makefiles.  This is much less of a problem with Autoconf,
25997 which uses the general-purpose preprocessor M4, and where the
25998 package's author (rather than the installer) does the preprocessing in a
25999 standard way.
26000 @end quotation
26003 Finally, Mark Eichin notes:
26005 @quotation
26006 Imake isn't all that extensible, either.  In order to add new features to
26007 Imake, you need to provide your own project template, and duplicate most
26008 of the features of the existing one.  This means that for a sophisticated
26009 project, using the vendor-provided Imake templates fails to provide any
26010 leverage---since they don't cover anything that your own project needs
26011 (unless it is an X11 program).
26013 On the other side, though:
26015 The one advantage that Imake has over @command{configure}:
26016 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
26017 than @file{Makefile.in} files.  There is a fix to this, however---at least
26018 for the Kerberos V5 tree, we've modified things to call in common
26019 @file{post.in} and @file{pre.in} makefile fragments for the
26020 entire tree.  This means that a lot of common things don't have to be
26021 duplicated, even though they normally are in @command{configure} setups.
26022 @end quotation
26025 @node Defining Directories
26026 @section How Do I @code{#define} Installation Directories?
26028 @display
26029 My program needs library files, installed in @code{datadir} and
26030 similar.  If I use
26032 @example
26033 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
26034   [Define to the read-only architecture-independent
26035    data directory.])
26036 @end example
26038 @noindent
26039 I get
26041 @example
26042 #define DATADIR "$@{prefix@}/share"
26043 @end example
26044 @end display
26046 As already explained, this behavior is on purpose, mandated by the
26047 GNU Coding Standards, see @ref{Installation Directory
26048 Variables}.  There are several means to achieve a similar goal:
26050 @itemize @minus
26051 @item
26052 Do not use @code{AC_DEFINE} but use your makefile to pass the
26053 actual value of @code{datadir} via compilation flags.
26054 @xref{Installation Directory Variables}, for the details.
26056 @item
26057 This solution can be simplified when compiling a program: you may either
26058 extend the @code{CPPFLAGS}:
26060 @example
26061 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26062 @end example
26064 @noindent
26065 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26067 @example
26068 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26069 @end example
26071 @noindent
26072 Alternatively, create a dedicated header file:
26074 @example
26075 DISTCLEANFILES = myprog-paths.h
26076 myprog-paths.h: Makefile
26077         echo '#define DATADIR "$(datadir)"' >$@@
26078 @end example
26080 @noindent
26081 The gnulib module @samp{configmake} provides such a header with all the
26082 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26083 Gnulib}.
26085 @item
26086 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26087 value of @code{datadir} and others.  Many people have wrapped macros to
26088 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26089 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26090 Archive}.
26092 This solution does not conform to the GNU Coding Standards.
26094 @item
26095 Note that all the previous solutions hard wire the absolute name of
26096 these directories in the executables, which is not a good property.  You
26097 may try to compute the names relative to @code{prefix}, and try to
26098 find @code{prefix} at runtime, this way your package is relocatable.
26099 @end itemize
26102 @node Autom4te Cache
26103 @section What is @file{autom4te.cache}?
26105 @display
26106 What is this directory @file{autom4te.cache}?  Can I safely remove it?
26107 @end display
26109 In the GNU Build System, @file{configure.ac} plays a central
26110 role and is read by many tools: @command{autoconf} to create
26111 @file{configure}, @command{autoheader} to create @file{config.h.in},
26112 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26113 check the completeness of @file{configure.ac}, @command{autoreconf} to
26114 check the GNU Build System components that are used.  To
26115 ``read @file{configure.ac}'' actually means to compile it with M4,
26116 which can be a long process for complex @file{configure.ac}.
26118 This is why all these tools, instead of running directly M4, invoke
26119 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26120 a specific demand, stores additional information in
26121 @file{autom4te.cache} for future runs.  For instance, if you run
26122 @command{autoconf}, behind the scenes, @command{autom4te} also
26123 stores information for the other tools, so that when you invoke
26124 @command{autoheader} or @command{automake} etc., reprocessing
26125 @file{configure.ac} is not needed.  The speed up is frequently 30%,
26126 and is increasing with the size of @file{configure.ac}.
26128 But it is and remains being simply a cache: you can safely remove it.
26130 @sp 1
26132 @display
26133 Can I permanently get rid of it?
26134 @end display
26136 The creation of this cache can be disabled from
26137 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26138 details.  You should be aware that disabling the cache slows down the
26139 Autoconf test suite by 40%.  The more GNU Build System
26140 components are used, the more the cache is useful; for instance
26141 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26142 the cache @emph{although @option{--force} implies that the cache is
26143 not fully exploited}, and eight times slower than without
26144 @option{--force}.
26147 @node Present But Cannot Be Compiled
26148 @section Header Present But Cannot Be Compiled
26150 The most important guideline to bear in mind when checking for
26151 features is to mimic as much as possible the intended use.
26152 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26153 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26154 the preprocessor, instead of the compiler, to check for headers.  As a
26155 result, incompatibilities between headers went unnoticed during
26156 configuration, and maintainers finally had to deal with this issue
26157 elsewhere.
26159 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
26160 checks are performed, and @command{configure} complains loudly if the
26161 compiler and the preprocessor do not agree.  However, only the compiler
26162 result is considered.  As of Autoconf 2.70, only the compiler check is
26163 performed.
26165 Consider the following example:
26167 @smallexample
26168 $ @kbd{cat number.h}
26169 typedef int number;
26170 $ @kbd{cat pi.h}
26171 const number pi = 3;
26172 $ @kbd{cat configure.ac}
26173 AC_INIT([Example], [1.0], [bug-example@@example.org])
26174 AC_CHECK_HEADERS([pi.h])
26175 $ @kbd{autoconf -Wall}
26176 $ @kbd{./configure CPPFLAGS='-I.'}
26177 checking for gcc... gcc
26178 checking whether the C compiler works... yes
26179 checking for C compiler default output file name... a.out
26180 checking for suffix of executables...
26181 checking whether we are cross compiling... no
26182 checking for suffix of object files... o
26183 checking whether the compiler supports GNU C... yes
26184 checking whether gcc accepts -g... yes
26185 checking for gcc option to enable C11 features... -std=gnu11
26186 checking for sys/types.h... yes
26187 checking for sys/stat.h... yes
26188 checking for strings.h... yes
26189 checking for inttypes.h... yes
26190 checking for stdint.h... yes
26191 checking for unistd.h... yes
26192 checking for pi.h... no
26193 @end smallexample
26195 @noindent
26196 The proper way to handle this case is using the fourth argument
26197 (@pxref{Generic Headers}):
26199 @example
26200 $ @kbd{cat configure.ac}
26201 AC_INIT([Example], [1.0], [bug-example@@example.org])
26202 AC_CHECK_HEADERS([number.h pi.h], [], [],
26203 [[#ifdef HAVE_NUMBER_H
26204 # include <number.h>
26205 #endif
26207 $ @kbd{autoconf -Wall}
26208 $ @kbd{./configure CPPFLAGS='-I.'}
26209 checking for gcc... gcc
26210 checking whether the C compiler works... yes
26211 checking for C compiler default output file name... a.out
26212 checking for suffix of executables...
26213 checking whether we are cross compiling... no
26214 checking for suffix of object files... o
26215 checking whether the compiler supports GNU C... yes
26216 checking whether gcc accepts -g... yes
26217 checking for gcc option to enable C11 features... -std=gnu11
26218 checking for number.h... yes
26219 checking for pi.h... yes
26220 @end example
26222 See @ref{Particular Headers}, for a list of headers with their
26223 prerequisites.
26225 @node Expanded Before Required
26226 @section Expanded Before Required
26228 @cindex expanded before required
26229 Older versions of Autoconf silently built files with incorrect ordering
26230 between dependent macros if an outer macro first expanded, then later
26231 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26232 situation no longer generates out-of-order code, but results in
26233 duplicate output and a syntax warning:
26235 @example
26236 $ @kbd{cat configure.ac}
26237 @result{}AC_DEFUN([TESTA], [[echo in A
26238 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26239 @result{}SEEN_A=:]])
26240 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26241 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26242 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26243 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26244 @result{}TESTA
26245 @result{}TESTC])
26246 @result{}AC_INIT
26247 @result{}OUTER
26248 @result{}AC_OUTPUT
26249 $ @kbd{autoconf}
26250 @result{}configure.ac:11: warning: AC_REQUIRE:
26251 @result{} `TESTA' was expanded before it was required
26252 @result{}configure.ac:4: TESTB is expanded from...
26253 @result{}configure.ac:6: TESTC is expanded from...
26254 @result{}configure.ac:7: OUTER is expanded from...
26255 @result{}configure.ac:11: the top level
26256 @end example
26258 @noindent
26259 To avoid this warning, decide what purpose the macro in question serves.
26260 If it only needs to be expanded once (for example, if it provides
26261 initialization text used by later macros), then the simplest fix is to
26262 change the macro to be declared with @code{AC_DEFUN_ONCE}
26263 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26264 newer.  A more portable fix is to change all
26265 instances of direct calls to instead go through @code{AC_REQUIRE}
26266 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26267 by arguments or by the current definition of other macros in the m4
26268 environment, then the macro should always be directly expanded instead
26269 of required.
26271 For another case study, consider this example trimmed down from an
26272 actual package.  Originally, the package contained shell code and
26273 multiple macro invocations at the top level of @file{configure.ac}:
26275 @example
26276 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26277 foobar=
26278 AC_PROG_CC
26280 @end example
26282 @noindent
26283 but that was getting complex, so the author wanted to offload some of
26284 the text into a new macro in another file included via
26285 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26286 macro:
26288 @example
26289 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26290 AC_DEFUN([BAR], [
26291 foobar=
26292 AC_PROG_CC
26296 @end example
26298 @noindent
26299 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26300 before the single compiler check, as the author intended.  But with
26301 Autoconf 2.64, this issues the ``expanded before it was required''
26302 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26303 check, one before @samp{foobar=}, and one after.  To understand why this
26304 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26305 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26306 the documented semantics of @code{AC_REQUIRE}, this means that
26307 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26308 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26309 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26310 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26311 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26312 autoconf.  In other words, the author was unknowingly relying on a bug
26313 exploit to get the desired results, and that exploit broke once the bug
26314 was fixed.
26316 So, what recourse does the author have, to restore their intended
26317 semantics of setting @samp{foobar=} prior to a single compiler check,
26318 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26319 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26320 there is always the possibility of using the lower-level
26321 @code{m4_define}:
26323 @example
26324 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26325 m4_define([BAR], [
26326 foobar=
26327 AC_PROG_CC
26331 @end example
26333 @noindent
26334 This works great if everything is in the same file.  However, it does
26335 not help in the case where the author wants to have @command{aclocal}
26336 find the definition of @code{BAR} from its own file, since
26337 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26338 better fix is to recognize that if @code{BAR} also uses
26339 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26340 to a subsequent require.  Then, by creating yet another helper macro,
26341 the author can once again guarantee a single invocation of
26342 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26343 author can also use @code{AC_BEFORE} to make sure no other macro
26344 appearing before @code{BAR} has triggered an unwanted expansion of
26345 @code{AC_PROG_CC}.
26347 @example
26348 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26349 AC_DEFUN([BEFORE_CC], [
26350 foobar=
26352 AC_DEFUN([BAR], [
26353 AC_BEFORE([$0], [AC_PROG_CC])dnl
26354 AC_REQUIRE([BEFORE_CC])dnl
26355 AC_REQUIRE([AC_PROG_CC])dnl
26359 @end example
26362 @node Debugging
26363 @section Debugging @command{configure} scripts
26365 While in general, @command{configure} scripts generated by Autoconf
26366 strive to be fairly portable to various systems, compilers, shells, and
26367 other tools, it may still be necessary to debug a failing test, broken
26368 script or makefile, or fix or override an incomplete, faulty, or erroneous
26369 test, especially during macro development.  Failures can occur at all levels,
26370 in M4 syntax or semantics, shell script issues, or due to bugs in the
26371 test or the tools invoked by @command{configure}.  Together with the
26372 rather arcane error message that @command{m4} and @command{make} may
26373 produce when their input contains syntax errors, this can make debugging
26374 rather painful.
26376 Nevertheless, here is a list of hints and strategies that may help:
26378 @itemize
26379 @item
26380 When @command{autoconf} fails, common causes for error include:
26382 @itemize
26383 @item
26384 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26385 Parentheses}),
26387 @item under- or overquoted macro arguments (@pxref{Autoconf
26388 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26389 Macros}),
26391 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26392 Language}).
26393 @end itemize
26395 Typically, it helps to go back to the last working version of the input
26396 and compare the differences for each of these errors.  Another
26397 possibility is to sprinkle pairs of @code{m4_traceon} and
26398 @code{m4_traceoff} judiciously in the code, either without a parameter
26399 or listing some macro names and watch @command{m4} expand its input
26400 verbosely (@pxref{Debugging via autom4te}).
26402 @item
26403 Sometimes @command{autoconf} succeeds but the generated
26404 @command{configure} script has invalid shell syntax.  You can detect this
26405 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26406 If this command fails, the same tips apply, as if @command{autoconf} had
26407 failed.
26409 @item
26410 Debugging @command{configure} script execution may be done by sprinkling
26411 pairs of @code{set -x} and @code{set +x} into the shell script before
26412 and after the region that contains a bug.  Running the whole script with
26413 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26414 @var{shell} may work, but produces lots of output.  Here, it can help to
26415 search for markers like @samp{checking for} a particular test in the
26416 @var{log-file}.
26418 @item
26419 Alternatively, you might use a shell with debugging capabilities like
26420 @uref{http://bashdb.sourceforge.net/, bashdb}.
26422 @item
26423 When @command{configure} tests produce invalid results for your system,
26424 it may be necessary to override them:
26426 @itemize
26427 @item
26428 For programs, tools or libraries variables, preprocessor, compiler, or
26429 linker flags, it is often sufficient to override them at @command{make}
26430 run time with some care (@pxref{Macros and Submakes}).  Since this
26431 normally won't cause @command{configure} to be run again with these
26432 changed settings, it may fail if the changed variable would have caused
26433 different test results from @command{configure}, so this may work only
26434 for simple differences.
26436 @item
26437 Most tests which produce their result in a substituted variable allow to
26438 override the test by setting the variable on the @command{configure}
26439 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26440 @pxref{Particular Systems}).
26442 @item
26443 Many tests store their result in a cache variable (@pxref{Caching
26444 Results}).  This lets you override them either on the
26445 @command{configure} command line as above, or through a primed cache or
26446 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26447 cache variable is documented with a test macro or may be inferred from
26448 @ref{Cache Variable Names}; the precise semantics of undocumented
26449 variables are often internal details, subject to change.
26450 @end itemize
26452 @item
26453 Alternatively, @command{configure} may produce invalid results because
26454 of uncaught programming errors, in your package or in an upstream
26455 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26456 library with a specified function, always check @file{config.log}.  This
26457 will reveal the exact error that produced the failing result: the
26458 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26459 @end itemize
26461 Conversely, as macro author, you can make it easier for users of your
26462 macro:
26464 @itemize
26465 @item
26466 by minimizing dependencies between tests and between test results as far
26467 as possible,
26469 @item
26470 by using @command{make} variables to factorize and allow
26471 override of settings at @command{make} run time,
26473 @item
26474 by honoring the GNU Coding Standards and not overriding flags
26475 reserved for the user except temporarily during @command{configure}
26476 tests,
26478 @item
26479 by not requiring users of your macro to use the cache variables.
26480 Instead, expose the result of the test via @var{run-if-true} and
26481 @var{run-if-false} parameters.  If the result is not a boolean,
26482 then provide it through documented shell variables.
26483 @end itemize
26486 @c ===================================================== History of Autoconf.
26488 @node History
26489 @chapter History of Autoconf
26490 @cindex History of autoconf
26492 @emph{This chapter was written by the original author, David MacKenzie.}
26494 You may be wondering, Why was Autoconf originally written?  How did it
26495 get into its present form?  (Why does it look like gorilla spit?)  If
26496 you're not wondering, then this chapter contains no information useful
26497 to you, and you might as well skip it.  If you @emph{are} wondering,
26498 then let there be light@enddots{}
26500 @menu
26501 * Genesis::                     Prehistory and naming of @command{configure}
26502 * Exodus::                      The plagues of M4 and Perl
26503 * Leviticus::                   The priestly code of portability arrives
26504 * Numbers::                     Growth and contributors
26505 * Deuteronomy::                 Approaching the promises of easy configuration
26506 @end menu
26508 @node Genesis
26509 @section Genesis
26511 In June 1991 I was maintaining many of the GNU utilities for the
26512 Free Software Foundation.  As they were ported to more platforms and
26513 more programs were added, the number of @option{-D} options that users
26514 had to select in the makefile (around 20) became burdensome.
26515 Especially for me---I had to test each new release on a bunch of
26516 different systems.  So I wrote a little shell script to guess some of
26517 the correct settings for the fileutils package, and released it as part
26518 of fileutils 2.0.  That @command{configure} script worked well enough that
26519 the next month I adapted it (by hand) to create similar @command{configure}
26520 scripts for several other GNU utilities packages.  Brian Berliner
26521 also adapted one of my scripts for his CVS revision control system.
26523 Later that summer, I learned that Richard Stallman and Richard Pixley
26524 were developing similar scripts to use in the GNU compiler tools;
26525 so I adapted my @command{configure} scripts to support their evolving
26526 interface: using the file name @file{Makefile.in} as the templates;
26527 adding @samp{+srcdir}, the first option (of many); and creating
26528 @file{config.status} files.
26530 @node Exodus
26531 @section Exodus
26533 As I got feedback from users, I incorporated many improvements, using
26534 Emacs to search and replace, cut and paste, similar changes in each of
26535 the scripts.  As I adapted more GNU utilities packages to use
26536 @command{configure} scripts, updating them all by hand became impractical.
26537 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26538 mail saying that the @command{configure} scripts were great, and asking if
26539 I had a tool for generating them that I could send him.  No, I thought,
26540 but I should!  So I started to work out how to generate them.  And the
26541 journey from the slavery of hand-written @command{configure} scripts to the
26542 abundance and ease of Autoconf began.
26544 Cygnus @command{configure}, which was being developed at around that time,
26545 is table driven; it is meant to deal mainly with a discrete number of
26546 system types with a small number of mainly unguessable features (such as
26547 details of the object file format).  The automatic configuration system
26548 that Brian Fox had developed for Bash takes a similar approach.  For
26549 general use, it seems to me a hopeless cause to try to maintain an
26550 up-to-date database of which features each variant of each operating
26551 system has.  It's easier and more reliable to check for most features on
26552 the fly---especially on hybrid systems that people have hacked on
26553 locally or that have patches from vendors installed.
26555 I considered using an architecture similar to that of Cygnus
26556 @command{configure}, where there is a single @command{configure} script that
26557 reads pieces of @file{configure.in} when run.  But I didn't want to have
26558 to distribute all of the feature tests with every package, so I settled
26559 on having a different @command{configure} made from each
26560 @file{configure.in} by a preprocessor.  That approach also offered more
26561 control and flexibility.
26563 I looked briefly into using the Metaconfig package, by Larry Wall,
26564 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26565 reasons.  The @command{Configure} scripts it produces are interactive,
26566 which I find quite inconvenient; I didn't like the ways it checked for
26567 some features (such as library functions); I didn't know that it was
26568 still being maintained, and the @command{Configure} scripts I had
26569 seen didn't work on many modern systems (such as System V R4 and NeXT);
26570 it wasn't flexible in what it could do in response to a feature's
26571 presence or absence; I found it confusing to learn; and it was too big
26572 and complex for my needs (I didn't realize then how much Autoconf would
26573 eventually have to grow).
26575 I considered using Perl to generate my style of @command{configure}
26576 scripts, but decided that M4 was better suited to the job of simple
26577 textual substitutions: it gets in the way less, because output is
26578 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26579 the GNU extensions to M4.)  Also, some of my friends at the
26580 University of Maryland had recently been putting M4 front ends on
26581 several programs, including @code{tvtwm}, and I was interested in trying
26582 out a new language.
26584 @node Leviticus
26585 @section Leviticus
26587 Since my @command{configure} scripts determine the system's capabilities
26588 automatically, with no interactive user intervention, I decided to call
26589 the program that generates them Autoconfig.  But with a version number
26590 tacked on, that name would be too long for old Unix file systems,
26591 so I shortened it to Autoconf.
26593 In the fall of 1991 I called together a group of fellow questers after
26594 the Holy Grail of portability (er, that is, alpha testers) to give me
26595 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26596 and continued to add features and improve the techniques used in the
26597 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26598 with the idea of making an Autoconf shell script to run M4
26599 and check for unresolved macro calls; Richard Pixley, who suggested
26600 running the compiler instead of searching the file system to find
26601 include files and symbols, for more accurate results; Karl Berry, who
26602 got Autoconf to configure @TeX{} and added the macro index to the
26603 documentation; and Ian Lance Taylor, who added support for creating a C
26604 header file as an alternative to putting @option{-D} options in a
26605 makefile, so he could use Autoconf for his UUCP package.
26606 The alpha testers cheerfully adjusted their files again and again as the
26607 names and calling conventions of the Autoconf macros changed from
26608 release to release.  They all contributed many specific checks, great
26609 ideas, and bug fixes.
26611 @node Numbers
26612 @section Numbers
26614 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26615 and converted many GNU packages to use it.  I was surprised by how
26616 positive the reaction to it was.  More people started using it than I
26617 could keep track of, including people working on software that wasn't
26618 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26619 Autoconf continued to improve rapidly, as many people using the
26620 @command{configure} scripts reported problems they encountered.
26622 Autoconf turned out to be a good torture test for M4 implementations.
26623 Unix M4 started to dump core because of the length of the
26624 macros that Autoconf defined, and several bugs showed up in GNU
26625 M4 as well.  Eventually, we realized that we needed to use some
26626 features that only GNU M4 has.  4.3BSD M4, in
26627 particular, has an impoverished set of builtin macros; the System V
26628 version is better, but still doesn't provide everything we need.
26630 More development occurred as people put Autoconf under more stresses
26631 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26632 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26633 invalid arguments.  Jim Blandy bravely coerced it into configuring
26634 GNU Emacs, laying the groundwork for several later improvements.
26635 Roland McGrath got it to configure the GNU C Library, wrote the
26636 @command{autoheader} script to automate the creation of C header file
26637 templates, and added a @option{--verbose} option to @command{configure}.
26638 Noah Friedman added the @option{--autoconf-dir} option and
26639 @code{AC_MACRODIR} environment variable.  (He also coined the term
26640 @dfn{autoconfiscate} to mean ``adapt a software package to use
26641 Autoconf''.)  Roland and Noah improved the quoting protection in
26642 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26643 dealing with portability problems from February through June, 1993.
26645 @node Deuteronomy
26646 @section Deuteronomy
26648 A long wish list for major features had accumulated, and the effect of
26649 several years of patching by various people had left some residual
26650 cruft.  In April 1994, while working for Cygnus Support, I began a major
26651 revision of Autoconf.  I added most of the features of the Cygnus
26652 @command{configure} that Autoconf had lacked, largely by adapting the
26653 relevant parts of Cygnus @command{configure} with the help of david zuhn
26654 and Ken Raeburn.  These features include support for using
26655 @file{config.sub}, @file{config.guess}, @option{--host}, and
26656 @option{--target}; making links to files; and running @command{configure}
26657 scripts in subdirectories.  Adding these features enabled Ken to convert
26658 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26659 Autoconf.
26661 I added more features in response to other peoples' requests.  Many
26662 people had asked for @command{configure} scripts to share the results of
26663 the checks between runs, because (particularly when configuring a large
26664 source tree, like Cygnus does) they were frustratingly slow.  Mike
26665 Haertel suggested adding site-specific initialization scripts.  People
26666 distributing software that had to unpack on MS-DOS asked for a way to
26667 override the @file{.in} extension on the file names, which produced file
26668 names like @file{config.h.in} containing two dots.  Jim Avera did an
26669 extensive examination of the problems with quoting in @code{AC_DEFINE}
26670 and @code{AC_SUBST}; his insights led to significant improvements.
26671 Richard Stallman asked that compiler output be sent to @file{config.log}
26672 instead of @file{/dev/null}, to help people debug the Emacs
26673 @command{configure} script.
26675 I made some other changes because of my dissatisfaction with the quality
26676 of the program.  I made the messages showing results of the checks less
26677 ambiguous, always printing a result.  I regularized the names of the
26678 macros and cleaned up coding style inconsistencies.  I added some
26679 auxiliary utilities that I had developed to help convert source code
26680 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26681 the macros not interrupt each others' messages.  (That feature revealed
26682 some performance bottlenecks in GNU M4, which he hastily
26683 corrected!)  I reorganized the documentation around problems people want
26684 to solve.  And I began a test suite, because experience had shown that
26685 Autoconf has a pronounced tendency to regress when we change it.
26687 Again, several alpha testers gave invaluable feedback, especially
26688 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26689 and Mark Eichin.
26691 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26692 have free time again.  I think.  Yeah, right.)
26695 @c ========================================================== Appendices
26698 @node GNU Free Documentation License
26699 @appendix GNU Free Documentation License
26701 @include fdl.texi
26703 @node Indices
26704 @appendix Indices
26706 @menu
26707 * Environment Variable Index::  Index of environment variables used
26708 * Output Variable Index::       Index of variables set in output files
26709 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26710 * Cache Variable Index::        Index of documented cache variables
26711 * Autoconf Macro Index::        Index of Autoconf macros
26712 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26713 * Autotest Macro Index::        Index of Autotest macros
26714 * Program & Function Index::    Index of those with portability problems
26715 * Concept Index::               General index
26716 @end menu
26718 @node Environment Variable Index
26719 @appendixsec Environment Variable Index
26721 This is an alphabetical list of the environment variables that might
26722 influence Autoconf checks.
26724 @printindex ev
26726 @node Output Variable Index
26727 @appendixsec Output Variable Index
26729 This is an alphabetical list of the variables that Autoconf can
26730 substitute into files that it creates, typically one or more
26731 makefiles.  @xref{Setting Output Variables}, for more information
26732 on how this is done.
26734 @printindex ov
26736 @node Preprocessor Symbol Index
26737 @appendixsec Preprocessor Symbol Index
26739 This is an alphabetical list of the C preprocessor symbols that the
26740 Autoconf macros define.  To work with Autoconf, C source code needs to
26741 use these names in @code{#if} or @code{#ifdef} directives.
26743 @printindex cv
26745 @node Cache Variable Index
26746 @appendixsec Cache Variable Index
26748 This is an alphabetical list of documented cache variables used
26749 by macros defined in Autoconf.  Autoconf macros may use additional cache
26750 variables internally.
26751 @ifset shortindexflag
26752 To make the list easier to use, the variables are listed without their
26753 preceding @samp{ac_cv_}.
26754 @end ifset
26756 @printindex CA
26758 @node Autoconf Macro Index
26759 @appendixsec Autoconf Macro Index
26761 This is an alphabetical list of the Autoconf macros.
26762 @ifset shortindexflag
26763 To make the list easier to use, the macros are listed without their
26764 preceding @samp{AC_}.
26765 @end ifset
26767 @printindex AC
26769 @node M4 Macro Index
26770 @appendixsec M4 Macro Index
26772 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26773 @ifset shortindexflag
26774 To make the list easier to use, the macros are listed without their
26775 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26776 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26777 names.
26778 @end ifset
26780 @printindex MS
26782 @node Autotest Macro Index
26783 @appendixsec Autotest Macro Index
26785 This is an alphabetical list of the Autotest macros.
26786 @ifset shortindexflag
26787 To make the list easier to use, the macros are listed without their
26788 preceding @samp{AT_}.
26789 @end ifset
26791 @printindex AT
26793 @node Program & Function Index
26794 @appendixsec Program and Function Index
26796 This is an alphabetical list of the programs and functions whose
26797 portability is discussed in this document.
26799 @printindex pr
26801 @node Concept Index
26802 @appendixsec Concept Index
26804 This is an alphabetical list of the files, tools, and concepts
26805 introduced in this document.
26807 @printindex cp
26809 @bye
26811 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26812 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26813 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26814 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26815 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26816 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26817 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26818 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26819 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26820 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26821 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26822 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26823 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26824 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26825 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26826 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26827 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26828 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26829 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26830 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26831 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26832 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26833 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26834 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26835 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26836 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26837 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26838 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26839 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26840 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26841 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26842 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26843 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26844 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26845 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26846 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26847 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26848 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26849 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26850 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26851 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26852 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26853 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26854 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26855 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26856 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm
26857 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26858 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26859 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26860 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26861 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26862 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26863 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26864 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26865 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26866 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26867 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26868 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26869 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26870 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26871 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26872 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26873 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26874 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26875 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26876 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26877 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26878 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26879 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26880 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26881 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26882 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26883 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26884 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26885 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26886 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26887 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26888 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26889 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26890 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26891 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26892 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26893 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26894 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26895 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26896 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26897 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26898 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26899 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26900 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26901 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck
26902 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26904 @c Local Variables:
26905 @c fill-column: 72
26906 @c ispell-local-dictionary: "american"
26907 @c indent-tabs-mode: nil
26908 @c whitespace-check-buffer-indent: nil
26909 @c End: