AC_HEADER_MAJOR: port to glibc 2.25
[autoconf/ericb.git] / doc / autoconf.texi
blob684041dd5a818b93ae50608548a0b7d7164ce02f
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @documentencoding UTF-8
8 @setchapternewpage odd
9 @finalout
11 @c @ovar(ARG)
12 @c ----------
13 @c The ARG is an optional argument.  To be used for macro arguments in
14 @c their documentation (@defmac).
15 @macro ovar{varname}
16 @r{[}@var{\varname\}@r{]}
17 @end macro
19 @c @dvar(ARG, DEFAULT)
20 @c -------------------
21 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
22 @c for macro arguments in their documentation (@defmac).
23 @macro dvar{varname, default}
24 @r{[}@var{\varname\} = @samp{\default\}@r{]}
25 @end macro
27 @c @dvarv(ARG, DEFAULT-VAR)
28 @c ------------------------
29 @c Same as @dvar{ARG, DEFAULT-VAR}, but with @var instead of @samp
30 @c around DEFAULT-VAR.
31 @macro dvarv{varname, default}
32 @r{[}@var{\varname\} = @var{\default\}@r{]}@c
33 @end macro
35 @c Handling the indexes with Texinfo yields several different problems.
37 @c Because we want to drop out the AC_ part of the macro names in the
38 @c printed manual, but not in the other outputs, we need a layer above
39 @c the usual @acindex{} etc.  That's why we first define indexes such as
40 @c acx meant to become the macro @acindex.  First of all, using 'ac_'
41 @c does not work with makeinfo, and using 'ac1' doesn't work with TeX.
42 @c So use something more regular 'acx'.  Then you finish with a printed
43 @c index saying 'index is not existent'.  Of course: you ought to use
44 @c two letters :(  So you use capitals.
46 @c Second, when defining a macro in the TeX world, following spaces are
47 @c eaten.  But then, since we embed @acxindex commands that use the end
48 @c of line as an end marker, the whole things wrecks itself.  So make
49 @c sure you do *force* an additional end of line, add a '@c'.
51 @c Finally, you might want to get rid of TeX expansion, using --expand
52 @c with texi2dvi.  But then you wake up an old problem: we use macros
53 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
55 @c Define an environment variable index, for variables users may set
56 @c in their environment or on the configure command line.
57 @defcodeindex ev
58 @c Define an output variable index, for commonly AC_SUBST'ed variables.
59 @defcodeindex ov
60 @c Define a cache variable index, for variables matching *_cv_*.
61 @defcodeindex CA
62 @c Other shell variables not fitting the above categories should be
63 @c listed in the predefined vrindex, which we merge in the concept index.
64 @syncodeindex vr cp
65 @c Define a CPP preprocessor macro index, for #define'd strings.
66 @defcodeindex cv
67 @c Define an Autoconf macro index that @defmac doesn't write to.
68 @defcodeindex AC
69 @c Define an Autotest macro index that @defmac doesn't write to.
70 @defcodeindex AT
71 @c Define an M4sugar macro index that @defmac doesn't write to.
72 @defcodeindex MS
73 @c Define an index for *foreign* programs: 'mv' etc.  Used for the
74 @c portability sections and so on.
75 @defindex pr
77 @c shortindexflag
78 @c --------------
79 @c Shall we factor AC_ out of the Autoconf macro index etc.?
80 @iftex
81 @set shortindexflag
82 @end iftex
84 @c @acindex{MACRO}
85 @c ---------------
86 @c Registering an AC_\MACRO\.
87 @ifset shortindexflag
88 @macro acindex{macro}
89 @ACindex \macro\
91 @end macro
92 @end ifset
93 @ifclear shortindexflag
94 @macro acindex{macro}
95 @ACindex AC_\macro\
96 @end macro
97 @end ifclear
99 @c @ahindex{MACRO}
100 @c ---------------
101 @c Registering an AH_\MACRO\.
102 @macro ahindex{macro}
103 @ACindex AH_\macro\
105 @end macro
107 @c @asindex{MACRO}
108 @c ---------------
109 @c Registering an AS_\MACRO\.
110 @ifset shortindexflag
111 @macro asindex{macro}
112 @MSindex \macro\
114 @end macro
115 @end ifset
116 @ifclear shortindexflag
117 @macro asindex{macro}
118 @MSindex AS_\macro\
119 @end macro
120 @end ifclear
122 @c @atindex{MACRO}
123 @c ---------------
124 @c Registering an AT_\MACRO\.
125 @ifset shortindexflag
126 @macro atindex{macro}
127 @ATindex \macro\
129 @end macro
130 @end ifset
131 @ifclear shortindexflag
132 @macro atindex{macro}
133 @ATindex AT_\macro\
134 @end macro
135 @end ifclear
137 @c @auindex{MACRO}
138 @c ---------------
139 @c Registering an AU_\MACRO\.
140 @macro auindex{macro}
141 @ACindex AU_\macro\
143 @end macro
145 @c @hdrindex{MACRO}
146 @c ----------------
147 @c Indexing a header.
148 @macro hdrindex{macro}
149 @prindex @file{\macro\}
151 @end macro
153 @c @msindex{MACRO}
154 @c ---------------
155 @c Registering an m4_\MACRO\.
156 @ifset shortindexflag
157 @macro msindex{macro}
158 @MSindex \macro\
160 @end macro
161 @end ifset
162 @ifclear shortindexflag
163 @macro msindex{macro}
164 @MSindex m4_\macro\
165 @end macro
166 @end ifclear
169 @c @caindex{VARIABLE}
170 @c ------------------
171 @c Registering an ac_cv_\VARIABLE\ cache variable.
172 @ifset shortindexflag
173 @macro caindex{macro}
174 @CAindex \macro\
175 @end macro
176 @end ifset
177 @ifclear shortindexflag
178 @macro caindex{macro}
179 @CAindex ac_cv_\macro\
180 @end macro
181 @end ifclear
183 @c Define an index for functions: `alloca' etc.  Used for the
184 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
185 @c since `@defmac' goes into it => we'd get all the macros too.
187 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
189 @c   ! No room for a new @write .
190 @c   l.112 @defcodeindex fu
192 @c   so don't define yet another one :(  Just put some tags before each
193 @c   @prindex which is actually a @funindex.
195 @c   @defcodeindex fu
198 @c   @c Put the programs and functions into their own index.
199 @c   @syncodeindex fu pr
201 @comment %**end of header
202 @comment ========================================================
204 @copying
206 This manual (@value{UPDATED}) is for GNU Autoconf
207 (version @value{VERSION}),
208 a package for creating scripts to configure source code packages using
209 templates and an M4 macro package.
211 Copyright @copyright{} 1992--1996, 1998--2016 Free Software Foundation,
212 Inc.
214 @quotation
215 Permission is granted to copy, distribute and/or modify this document
216 under the terms of the GNU Free Documentation License,
217 Version 1.3 or any later version published by the Free Software
218 Foundation; with no Invariant Sections, no Front-Cover texts, and
219 no Back-Cover Texts.  A copy of the license is included in the section
220 entitled ``GNU Free Documentation License.''
221 @end quotation
222 @end copying
226 @dircategory Software development
227 @direntry
228 * Autoconf: (autoconf).         Create source code configuration scripts.
229 @end direntry
231 @dircategory Individual utilities
232 @direntry
233 * autoscan: (autoconf)autoscan Invocation.
234                                 Semi-automatic @file{configure.ac} writing
235 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
236 * autoconf-invocation: (autoconf)autoconf Invocation.
237                                 How to create configuration scripts
238 * autoreconf: (autoconf)autoreconf Invocation.
239                                 Remaking multiple @command{configure} scripts
240 * autoheader: (autoconf)autoheader Invocation.
241                                 How to create configuration templates
242 * autom4te: (autoconf)autom4te Invocation.
243                                 The Autoconf executables backbone
244 * configure: (autoconf)configure Invocation.    Configuring a package.
245 * autoupdate: (autoconf)autoupdate Invocation.
246                                 Automatic update of @file{configure.ac}
247 * config.status: (autoconf)config.status Invocation. Recreating configurations.
248 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
249 @end direntry
251 @titlepage
252 @title Autoconf
253 @subtitle Creating Automatic Configuration Scripts
254 @subtitle for version @value{VERSION}, @value{UPDATED}
255 @author David MacKenzie
256 @author Ben Elliston
257 @author Akim Demaille
258 @page
259 @vskip 0pt plus 1filll
260 @insertcopying
261 @end titlepage
263 @contents
266 @ifnottex
267 @node Top
268 @top Autoconf
269 @insertcopying
270 @end ifnottex
272 @c The master menu, created with texinfo-master-menu, goes here.
274 @menu
275 * Introduction::                Autoconf's purpose, strengths, and weaknesses
276 * The GNU Build System::        A set of tools for portable software packages
277 * Making configure Scripts::    How to organize and produce Autoconf scripts
278 * Setup::                       Initialization and output
279 * Existing Tests::              Macros that check for particular features
280 * Writing Tests::               How to write new feature checks
281 * Results::                     What to do with results from feature checks
282 * Programming in M4::           Layers on top of which Autoconf is written
283 * Programming in M4sh::         Shell portability layer
284 * Writing Autoconf Macros::     Adding new macros to Autoconf
285 * Portable Shell::              Shell script portability pitfalls
286 * Portable Make::               Makefile portability pitfalls
287 * Portable C and C++::          C and C++ portability pitfalls
288 * Manual Configuration::        Selecting features that can't be guessed
289 * Site Configuration::          Local defaults for @command{configure}
290 * Running configure Scripts::   How to use the Autoconf output
291 * config.status Invocation::    Recreating a configuration
292 * Obsolete Constructs::         Kept for backward compatibility
293 * Using Autotest::              Creating portable test suites
294 * FAQ::                         Frequent Autoconf Questions, with answers
295 * History::                     History of Autoconf
296 * GNU Free Documentation License::  License for copying this manual
297 * Indices::                     Indices of symbols, concepts, etc.
299 @detailmenu
300  --- The Detailed Node Listing ---
302 The GNU Build System
304 * Automake::                    Escaping makefile hell
305 * Gnulib::                      The GNU portability library
306 * Libtool::                     Building libraries portably
307 * Pointers::                    More info on the GNU build system
309 Making @command{configure} Scripts
311 * Writing Autoconf Input::      What to put in an Autoconf input file
312 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
313 * ifnames Invocation::          Listing the conditionals in source code
314 * autoconf Invocation::         How to create configuration scripts
315 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
317 Writing @file{configure.ac}
319 * Shell Script Compiler::       Autoconf as solution of a problem
320 * Autoconf Language::           Programming in Autoconf
321 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
323 Initialization and Output Files
325 * Initializing configure::      Option processing etc.
326 * Versioning::                  Dealing with Autoconf versions
327 * Notices::                     Copyright, version numbers in @command{configure}
328 * Input::                       Where Autoconf should find files
329 * Output::                      Outputting results from the configuration
330 * Configuration Actions::       Preparing the output based on results
331 * Configuration Files::         Creating output files
332 * Makefile Substitutions::      Using output variables in makefiles
333 * Configuration Headers::       Creating a configuration header file
334 * Configuration Commands::      Running arbitrary instantiation commands
335 * Configuration Links::         Links depending on the configuration
336 * Subdirectories::              Configuring independent packages together
337 * Default Prefix::              Changing the default installation prefix
339 Substitutions in Makefiles
341 * Preset Output Variables::     Output variables that are always set
342 * Installation Directory Variables::  Other preset output variables
343 * Changed Directory Variables::  Warnings about @file{datarootdir}
344 * Build Directories::           Supporting multiple concurrent compiles
345 * Automatic Remaking::          Makefile rules for configuring
347 Configuration Header Files
349 * Header Templates::            Input for the configuration headers
350 * autoheader Invocation::       How to create configuration templates
351 * Autoheader Macros::           How to specify CPP templates
353 Existing Tests
355 * Common Behavior::             Macros' standard schemes
356 * Alternative Programs::        Selecting between alternative programs
357 * Files::                       Checking for the existence of files
358 * Libraries::                   Library archives that might be missing
359 * Library Functions::           C library functions that might be missing
360 * Header Files::                Header files that might be missing
361 * Declarations::                Declarations that may be missing
362 * Structures::                  Structures or members that might be missing
363 * Types::                       Types that might be missing
364 * Compilers and Preprocessors::  Checking for compiling programs
365 * System Services::             Operating system services
366 * Posix Variants::              Special kludges for specific Posix variants
367 * Erlang Libraries::            Checking for the existence of Erlang libraries
369 Common Behavior
371 * Standard Symbols::            Symbols defined by the macros
372 * Default Includes::            Includes used by the generic macros
374 Alternative Programs
376 * Particular Programs::         Special handling to find certain programs
377 * Generic Programs::            How to find other programs
379 Library Functions
381 * Function Portability::        Pitfalls with usual functions
382 * Particular Functions::        Special handling to find certain functions
383 * Generic Functions::           How to find other functions
385 Header Files
387 * Header Portability::          Collected knowledge on common headers
388 * Particular Headers::          Special handling to find certain headers
389 * Generic Headers::             How to find other headers
391 Declarations
393 * Particular Declarations::     Macros to check for certain declarations
394 * Generic Declarations::        How to find other declarations
396 Structures
398 * Particular Structures::       Macros to check for certain structure members
399 * Generic Structures::          How to find other structure members
401 Types
403 * Particular Types::            Special handling to find certain types
404 * Generic Types::               How to find other types
406 Compilers and Preprocessors
408 * Specific Compiler Characteristics::  Some portability issues
409 * Generic Compiler Characteristics::  Language independent tests and features
410 * C Compiler::                  Checking its characteristics
411 * C++ Compiler::                Likewise
412 * Objective C Compiler::        Likewise
413 * Objective C++ Compiler::      Likewise
414 * Erlang Compiler and Interpreter::  Likewise
415 * Fortran Compiler::            Likewise
416 * Go Compiler::                 Likewise
418 Writing Tests
420 * Language Choice::             Selecting which language to use for testing
421 * Writing Test Programs::       Forging source files for compilers
422 * Running the Preprocessor::    Detecting preprocessor symbols
423 * Running the Compiler::        Detecting language or header features
424 * Running the Linker::          Detecting library features
425 * Runtime::                     Testing for runtime features
426 * Systemology::                 A zoology of operating systems
427 * Multiple Cases::              Tests for several possible values
429 Writing Test Programs
431 * Guidelines::                  General rules for writing test programs
432 * Test Functions::              Avoiding pitfalls in test programs
433 * Generating Sources::          Source program boilerplate
435 Results of Tests
437 * Defining Symbols::            Defining C preprocessor symbols
438 * Setting Output Variables::    Replacing variables in output files
439 * Special Chars in Variables::  Characters to beware of in variables
440 * Caching Results::             Speeding up subsequent @command{configure} runs
441 * Printing Messages::           Notifying @command{configure} users
443 Caching Results
445 * Cache Variable Names::        Shell variables used in caches
446 * Cache Files::                 Files @command{configure} uses for caching
447 * Cache Checkpointing::         Loading and saving the cache file
449 Programming in M4
451 * M4 Quotation::                Protecting macros from unwanted expansion
452 * Using autom4te::              The Autoconf executables backbone
453 * Programming in M4sugar::      Convenient pure M4 macros
454 * Debugging via autom4te::      Figuring out what M4 was doing
456 M4 Quotation
458 * Active Characters::           Characters that change the behavior of M4
459 * One Macro Call::              Quotation and one macro call
460 * Quoting and Parameters::      M4 vs. shell parameters
461 * Quotation and Nested Macros::  Macros calling macros
462 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
463 * Quadrigraphs::                Another way to escape special characters
464 * Balancing Parentheses::       Dealing with unbalanced parentheses
465 * Quotation Rule Of Thumb::     One parenthesis, one quote
467 Using @command{autom4te}
469 * autom4te Invocation::         A GNU M4 wrapper
470 * Customizing autom4te::        Customizing the Autoconf package
472 Programming in M4sugar
474 * Redefined M4 Macros::         M4 builtins changed in M4sugar
475 * Diagnostic Macros::           Diagnostic messages from M4sugar
476 * Diversion support::           Diversions in M4sugar
477 * Conditional constructs::      Conditions in M4
478 * Looping constructs::          Iteration in M4
479 * Evaluation Macros::           More quotation and evaluation control
480 * Text processing Macros::      String manipulation in M4
481 * Number processing Macros::    Arithmetic computation in M4
482 * Set manipulation Macros::     Set manipulation in M4
483 * Forbidden Patterns::          Catching unexpanded macros
485 Programming in M4sh
487 * Common Shell Constructs::     Portability layer for common shell constructs
488 * Polymorphic Variables::       Support for indirect variable names
489 * Initialization Macros::       Macros to establish a sane shell environment
490 * File Descriptor Macros::      File descriptor macros for input and output
492 Writing Autoconf Macros
494 * Macro Definitions::           Basic format of an Autoconf macro
495 * Macro Names::                 What to call your new macros
496 * Reporting Messages::          Notifying @command{autoconf} users
497 * Dependencies Between Macros::  What to do when macros depend on other macros
498 * Obsoleting Macros::           Warning about old ways of doing things
499 * Coding Style::                Writing Autoconf macros @`a la Autoconf
501 Dependencies Between Macros
503 * Prerequisite Macros::         Ensuring required information
504 * Suggested Ordering::          Warning about possible ordering problems
505 * One-Shot Macros::             Ensuring a macro is called only once
507 Portable Shell Programming
509 * Shellology::                  A zoology of shells
510 * 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 have to use text that also resembles a macro
1247 call.  You must quote that text even when it is not passed as a macro
1248 argument.  For example, these two approaches in @file{configure.ac}
1249 (quoting just the potential problems, or quoting the entire line) will
1250 protect your script in case autoconf ever adds a macro @code{AC_DC}:
1252 @example
1253 echo "Hard rock was here!  --[AC_DC]"
1254 [echo "Hard rock was here!  --AC_DC"]
1255 @end example
1257 @noindent
1258 which results in this text in @file{configure}:
1260 @example
1261 echo "Hard rock was here!  --AC_DC"
1262 echo "Hard rock was here!  --AC_DC"
1263 @end example
1265 @noindent
1266 When you use the same text in a macro argument, you must therefore have
1267 an extra quotation level (since one is stripped away by the macro
1268 substitution).  In general, then, it is a good idea to @emph{use double
1269 quoting for all literal string arguments}, either around just the
1270 problematic portions, or over the entire argument:
1272 @example
1273 AC_MSG_WARN([[AC_DC] stinks  --Iron Maiden])
1274 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1275 @end example
1277 However, the above example triggers a warning about a possibly
1278 unexpanded macro when running @command{autoconf}, because it collides
1279 with the namespace of macros reserved for the Autoconf language.  To be
1280 really safe, you can use additional escaping (either a quadrigraph, or
1281 creative shell constructs) to silence that particular warning:
1283 @example
1284 echo "Hard rock was here!  --AC""_DC"
1285 AC_MSG_WARN([[AC@@&t@@_DC stinks  --Iron Maiden]])
1286 @end example
1288 You are now able to understand one of the constructs of Autoconf that
1289 has been continually misunderstood@enddots{}  The rule of thumb is that
1290 @emph{whenever you expect macro expansion, expect quote expansion};
1291 i.e., expect one level of quotes to be lost.  For instance:
1293 @example
1294 AC_COMPILE_IFELSE(AC_LANG_SOURCE([char b[10];]), [],
1295  [AC_MSG_ERROR([you lose])])
1296 @end example
1298 @noindent
1299 is incorrect: here, the first argument of @code{AC_LANG_SOURCE} is
1300 @samp{char b[10];} and is expanded once, which results in
1301 @samp{char b10;}; and the @code{AC_LANG_SOURCE} is also expanded prior
1302 to being passed to @code{AC_COMPILE_IFELSE}.  (There was an idiom common
1303 in Autoconf's past to
1304 address this issue via the M4 @code{changequote} primitive, but do not
1305 use it!)  Let's take a closer look: the author meant the first argument
1306 to be understood as a literal, and therefore it must be quoted twice;
1307 likewise, the intermediate @code{AC_LANG_SOURCE} macro should be quoted
1308 once so that it is only expanded after the rest of the body of
1309 @code{AC_COMPILE_IFELSE} is in place:
1311 @example
1312 AC_COMPILE_IFELSE([AC_LANG_SOURCE([[char b[10];]])], [],
1313   [AC_MSG_ERROR([you lose])])
1314 @end example
1316 @noindent
1317 Voil@`a, you actually produce @samp{char b[10];} this time!
1319 On the other hand, descriptions (e.g., the last parameter of
1320 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1321 are subject to line breaking, for example---and should not be double quoted.
1322 Even if these descriptions are short and are not actually broken, double
1323 quoting them yields weird results.
1325 Some macros take optional arguments, which this documentation represents
1326 as @ovar{arg} (not to be confused with the quote characters).  You may
1327 just leave them empty, or use @samp{[]} to make the emptiness of the
1328 argument explicit, or you may simply omit the trailing commas.  The
1329 three lines below are equivalent:
1331 @example
1332 AC_CHECK_HEADERS([stdio.h], [], [], [])
1333 AC_CHECK_HEADERS([stdio.h],,,)
1334 AC_CHECK_HEADERS([stdio.h])
1335 @end example
1337 It is best to put each macro call on its own line in
1338 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1339 rely on the newline after the macro call to terminate the commands.
1340 This approach makes the generated @command{configure} script a little
1341 easier to read by not inserting lots of blank lines.  It is generally
1342 safe to set shell variables on the same line as a macro call, because
1343 the shell allows assignments without intervening newlines.
1345 You can include comments in @file{configure.ac} files by starting them
1346 with the @samp{#}.  For example, it is helpful to begin
1347 @file{configure.ac} files with a line like this:
1349 @example
1350 # Process this file with autoconf to produce a configure script.
1351 @end example
1353 @node Autoconf Input Layout
1354 @subsection Standard @file{configure.ac} Layout
1356 The order in which @file{configure.ac} calls the Autoconf macros is not
1357 important, with a few exceptions.  Every @file{configure.ac} must
1358 contain a call to @code{AC_INIT} before the checks, and a call to
1359 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1360 rely on other macros having been called first, because they check
1361 previously set values of some variables to decide what to do.  These
1362 macros are noted in the individual descriptions (@pxref{Existing
1363 Tests}), and they also warn you when @command{configure} is created if they
1364 are called out of order.
1366 To encourage consistency, here is a suggested order for calling the
1367 Autoconf macros.  Generally speaking, the things near the end of this
1368 list are those that could depend on things earlier in it.  For example,
1369 library functions could be affected by types and libraries.
1371 @display
1372 @group
1373 Autoconf requirements
1374 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1375 information on the package
1376 checks for programs
1377 checks for libraries
1378 checks for header files
1379 checks for types
1380 checks for structures
1381 checks for compiler characteristics
1382 checks for library functions
1383 checks for system services
1384 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1385 @code{AC_OUTPUT}
1386 @end group
1387 @end display
1390 @node autoscan Invocation
1391 @section Using @command{autoscan} to Create @file{configure.ac}
1392 @cindex @command{autoscan}
1394 The @command{autoscan} program can help you create and/or maintain a
1395 @file{configure.ac} file for a software package.  @command{autoscan}
1396 examines source files in the directory tree rooted at a directory given
1397 as a command line argument, or the current directory if none is given.
1398 It searches the source files for common portability problems and creates
1399 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1400 for that package, and checks a possibly existing @file{configure.ac} for
1401 completeness.
1403 When using @command{autoscan} to create a @file{configure.ac}, you
1404 should manually examine @file{configure.scan} before renaming it to
1405 @file{configure.ac}; it probably needs some adjustments.
1406 Occasionally, @command{autoscan} outputs a macro in the wrong order
1407 relative to another macro, so that @command{autoconf} produces a warning;
1408 you need to move such macros manually.  Also, if you want the package to
1409 use a configuration header file, you must add a call to
1410 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1411 also have to change or add some @code{#if} directives to your program in
1412 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1413 information about a program that can help with that job).
1415 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1416 consider adding its suggestions.  The file @file{autoscan.log}
1417 contains detailed information on why a macro is requested.
1419 @command{autoscan} uses several data files (installed along with Autoconf)
1420 to determine which macros to output when it finds particular symbols in
1421 a package's source files.  These data files all have the same format:
1422 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1423 output if that symbol is encountered.  Lines starting with @samp{#} are
1424 comments.
1426 @command{autoscan} accepts the following options:
1428 @table @option
1429 @item --help
1430 @itemx -h
1431 Print a summary of the command line options and exit.
1433 @item --version
1434 @itemx -V
1435 Print the version number of Autoconf and exit.
1437 @item --verbose
1438 @itemx -v
1439 Print the names of the files it examines and the potentially interesting
1440 symbols it finds in them.  This output can be voluminous.
1442 @item --debug
1443 @itemx -d
1444 Don't remove temporary files.
1446 @item --include=@var{dir}
1447 @itemx -I @var{dir}
1448 Append @var{dir} to the include path.  Multiple invocations accumulate.
1450 @item --prepend-include=@var{dir}
1451 @itemx -B @var{dir}
1452 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1453 @end table
1455 @node ifnames Invocation
1456 @section Using @command{ifnames} to List Conditionals
1457 @cindex @command{ifnames}
1459 @command{ifnames} can help you write @file{configure.ac} for a software
1460 package.  It prints the identifiers that the package already uses in C
1461 preprocessor conditionals.  If a package has already been set up to have
1462 some portability, @command{ifnames} can thus help you figure out what its
1463 @command{configure} needs to check for.  It may help fill in some gaps in a
1464 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1465 Invocation}).
1467 @command{ifnames} scans all of the C source files named on the command line
1468 (or the standard input, if none are given) and writes to the standard
1469 output a sorted list of all the identifiers that appear in those files
1470 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1471 directives.  It prints each identifier on a line, followed by a
1472 space-separated list of the files in which that identifier occurs.
1474 @noindent
1475 @command{ifnames} accepts the following options:
1477 @table @option
1478 @item --help
1479 @itemx -h
1480 Print a summary of the command line options and exit.
1482 @item --version
1483 @itemx -V
1484 Print the version number of Autoconf and exit.
1485 @end table
1487 @node autoconf Invocation
1488 @section Using @command{autoconf} to Create @command{configure}
1489 @cindex @command{autoconf}
1491 To create @command{configure} from @file{configure.ac}, run the
1492 @command{autoconf} program with no arguments.  @command{autoconf} processes
1493 @file{configure.ac} with the M4 macro processor, using the
1494 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1495 file instead of @file{configure.ac} and writes the configuration script
1496 to the standard output instead of to @command{configure}.  If you give
1497 @command{autoconf} the argument @option{-}, it reads from the standard
1498 input instead of @file{configure.ac} and writes the configuration script
1499 to the standard output.
1501 The Autoconf macros are defined in several files.  Some of the files are
1502 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1503 looks for the optional file @file{acsite.m4} in the directory that
1504 contains the distributed Autoconf macro files, and for the optional file
1505 @file{aclocal.m4} in the current directory.  Those files can contain
1506 your site's or the package's own Autoconf macro definitions
1507 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1508 defined in more than one of the files that @command{autoconf} reads, the
1509 last definition it reads overrides the earlier ones.
1511 @command{autoconf} accepts the following options:
1513 @table @option
1514 @item --help
1515 @itemx -h
1516 Print a summary of the command line options and exit.
1518 @item --version
1519 @itemx -V
1520 Print the version number of Autoconf and exit.
1522 @item --verbose
1523 @itemx -v
1524 Report processing steps.
1526 @item --debug
1527 @itemx -d
1528 Don't remove the temporary files.
1530 @item --force
1531 @itemx -f
1532 Remake @file{configure} even if newer than its input files.
1534 @item --include=@var{dir}
1535 @itemx -I @var{dir}
1536 Append @var{dir} to the include path.  Multiple invocations accumulate.
1538 @item --prepend-include=@var{dir}
1539 @itemx -B @var{dir}
1540 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1542 @item --output=@var{file}
1543 @itemx -o @var{file}
1544 Save output (script or trace) to @var{file}.  The file @option{-} stands
1545 for the standard output.
1547 @item --warnings=@var{category}
1548 @itemx -W @var{category}
1549 @evindex WARNINGS
1550 Report the warnings related to @var{category} (which can actually be a
1551 comma separated list).  @xref{Reporting Messages}, macro
1552 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1553 values include:
1555 @table @samp
1556 @item all
1557 report all the warnings
1559 @item none
1560 report none
1562 @item error
1563 treats warnings as errors
1565 @item no-@var{category}
1566 disable warnings falling into @var{category}
1567 @end table
1569 Warnings about @samp{syntax} are enabled by default, and the environment
1570 variable @env{WARNINGS}, a comma separated list of categories, is
1571 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1572 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1573 disable the defaults and @env{WARNINGS}, and then
1574 enable warnings about obsolete constructs, use @option{-W
1575 none,obsolete}.
1577 @cindex Back trace
1578 @cindex Macro invocation stack
1579 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1580 displays a back trace for errors, but not for warnings; if you want
1581 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1582 examples.
1584 @item --trace=@var{macro}[:@var{format}]
1585 @itemx -t @var{macro}[:@var{format}]
1586 Do not create the @command{configure} script, but list the calls to
1587 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1588 arguments can be used to list several macros.  Multiple @option{--trace}
1589 arguments for a single macro are not cumulative; instead, you should
1590 just make @var{format} as long as needed.
1592 The @var{format} is a regular string, with newlines if desired, and
1593 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1594 @ref{autom4te Invocation}, for details on the @var{format}.
1596 @item --initialization
1597 @itemx -i
1598 By default, @option{--trace} does not trace the initialization of the
1599 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1600 results in a noticeable speedup, but can be disabled by this option.
1601 @end table
1604 It is often necessary to check the content of a @file{configure.ac}
1605 file, but parsing it yourself is extremely fragile and error-prone.  It
1606 is suggested that you rely upon @option{--trace} to scan
1607 @file{configure.ac}.  For instance, to find the list of variables that
1608 are substituted, use:
1610 @example
1611 @group
1612 $ @kbd{autoconf -t AC_SUBST}
1613 configure.ac:2:AC_SUBST:ECHO_C
1614 configure.ac:2:AC_SUBST:ECHO_N
1615 configure.ac:2:AC_SUBST:ECHO_T
1616 @i{More traces deleted}
1617 @end group
1618 @end example
1620 @noindent
1621 The example below highlights the difference between @samp{$@@},
1622 @samp{$*}, and @samp{$%}.
1624 @example
1625 @group
1626 $ @kbd{cat configure.ac}
1627 AC_DEFINE(This, is, [an
1628 [example]])
1629 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1630 *: $*
1631 %: $%'
1632 @@: [This],[is],[an
1633 [example]]
1634 *: This,is,an
1635 [example]
1636 %: This:is:an [example]
1637 @end group
1638 @end example
1640 @noindent
1641 The @var{format} gives you a lot of freedom:
1643 @example
1644 @group
1645 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1646 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1647 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1648 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1649 @i{More traces deleted}
1650 @end group
1651 @end example
1653 @noindent
1654 A long @var{separator} can be used to improve the readability of complex
1655 structures, and to ease their parsing (for instance when no single
1656 character is suitable as a separator):
1658 @example
1659 @group
1660 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1661 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1662 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1663 AUTOMAKE|:::::|automake|:::::|$missing_dir
1664 @i{More traces deleted}
1665 @end group
1666 @end example
1668 @node autoreconf Invocation
1669 @section Using @command{autoreconf} to Update @command{configure} Scripts
1670 @cindex @command{autoreconf}
1672 Installing the various components of the GNU Build System can be
1673 tedious: running @command{autopoint} for Gettext, @command{automake} for
1674 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1675 because some tools such as @command{automake} have been updated on your
1676 system, or because some of the sources such as @file{configure.ac} have
1677 been updated, or finally, simply in order to install the GNU Build
1678 System in a fresh tree.
1680 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1681 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1682 @command{autopoint} (when appropriate) repeatedly to update the
1683 GNU Build System in the specified directories and their
1684 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1685 those files that are older than their sources.  The environment variables
1686 @env{AUTOM4TE}, @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE},
1687 @env{ACLOCAL}, @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE}
1688 may be used to override the invocation of the respective tools.
1690 If you install a new version of some tool, you can make
1691 @command{autoreconf} remake @emph{all} of the files by giving it the
1692 @option{--force} option.
1694 @xref{Automatic Remaking}, for Make rules to automatically
1695 rebuild @command{configure} scripts when their source files change.  That
1696 method handles the timestamps of configuration header templates
1697 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1698 @option{--localdir=@var{dir}}.
1700 @cindex Gettext
1701 @cindex @command{autopoint}
1702 Gettext supplies the @command{autopoint} command to add translation
1703 infrastructure to a source package.  If you use @command{autopoint},
1704 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1705 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1706 Invocation, , Invoking the @code{autopoint} Program, gettext,
1707 GNU @code{gettext} utilities}, for further details.
1709 @noindent
1710 @command{autoreconf} accepts the following options:
1712 @table @option
1713 @item --help
1714 @itemx -h
1715 Print a summary of the command line options and exit.
1717 @item --version
1718 @itemx -V
1719 Print the version number of Autoconf and exit.
1721 @item --verbose
1722 @itemx -v
1723 Print the name of each directory @command{autoreconf} examines and the
1724 commands it runs.  If given two or more times, pass @option{--verbose}
1725 to subordinate tools that support it.
1727 @item --debug
1728 @itemx -d
1729 Don't remove the temporary files.
1731 @item --force
1732 @itemx -f
1733 Remake even @file{configure} scripts and configuration headers that are
1734 newer than their input files (@file{configure.ac} and, if present,
1735 @file{aclocal.m4}).
1737 @item --install
1738 @itemx -i
1739 Install the missing auxiliary files in the package.  By default, files
1740 are copied; this can be changed with @option{--symlink}.
1742 If deemed appropriate, this option triggers calls to
1743 @samp{automake --add-missing},
1744 @samp{libtoolize}, @samp{autopoint}, etc.
1746 @item --no-recursive
1747 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1748 macro @code{AC_CONFIG_SUBDIRS}).
1750 @item --symlink
1751 @itemx -s
1752 When used with @option{--install}, install symbolic links to the missing
1753 auxiliary files instead of copying them.
1755 @item --make
1756 @itemx -m
1757 When the directories were configured, update the configuration by
1758 running @samp{./config.status --recheck && ./config.status}, and then
1759 run @samp{make}.
1761 @item --include=@var{dir}
1762 @itemx -I @var{dir}
1763 Append @var{dir} to the include path.  Multiple invocations accumulate.
1764 Passed on to @command{aclocal}, @command{autoconf} and
1765 @command{autoheader} internally.
1767 @item --prepend-include=@var{dir}
1768 @itemx -B @var{dir}
1769 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1770 Passed on to @command{autoconf} and @command{autoheader} internally.
1772 @item --warnings=@var{category}
1773 @itemx -W @var{category}
1774 @evindex WARNINGS
1775 Report the warnings related to @var{category} (which can actually be a
1776 comma separated list).
1778 @table @samp
1779 @item cross
1780 related to cross compilation issues.
1782 @item obsolete
1783 report the uses of obsolete constructs.
1785 @item portability
1786 portability issues
1788 @item syntax
1789 dubious syntactic constructs.
1791 @item all
1792 report all the warnings
1794 @item none
1795 report none
1797 @item error
1798 treats warnings as errors
1800 @item no-@var{category}
1801 disable warnings falling into @var{category}
1802 @end table
1804 Warnings about @samp{syntax} are enabled by default, and the environment
1805 variable @env{WARNINGS}, a comma separated list of categories, is
1806 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1807 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1808 disable the defaults and @env{WARNINGS}, and then
1809 enable warnings about obsolete constructs, use @option{-W
1810 none,obsolete}.
1811 @end table
1813 If you want @command{autoreconf} to pass flags that are not listed here
1814 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1815 Due to a limitation in the Autoconf implementation these flags currently
1816 must be set on a single line in @file{Makefile.am}, without any
1817 backslash-newlines.  Also, be aware that future Automake releases might
1818 start flagging @code{ACLOCAL_AMFLAGS} as obsolescent, or even remove
1819 support for it.
1821 @c ========================================= Initialization and Output Files.
1823 @node Setup
1824 @chapter Initialization and Output Files
1826 Autoconf-generated @command{configure} scripts need some information about
1827 how to initialize, such as how to find the package's source files and
1828 about the output files to produce.  The following sections describe the
1829 initialization and the creation of output files.
1831 @menu
1832 * Initializing configure::      Option processing etc.
1833 * Versioning::                  Dealing with Autoconf versions
1834 * Notices::                     Copyright, version numbers in @command{configure}
1835 * Input::                       Where Autoconf should find files
1836 * Output::                      Outputting results from the configuration
1837 * Configuration Actions::       Preparing the output based on results
1838 * Configuration Files::         Creating output files
1839 * Makefile Substitutions::      Using output variables in makefiles
1840 * Configuration Headers::       Creating a configuration header file
1841 * Configuration Commands::      Running arbitrary instantiation commands
1842 * Configuration Links::         Links depending on the configuration
1843 * Subdirectories::              Configuring independent packages together
1844 * Default Prefix::              Changing the default installation prefix
1845 @end menu
1847 @node Initializing configure
1848 @section Initializing @command{configure}
1850 Every @command{configure} script must call @code{AC_INIT} before doing
1851 anything else that produces output.  Calls to silent macros, such as
1852 @code{AC_DEFUN}, may also occur prior to @code{AC_INIT}, although these
1853 are generally used via @file{aclocal.m4}, since that is implicitly
1854 included before the start of @file{configure.ac}.  The only other
1855 required macro is @code{AC_OUTPUT} (@pxref{Output}).
1857 @anchor{AC_INIT}
1858 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1859   @ovar{tarname}, @ovar{url})
1860 @acindex{INIT}
1861 Process any command-line arguments and perform initialization
1862 and verification.
1864 Set the name of the @var{package} and its @var{version}.  These are
1865 typically used in @option{--version} support, including that of
1866 @command{configure}.  The optional argument @var{bug-report} should be
1867 the email to which users should send bug reports.  The package
1868 @var{tarname} differs from @var{package}: the latter designates the full
1869 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1870 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1871 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1872 other than alphanumerics and underscores are changed to @samp{-}.  If
1873 provided, @var{url} should be the home page for the package.
1875 The arguments of @code{AC_INIT} must be static, i.e., there should not
1876 be any shell computation, quotes, or newlines, but they can be computed
1877 by M4.  This is because the package information strings are expanded at
1878 M4 time into several contexts, and must give the same text at shell time
1879 whether used in single-quoted strings, double-quoted strings, quoted
1880 here-documents, or unquoted here-documents.  It is permissible to use
1881 @code{m4_esyscmd} or @code{m4_esyscmd_s} for computing a version string
1882 that changes with every commit to a version control system (in fact,
1883 Autoconf does just that, for all builds of the development tree made
1884 between releases).
1886 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1887 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1888 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1890 @table @asis
1891 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1892 @acindex{PACKAGE_NAME}
1893 @ovindex PACKAGE_NAME
1894 @cvindex PACKAGE_NAME
1895 Exactly @var{package}.
1897 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1898 @acindex{PACKAGE_TARNAME}
1899 @ovindex PACKAGE_TARNAME
1900 @cvindex PACKAGE_TARNAME
1901 Exactly @var{tarname}, possibly generated from @var{package}.
1903 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1904 @acindex{PACKAGE_VERSION}
1905 @ovindex PACKAGE_VERSION
1906 @cvindex PACKAGE_VERSION
1907 Exactly @var{version}.
1909 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1910 @acindex{PACKAGE_STRING}
1911 @ovindex PACKAGE_STRING
1912 @cvindex PACKAGE_STRING
1913 Exactly @samp{@var{package} @var{version}}.
1915 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1916 @acindex{PACKAGE_BUGREPORT}
1917 @ovindex PACKAGE_BUGREPORT
1918 @cvindex PACKAGE_BUGREPORT
1919 Exactly @var{bug-report}, if one was provided.  Typically an email
1920 address, or URL to a bug management web page.
1922 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1923 @acindex{PACKAGE_URL}
1924 @ovindex PACKAGE_URL
1925 @cvindex PACKAGE_URL
1926 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1927 @var{package} begins with @samp{GNU }, then this defaults to
1928 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1929 assumed.
1930 @end table
1931 @end defmac
1933 If your @command{configure} script does its own option processing, it
1934 should inspect @samp{$@@} or @samp{$*} immediately after calling
1935 @code{AC_INIT}, because other Autoconf macros liberally use the
1936 @command{set} command to process strings, and this has the side effect
1937 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1938 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1939 implement your own option processing.  @xref{Site Configuration}.
1941 @node Versioning
1942 @section Dealing with Autoconf versions
1943 @cindex Autoconf version
1944 @cindex version, Autoconf
1946 The following optional macros can be used to help choose the minimum
1947 version of Autoconf that can successfully compile a given
1948 @file{configure.ac}.
1950 @defmac AC_PREREQ (@var{version})
1951 @acindex{PREREQ}
1952 @cindex Version
1953 Ensure that a recent enough version of Autoconf is being used.  If the
1954 version of Autoconf being used to create @command{configure} is
1955 earlier than @var{version}, print an error message to the standard
1956 error output and exit with failure (exit status is 63).  For example:
1958 @example
1959 AC_PREREQ([@value{VERSION}])
1960 @end example
1962 This macro may be used before @code{AC_INIT}.
1963 @end defmac
1965 @defmac AC_AUTOCONF_VERSION
1966 @acindex{AUTOCONF_VERSION}
1967 This macro was introduced in Autoconf 2.62.  It identifies the version
1968 of Autoconf that is currently parsing the input file, in a format
1969 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1970 other words, for this release of Autoconf, its value is
1971 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1972 conditional fallbacks based on when a feature was added to Autoconf,
1973 rather than using @code{AC_PREREQ} to require the newer version of
1974 Autoconf.  However, remember that the Autoconf philosophy favors feature
1975 checks over version checks.
1977 You should not expand this macro directly; use
1978 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1979 users might
1980 have a beta version of Autoconf installed, with arbitrary letters
1981 included in its version string.  This means it is possible for the
1982 version string to contain the name of a defined macro, such that
1983 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1984 macro during rescanning, and change the version string to be different
1985 than what you intended to check.
1986 @end defmac
1988 @node Notices
1989 @section Notices in @command{configure}
1990 @cindex Notices in @command{configure}
1992 The following macros manage version numbers for @command{configure}
1993 scripts.  Using them is optional.
1995 @defmac AC_COPYRIGHT (@var{copyright-notice})
1996 @acindex{COPYRIGHT}
1997 @cindex Copyright Notice
1998 State that, in addition to the Free Software Foundation's copyright on
1999 the Autoconf macros, parts of your @command{configure} are covered by the
2000 @var{copyright-notice}.
2002 The @var{copyright-notice} shows up in both the head of
2003 @command{configure} and in @samp{configure --version}.
2004 @end defmac
2007 @defmac AC_REVISION (@var{revision-info})
2008 @acindex{REVISION}
2009 @cindex Revision
2010 Copy revision stamp @var{revision-info} into the @command{configure}
2011 script, with any dollar signs or double-quotes removed.  This macro lets
2012 you put a revision stamp from @file{configure.ac} into @command{configure}
2013 without RCS or CVS changing it when you check in
2014 @command{configure}.  That way, you can determine easily which revision of
2015 @file{configure.ac} a particular @command{configure} corresponds to.
2017 For example, this line in @file{configure.ac}:
2019 @c The @w prevents RCS from changing the example in the manual.
2020 @example
2021 AC_REVISION([@w{$}Revision: 1.30 $])
2022 @end example
2024 @noindent
2025 produces this in @command{configure}:
2027 @example
2028 #!/bin/sh
2029 # From configure.ac Revision: 1.30
2030 @end example
2031 @end defmac
2034 @node Input
2035 @section Finding @command{configure} Input
2037 @anchor{AC_CONFIG_SRCDIR}
2038 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
2039 @acindex{CONFIG_SRCDIR}
2040 @var{unique-file-in-source-dir} is some file that is in the package's
2041 source directory; @command{configure} checks for this file's existence to
2042 make sure that the directory that it is told contains the source code in
2043 fact does.  Occasionally people accidentally specify the wrong directory
2044 with @option{--srcdir}; this is a safety check.  @xref{configure
2045 Invocation}, for more information.
2046 @end defmac
2049 @c FIXME: Remove definitively once --install explained.
2051 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
2052 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
2053 @c to split the macros in several files.  In this case, Autoconf must be
2054 @c told which files to load, and in which order.
2056 @c @defmac AC_INCLUDE (@var{file}@dots{})
2057 @c @acindex{INCLUDE}
2058 @c @c FIXME: There is no longer shell globbing.
2059 @c Read the macro definitions that appear in the listed files.  A list of
2060 @c space-separated file names or shell globbing patterns is expected.  The
2061 @c files are read in the order they're listed.
2063 @c Because the order of definition of macros is important (only the last
2064 @c definition of a macro is used), beware that it is @code{AC_INIT} that
2065 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
2066 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
2067 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
2068 @c the latter case, non-macro lines from included files may end up in the
2069 @c @file{configure} script, whereas in the former case, they'd be discarded
2070 @c just like any text that appear before @code{AC_INIT}.
2071 @c @end defmac
2073 Packages that do manual configuration or use the @command{install} program
2074 might need to tell @command{configure} where to find some other shell
2075 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
2076 it looks are correct for most cases.
2078 @defmac AC_CONFIG_AUX_DIR (@var{dir})
2079 @acindex{CONFIG_AUX_DIR}
2080 Use the auxiliary build tools (e.g., @file{install-sh},
2081 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
2082 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
2083 These are auxiliary files used in configuration.  @var{dir} can be
2084 either absolute or relative to @file{@var{srcdir}}.  The default is
2085 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
2086 @file{@var{srcdir}/../..}, whichever is the first that contains
2087 @file{install-sh}.  The other files are not checked for, so that using
2088 @code{AC_PROG_INSTALL} does not automatically require distributing the
2089 other auxiliary files.  It checks for @file{install.sh} also, but that
2090 name is obsolete because some @command{make} have a rule that creates
2091 @file{install} from it if there is no makefile.
2093 The auxiliary directory is commonly named @file{build-aux}.
2094 If you need portability to DOS variants, do not name the
2095 auxiliary directory @file{aux}.  @xref{File System Conventions}.
2096 @end defmac
2098 @defmac AC_REQUIRE_AUX_FILE (@var{file})
2099 @acindex{REQUIRE_AUX_FILE}
2100 Declares that @var{file} is expected in the directory defined above.  In
2101 Autoconf proper, this macro does nothing: its sole purpose is to be
2102 traced by third-party tools to produce a list of expected auxiliary
2103 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
2104 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
2105 (@pxref{Canonicalizing}) to register the auxiliary files they need.
2106 @end defmac
2108 Similarly, packages that use @command{aclocal} should declare where
2109 local macros can be found using @code{AC_CONFIG_MACRO_DIRS}.
2111 @defmac AC_CONFIG_MACRO_DIRS (@var{dir1} [@var{dir2} ... @var{dirN}])
2112 @defmacx AC_CONFIG_MACRO_DIR (@var{dir})
2113 @acindex{CONFIG_MACRO_DIRS}
2114 @acindex{CONFIG_MACRO_DIR}
2115 @acindex{CONFIG_MACRO_DIR_TRACE}
2116 Specify the given directories as the location of additional local Autoconf
2117 macros.  These macros are intended for use by commands like
2118 @command{autoreconf} or @command{aclocal} that trace macro calls; they should
2119 be called directly from @file{configure.ac} so that tools that install
2120 macros for @command{aclocal} can find the macros' declarations.  Tools
2121 that want to learn which directories have been selected should trace
2122 @code{AC_CONFIG_MACRO_DIR_TRACE}, which will be called once per directory.
2124 AC_CONFIG_MACRO_DIRS is the preferred form, and can be called multiple
2125 times and with multiple arguments; in such cases, directories in earlier
2126 calls are expected to be searched before directories in later calls, and
2127 directories appearing in the same call are expected to be searched in
2128 the order in which they appear in the call.  For historical reasons, the
2129 macro AC_CONFIG_MACRO_DIR can also be used once, if it appears first,
2130 for tools such as older @command{libtool} that weren't prepared to
2131 handle multiple directories.  For example, a usage like
2133 @smallexample
2134 AC_CONFIG_MACRO_DIR([dir1])
2135 AC_CONFIG_MACRO_DIRS([dir2])
2136 AC_CONFIG_MACRO_DIRS([dir3 dir4])
2137 @end smallexample
2139 will cause the trace of AC_CONFIG_MACRO_DIR_TRACE to appear four times,
2140 and should cause the directories to be searched in this order:
2141 @samp{dir1 dir2 dir3 dir4}.
2143 Note that if you use @command{aclocal} from an Automake release prior to
2144 1.13 to generate @file{aclocal.m4}, you must also set
2145 @code{ACLOCAL_AMFLAGS = -I @var{dir1} [-I @var{dir2} ... -I @var{dirN}]}
2146 in your top-level @file{Makefile.am}.  Due to a limitation in
2147 the Autoconf implementation of @command{autoreconf}, these include
2148 directives currently must be set on a single line in @file{Makefile.am},
2149 without any backslash-newlines.
2150 @end defmac
2153 @node Output
2154 @section Outputting Files
2155 @cindex Outputting files
2157 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2158 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2159 @file{config.status}, which in turn creates the makefiles and any
2160 other files resulting from configuration.  This is the only required
2161 macro besides @code{AC_INIT} (@pxref{Input}).
2163 @anchor{AC_OUTPUT}
2164 @defmac AC_OUTPUT
2165 @acindex{OUTPUT}
2166 @cindex Instantiation
2167 Generate @file{config.status} and launch it.  Call this macro once, at
2168 the end of @file{configure.ac}.
2170 @file{config.status} performs all the configuration actions: all the
2171 output files (see @ref{Configuration Files}, macro
2172 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2173 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2174 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2175 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2176 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2177 are honored.
2179 The location of your @code{AC_OUTPUT} invocation is the exact point
2180 where configuration actions are taken: any code afterwards is
2181 executed by @command{configure} once @command{config.status} was run.  If
2182 you want to bind actions to @command{config.status} itself
2183 (independently of whether @command{configure} is being run), see
2184 @ref{Configuration Commands, , Running Arbitrary Configuration
2185 Commands}.
2186 @end defmac
2188 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2189 @xref{Obsolete Macros}, for a description of the arguments that
2190 @code{AC_OUTPUT} used to support.
2193 If you run @command{make} in subdirectories, you should run it using the
2194 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2195 @code{MAKE} to the name of the @command{make} program plus any options it
2196 was given.  (But many do not include in it the values of any variables
2197 set on the command line, so those are not passed on automatically.)
2198 Some old versions of @command{make} do not set this variable.  The
2199 following macro allows you to use it even with those versions.
2201 @anchor{AC_PROG_MAKE_SET}
2202 @defmac AC_PROG_MAKE_SET
2203 @acindex{PROG_MAKE_SET}
2204 @ovindex SET_MAKE
2205 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2206 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2207 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2208 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2209 @code{SET_MAKE}.
2210 @end defmac
2212 If you use this macro, place a line like this in each @file{Makefile.in}
2213 that runs @command{MAKE} on other directories:
2215 @example
2216 @@SET_MAKE@@
2217 @end example
2221 @node Configuration Actions
2222 @section Performing Configuration Actions
2223 @cindex Configuration actions
2225 @file{configure} is designed so that it appears to do everything itself,
2226 but there is actually a hidden slave: @file{config.status}.
2227 @file{configure} is in charge of examining your system, but it is
2228 @file{config.status} that actually takes the proper actions based on the
2229 results of @file{configure}.  The most typical task of
2230 @file{config.status} is to @emph{instantiate} files.
2232 @acindex{CONFIG_@var{ITEMS}}
2233 This section describes the common behavior of the four standard
2234 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2235 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2236 have this prototype:
2238 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2239 @c awful.
2240 @example
2241 AC_CONFIG_@var{ITEMS}(@var{tag}@dots{}, @r{[}@var{commands}@r{]}, @r{[}@var{init-cmds}@r{]})
2242 @end example
2244 @noindent
2245 where the arguments are:
2247 @table @var
2248 @item tag@dots{}
2249 A blank-or-newline-separated list of tags, which are typically the names of
2250 the files to instantiate.
2252 You are encouraged to use literals as @var{tags}.  In particular, you
2253 should avoid
2255 @example
2256 @dots{} && my_foos="$my_foos fooo"
2257 @dots{} && my_foos="$my_foos foooo"
2258 AC_CONFIG_@var{ITEMS}([$my_foos])
2259 @end example
2261 @noindent
2262 and use this instead:
2264 @example
2265 @dots{} && AC_CONFIG_@var{ITEMS}([fooo])
2266 @dots{} && AC_CONFIG_@var{ITEMS}([foooo])
2267 @end example
2269 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2270 special @var{tag} values: they may have the form @samp{@var{output}} or
2271 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2272 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2274 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk])},
2275 for example, asks for
2276 the creation of the file @file{Makefile} that contains the expansion of the
2277 output variables in the concatenation of @file{boiler/top.mk} and
2278 @file{boiler/bot.mk}.
2280 The special value @samp{-} might be used to denote the standard output
2281 when used in @var{output}, or the standard input when used in the
2282 @var{inputs}.  You most probably don't need to use this in
2283 @file{configure.ac}, but it is convenient when using the command line
2284 interface of @file{./config.status}, see @ref{config.status Invocation},
2285 for more details.
2287 The @var{inputs} may be absolute or relative file names.  In the latter
2288 case they are first looked for in the build tree, and then in the source
2289 tree.  Input files should be text files, and a line length below 2000
2290 bytes should be safe.
2292 @item commands
2293 Shell commands output literally into @file{config.status}, and
2294 associated with a tag that the user can use to tell @file{config.status}
2295 which commands to run.  The commands are run each time a @var{tag}
2296 request is given to @file{config.status}, typically each time the file
2297 @file{@var{tag}} is created.
2299 The variables set during the execution of @command{configure} are
2300 @emph{not} available here: you first need to set them via the
2301 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2303 @table @code
2304 @item srcdir
2305 @vrindex srcdir
2306 The name of the top source directory, assuming that the working
2307 directory is the top build directory.  This
2308 is what the @command{configure} option @option{--srcdir} sets.
2310 @item ac_top_srcdir
2311 @vrindex ac_top_srcdir
2312 The name of the top source directory, assuming that the working
2313 directory is the current build directory.
2315 @item ac_top_build_prefix
2316 @vrindex ac_top_build_prefix
2317 The name of the top build directory, assuming that the working
2318 directory is the current build directory.
2319 It can be empty, or else ends with a slash, so that you may concatenate
2322 @item ac_srcdir
2323 @vrindex ac_srcdir
2324 The name of the corresponding source directory, assuming that the
2325 working directory is the current build directory.
2327 @item tmp
2328 @vrindex tmp
2329 The name of a temporary directory within the build tree, which you
2330 can use if you need to create additional temporary files.  The
2331 directory is cleaned up when @command{config.status} is done or
2332 interrupted.  Please use package-specific file name prefixes to
2333 avoid clashing with files that @command{config.status} may use
2334 internally.
2335 @end table
2337 @noindent
2338 The @dfn{current} directory refers to the directory (or
2339 pseudo-directory) containing the input part of @var{tags}.  For
2340 instance, running
2342 @example
2343 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2344 @end example
2346 @noindent
2347  with @option{--srcdir=../package} produces the following values:
2349 @example
2350 # Argument of --srcdir
2351 srcdir='../package'
2352 # Reversing deep/dir
2353 ac_top_build_prefix='../../'
2354 # Concatenation of $ac_top_build_prefix and srcdir
2355 ac_top_srcdir='../../../package'
2356 # Concatenation of $ac_top_srcdir and deep/dir
2357 ac_srcdir='../../../package/deep/dir'
2358 @end example
2360 @noindent
2361 independently of @samp{in/in.in}.
2363 @item init-cmds
2364 Shell commands output @emph{unquoted} near the beginning of
2365 @file{config.status}, and executed each time @file{config.status} runs
2366 (regardless of the tag).  Because they are unquoted, for example,
2367 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2368 is typically used by @file{configure} to give @file{config.status} some
2369 variables it needs to run the @var{commands}.
2371 You should be extremely cautious in your variable names: all the
2372 @var{init-cmds} share the same name space and may overwrite each other
2373 in unpredictable ways.  Sorry@enddots{}
2374 @end table
2376 All these macros can be called multiple times, with different
2377 @var{tag} values, of course!
2380 @node Configuration Files
2381 @section Creating Configuration Files
2382 @cindex Creating configuration files
2383 @cindex Configuration file creation
2385 Be sure to read the previous section, @ref{Configuration Actions}.
2387 @anchor{AC_CONFIG_FILES}
2388 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2389 @acindex{CONFIG_FILES}
2390 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2391 file (by default @file{@var{file}.in}), substituting the output variable
2392 values.
2393 @c Before we used to have this feature, which was later rejected
2394 @c because it complicates the writing of makefiles:
2395 @c If the file would be unchanged, it is left untouched, to preserve
2396 @c timestamp.
2397 This macro is one of the instantiating macros; see @ref{Configuration
2398 Actions}.  @xref{Makefile Substitutions}, for more information on using
2399 output variables.  @xref{Setting Output Variables}, for more information
2400 on creating them.  This macro creates the directory that the file is in
2401 if it doesn't exist.  Usually, makefiles are created this way,
2402 but other files, such as @file{.gdbinit}, can be specified as well.
2404 Typical calls to @code{AC_CONFIG_FILES} look like this:
2406 @example
2407 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2408 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2409 @end example
2411 You can override an input file name by appending to @var{file} a
2412 colon-separated list of input files.  Examples:
2414 @example
2415 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2416                 [lib/Makefile:boiler/lib.mk])
2417 @end example
2419 @noindent
2420 Doing this allows you to keep your file names acceptable to
2421 DOS variants, or
2422 to prepend and/or append boilerplate to the file.
2423 @end defmac
2427 @node Makefile Substitutions
2428 @section Substitutions in Makefiles
2429 @cindex Substitutions in makefiles
2430 @cindex Makefile substitutions
2432 Each subdirectory in a distribution that contains something to be
2433 compiled or installed should come with a file @file{Makefile.in}, from
2434 which @command{configure} creates a file @file{Makefile} in that directory.
2435 To create @file{Makefile}, @command{configure} performs a simple variable
2436 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2437 @file{Makefile.in} with the value that @command{configure} has determined
2438 for that variable.  Variables that are substituted into output files in
2439 this way are called @dfn{output variables}.  They are ordinary shell
2440 variables that are set in @command{configure}.  To make @command{configure}
2441 substitute a particular variable into the output files, the macro
2442 @code{AC_SUBST} must be called with that variable name as an argument.
2443 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2444 left unchanged.  @xref{Setting Output Variables}, for more information
2445 on creating output variables with @code{AC_SUBST}.
2447 A software package that uses a @command{configure} script should be
2448 distributed with a file @file{Makefile.in}, but no makefile; that
2449 way, the user has to properly configure the package for the local system
2450 before compiling it.
2452 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2453 GNU Coding Standards}, for more information on what to put in
2454 makefiles.
2456 @menu
2457 * Preset Output Variables::     Output variables that are always set
2458 * Installation Directory Variables::  Other preset output variables
2459 * Changed Directory Variables::  Warnings about @file{datarootdir}
2460 * Build Directories::           Supporting multiple concurrent compiles
2461 * Automatic Remaking::          Makefile rules for configuring
2462 @end menu
2464 @node Preset Output Variables
2465 @subsection Preset Output Variables
2466 @cindex Output variables
2468 Some output variables are preset by the Autoconf macros.  Some of the
2469 Autoconf macros set additional output variables, which are mentioned in
2470 the descriptions for those macros.  @xref{Output Variable Index}, for a
2471 complete list of output variables.  @xref{Installation Directory
2472 Variables}, for the list of the preset ones related to installation
2473 directories.  Below are listed the other preset ones, many of which are
2474 precious variables (@pxref{Setting Output Variables},
2475 @code{AC_ARG_VAR}).
2477 The preset variables which are available during @file{config.status}
2478 (@pxref{Configuration Actions}) may also be used during
2479 @command{configure} tests.  For example, it is permissible to reference
2480 @samp{$srcdir} when constructing a list of directories to pass via
2481 option @option{-I} during a compiler feature check.  When used in this
2482 manner, coupled with the fact that @command{configure} is always run
2483 from the top build directory, it is sufficient to use just
2484 @samp{$srcdir} instead of @samp{$top_srcdir}.
2486 @c Just say no to ASCII sorting!  We're humans, not computers.
2487 @c These variables are listed as they would be in a dictionary:
2488 @c actor
2489 @c Actress
2490 @c actress
2492 @defvar CFLAGS
2493 @evindex CFLAGS
2494 @ovindex CFLAGS
2495 Debugging and optimization options for the C compiler.  If it is not set
2496 in the environment when @command{configure} runs, the default value is set
2497 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2498 uses this variable when compiling or linking programs to test for C features.
2500 If a compiler option affects only the behavior of the preprocessor
2501 (e.g., @option{-D@var{name}}), it should be put into @code{CPPFLAGS}
2502 instead.  If it affects only the linker (e.g., @option{-L@var{directory}}),
2503 it should be put into @code{LDFLAGS} instead.  If it
2504 affects only the compiler proper, @code{CFLAGS} is the natural home for
2505 it.  If an option affects multiple phases of the compiler, though,
2506 matters get tricky.  One approach to put such options directly into
2507 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2508 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2510 However, remember that some @file{Makefile} variables are reserved by
2511 the GNU Coding Standards for the use of the ``user''---the person
2512 building the package.  For instance, @code{CFLAGS} is one such variable.
2514 Sometimes package developers are tempted to set user variables such as
2515 @code{CFLAGS} because it appears to make their job easier.  However, the
2516 package itself should never set a user variable, particularly not to
2517 include switches that are required for proper compilation of the
2518 package.  Since these variables are documented as being for the package
2519 builder, that person rightfully expects to be able to override any of
2520 these variables at build time.  If the package developer needs to add
2521 switches without interfering with the user, the proper way to do that is
2522 to introduce an additional variable.  Automake makes this easy by
2523 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2524 automake, GNU Automake}), but the concept is the same even if
2525 Automake is not used.
2526 @end defvar
2528 @defvar configure_input
2529 @ovindex configure_input
2530 A comment saying that the file was generated automatically by
2531 @command{configure} and giving the name of the input file.
2532 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2533 of every makefile it creates.  For other files, you should
2534 reference this variable in a comment at the top of each input file.  For
2535 example, an input shell script should begin like this:
2537 @example
2538 #!/bin/sh
2539 # @@configure_input@@
2540 @end example
2542 @noindent
2543 The presence of that line also reminds people editing the file that it
2544 needs to be processed by @command{configure} in order to be used.
2545 @end defvar
2547 @defvar CPPFLAGS
2548 @evindex CPPFLAGS
2549 @ovindex CPPFLAGS
2550 Preprocessor options for the C, C++, Objective C, and Objective C++
2551 preprocessors and compilers.  If
2552 it is not set in the environment when @command{configure} runs, the default
2553 value is empty.  @command{configure} uses this variable when preprocessing
2554 or compiling programs to test for C, C++, Objective C, and Objective C++
2555 features.
2557 This variable's contents should contain options like @option{-I},
2558 @option{-D}, and @option{-U} that affect only the behavior of the
2559 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2560 can do if an option affects other phases of the compiler as well.
2562 Currently, @command{configure} always links as part of a single
2563 invocation of the compiler that also preprocesses and compiles, so it
2564 uses this variable also when linking programs.  However, it is unwise to
2565 depend on this behavior because the GNU Coding Standards do
2566 not require it and many packages do not use @code{CPPFLAGS} when linking
2567 programs.
2569 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2570 might run into.
2571 @end defvar
2573 @defvar CXXFLAGS
2574 @evindex CXXFLAGS
2575 @ovindex CXXFLAGS
2576 Debugging and optimization options for the C++ compiler.  It acts like
2577 @code{CFLAGS}, but for C++ instead of C.
2578 @end defvar
2580 @defvar DEFS
2581 @ovindex DEFS
2582 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2583 is called, @command{configure} replaces @samp{@@DEFS@@} with
2584 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2585 variable is not defined while @command{configure} is performing its tests,
2586 only when creating the output files.  @xref{Setting Output Variables}, for
2587 how to check the results of previous tests.
2588 @end defvar
2590 @defvar ECHO_C
2591 @defvarx ECHO_N
2592 @defvarx ECHO_T
2593 @ovindex ECHO_C
2594 @ovindex ECHO_N
2595 @ovindex ECHO_T
2596 How does one suppress the trailing newline from @command{echo} for
2597 question-answer message pairs?  These variables provide a way:
2599 @example
2600 echo $ECHO_N "And the winner is... $ECHO_C"
2601 sleep 100000000000
2602 echo "$@{ECHO_T@}dead."
2603 @end example
2605 @noindent
2606 Some old and uncommon @command{echo} implementations offer no means to
2607 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2608 want to use it.
2609 @end defvar
2611 @defvar ERLCFLAGS
2612 @evindex ERLCFLAGS
2613 @ovindex ERLCFLAGS
2614 Debugging and optimization options for the Erlang compiler.  If it is not set
2615 in the environment when @command{configure} runs, the default value is empty.
2616 @command{configure} uses this variable when compiling
2617 programs to test for Erlang features.
2618 @end defvar
2620 @defvar FCFLAGS
2621 @evindex FCFLAGS
2622 @ovindex FCFLAGS
2623 Debugging and optimization options for the Fortran compiler.  If it
2624 is not set in the environment when @command{configure} runs, the default
2625 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2626 @command{configure} uses this variable when compiling or linking
2627 programs to test for Fortran features.
2628 @end defvar
2630 @defvar FFLAGS
2631 @evindex FFLAGS
2632 @ovindex FFLAGS
2633 Debugging and optimization options for the Fortran 77 compiler.  If it
2634 is not set in the environment when @command{configure} runs, the default
2635 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2636 @command{configure} uses this variable when compiling or linking
2637 programs to test for Fortran 77 features.
2638 @end defvar
2640 @defvar LDFLAGS
2641 @evindex LDFLAGS
2642 @ovindex LDFLAGS
2643 Options for the linker.  If it is not set
2644 in the environment when @command{configure} runs, the default value is empty.
2645 @command{configure} uses this variable when linking programs to test for
2646 C, C++, Objective C, Objective C++, Fortran, and Go features.
2648 This variable's contents should contain options like @option{-s} and
2649 @option{-L} that affect only the behavior of the linker.  Please see the
2650 explanation of @code{CFLAGS} for what you can do if an option also
2651 affects other phases of the compiler.
2653 Don't use this variable to pass library names
2654 (@option{-l}) to the linker; use @code{LIBS} instead.
2655 @end defvar
2657 @defvar LIBS
2658 @evindex LIBS
2659 @ovindex LIBS
2660 @option{-l} options to pass to the linker.  The default value is empty,
2661 but some Autoconf macros may prepend extra libraries to this variable if
2662 those libraries are found and provide necessary functions, see
2663 @ref{Libraries}.  @command{configure} uses this variable when linking
2664 programs to test for C, C++, Objective C, Objective C++, Fortran, and Go
2665 features.
2666 @end defvar
2668 @defvar OBJCFLAGS
2669 @evindex OBJCFLAGS
2670 @ovindex OBJCFLAGS
2671 Debugging and optimization options for the Objective C compiler.  It
2672 acts like @code{CFLAGS}, but for Objective C instead of C.
2673 @end defvar
2675 @defvar OBJCXXFLAGS
2676 @evindex OBJCXXFLAGS
2677 @ovindex OBJCXXFLAGS
2678 Debugging and optimization options for the Objective C++ compiler.  It
2679 acts like @code{CXXFLAGS}, but for Objective C++ instead of C++.
2680 @end defvar
2682 @defvar GOFLAGS
2683 @evindex GOFLAGS
2684 @ovindex GOFLAGS
2685 Debugging and optimization options for the Go compiler.  It acts like
2686 @code{CFLAGS}, but for Go instead of C.
2687 @end defvar
2689 @defvar builddir
2690 @ovindex builddir
2691 Rigorously equal to @samp{.}.  Added for symmetry only.
2692 @end defvar
2694 @defvar abs_builddir
2695 @ovindex abs_builddir
2696 Absolute name of @code{builddir}.
2697 @end defvar
2699 @defvar top_builddir
2700 @ovindex top_builddir
2701 The relative name of the top level of the current build tree.  In the
2702 top-level directory, this is the same as @code{builddir}.
2703 @end defvar
2705 @defvar top_build_prefix
2706 @ovindex top_build_prefix
2707 The relative name of the top level of the current build tree with final
2708 slash if nonempty.  This is the same as @code{top_builddir}, except that
2709 it contains zero or more runs of @code{../}, so it should not be
2710 appended with a slash for concatenation.  This helps for @command{make}
2711 implementations that otherwise do not treat @file{./file} and @file{file}
2712 as equal in the toplevel build directory.
2713 @end defvar
2715 @defvar abs_top_builddir
2716 @ovindex abs_top_builddir
2717 Absolute name of @code{top_builddir}.
2718 @end defvar
2720 @defvar srcdir
2721 @ovindex srcdir
2722 The name of the directory that contains the source code for
2723 that makefile.
2724 @end defvar
2726 @defvar abs_srcdir
2727 @ovindex abs_srcdir
2728 Absolute name of @code{srcdir}.
2729 @end defvar
2731 @defvar top_srcdir
2732 @ovindex top_srcdir
2733 The name of the top-level source code directory for the
2734 package.  In the top-level directory, this is the same as @code{srcdir}.
2735 @end defvar
2737 @defvar abs_top_srcdir
2738 @ovindex abs_top_srcdir
2739 Absolute name of @code{top_srcdir}.
2740 @end defvar
2742 @node Installation Directory Variables
2743 @subsection Installation Directory Variables
2744 @cindex Installation directories
2745 @cindex Directories, installation
2747 The following variables specify the directories for
2748 package installation, see @ref{Directory Variables, , Variables for
2749 Installation Directories, standards, The GNU Coding
2750 Standards}, for more information.  Each variable corresponds to an
2751 argument of @command{configure}; trailing slashes are stripped so that
2752 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2753 between directory names.  See the end of this section for
2754 details on when and how to use these variables.
2756 @defvar bindir
2757 @ovindex bindir
2758 The directory for installing executables that users run.
2759 @end defvar
2761 @defvar datadir
2762 @ovindex datadir
2763 The directory for installing idiosyncratic read-only
2764 architecture-independent data.
2765 @end defvar
2767 @defvar datarootdir
2768 @ovindex datarootdir
2769 The root of the directory tree for read-only architecture-independent
2770 data files.
2771 @end defvar
2773 @defvar docdir
2774 @ovindex docdir
2775 The directory for installing documentation files (other than Info and
2776 man).
2777 @end defvar
2779 @defvar dvidir
2780 @ovindex dvidir
2781 The directory for installing documentation files in DVI format.
2782 @end defvar
2784 @defvar exec_prefix
2785 @ovindex exec_prefix
2786 The installation prefix for architecture-dependent files.  By default
2787 it's the same as @code{prefix}.  You should avoid installing anything
2788 directly to @code{exec_prefix}.  However, the default value for
2789 directories containing architecture-dependent files should be relative
2790 to @code{exec_prefix}.
2791 @end defvar
2793 @defvar htmldir
2794 @ovindex htmldir
2795 The directory for installing HTML documentation.
2796 @end defvar
2798 @defvar includedir
2799 @ovindex includedir
2800 The directory for installing C header files.
2801 @end defvar
2803 @defvar infodir
2804 @ovindex infodir
2805 The directory for installing documentation in Info format.
2806 @end defvar
2808 @defvar libdir
2809 @ovindex libdir
2810 The directory for installing object code libraries.
2811 @end defvar
2813 @defvar libexecdir
2814 @ovindex libexecdir
2815 The directory for installing executables that other programs run.
2816 @end defvar
2818 @defvar localedir
2819 @ovindex localedir
2820 The directory for installing locale-dependent but
2821 architecture-independent data, such as message catalogs.  This directory
2822 usually has a subdirectory per locale.
2823 @end defvar
2825 @defvar localstatedir
2826 @ovindex localstatedir
2827 The directory for installing modifiable single-machine data.  Content in
2828 this directory typically survives a reboot.
2829 @end defvar
2831 @defvar runstatedir
2832 @ovindex runstatedir
2833 The directory for installing temporary modifiable single-machine data.
2834 Content in this directory survives as long as the process is running
2835 (such as pid files), as contrasted with @file{/tmp} that may be
2836 periodically cleaned.  Conversely, this directory is typically cleaned
2837 on a reboot.  By default, this is a subdirectory of
2838 @code{localstatedir}.
2839 @end defvar
2841 @defvar mandir
2842 @ovindex mandir
2843 The top-level directory for installing documentation in man format.
2844 @end defvar
2846 @defvar oldincludedir
2847 @ovindex oldincludedir
2848 The directory for installing C header files for non-GCC compilers.
2849 @end defvar
2851 @defvar pdfdir
2852 @ovindex pdfdir
2853 The directory for installing PDF documentation.
2854 @end defvar
2856 @defvar prefix
2857 @ovindex prefix
2858 The common installation prefix for all files.  If @code{exec_prefix}
2859 is defined to a different value, @code{prefix} is used only for
2860 architecture-independent files.
2861 @end defvar
2863 @defvar psdir
2864 @ovindex psdir
2865 The directory for installing PostScript documentation.
2866 @end defvar
2868 @defvar sbindir
2869 @ovindex sbindir
2870 The directory for installing executables that system
2871 administrators run.
2872 @end defvar
2874 @defvar sharedstatedir
2875 @ovindex sharedstatedir
2876 The directory for installing modifiable architecture-independent data.
2877 @end defvar
2879 @defvar sysconfdir
2880 @ovindex sysconfdir
2881 The directory for installing read-only single-machine data.
2882 @end defvar
2885 Most of these variables have values that rely on @code{prefix} or
2886 @code{exec_prefix}.  It is deliberate that the directory output
2887 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2888 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2889 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2891 This behavior is mandated by the GNU Coding Standards, so that when
2892 the user runs:
2894 @table @samp
2895 @item make
2896 she can still specify a different prefix from the one specified to
2897 @command{configure}, in which case, if needed, the package should hard
2898 code dependencies corresponding to the make-specified prefix.
2900 @item make install
2901 she can specify a different installation location, in which case the
2902 package @emph{must} still depend on the location which was compiled in
2903 (i.e., never recompile when @samp{make install} is run).  This is an
2904 extremely important feature, as many people may decide to install all
2905 the files of a package grouped together, and then install links from
2906 the final locations to there.
2907 @end table
2909 In order to support these features, it is essential that
2910 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2911 so that its value can be expanded based
2912 on the current value of @code{prefix}.
2914 A corollary is that you should not use these variables except in
2915 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2916 in @file{configure} and hard-coding it in makefiles using
2917 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2918 you should add
2919 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2920 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2922 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2923 @code{bindir} and friends in your shell scripts and other files; instead,
2924 let @command{make} manage their replacement.  For instance Autoconf
2925 ships templates of its shell scripts ending with @samp{.in}, and uses a
2926 makefile snippet similar to the following to build scripts like
2927 @command{autoheader} and @command{autom4te}:
2929 @example
2930 @group
2931 edit = sed \
2932         -e 's|@@bindir[@@]|$(bindir)|g' \
2933         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2934         -e 's|@@prefix[@@]|$(prefix)|g'
2935 @end group
2937 @group
2938 autoheader autom4te: Makefile
2939         rm -f $@@ $@@.tmp
2940         srcdir=''; \
2941           test -f ./$@@.in || srcdir=$(srcdir)/; \
2942           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2943 @c $$ restore font-lock
2944         chmod +x $@@.tmp
2945         chmod a-w $@@.tmp
2946         mv $@@.tmp $@@
2947 @end group
2949 @group
2950 autoheader: $(srcdir)/autoheader.in
2951 autom4te: $(srcdir)/autom4te.in
2952 @end group
2953 @end example
2955 Some details are noteworthy:
2957 @table @asis
2958 @item @samp{@@bindir[@@]}
2959 The brackets prevent @command{configure} from replacing
2960 @samp{@@bindir@@} in the Sed expression itself.
2961 Brackets are preferable to a backslash here, since
2962 Posix says @samp{\@@} is not portable.
2964 @item @samp{$(bindir)}
2965 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2966 instead.
2968 @item @samp{$(pkgdatadir)}
2969 The example takes advantage of the variable @samp{$(pkgdatadir)}
2970 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2972 @item @samp{/}
2973 Don't use @samp{/} in the Sed expressions that replace file names since
2974 most likely the
2975 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2976 Use a shell metacharacter instead, such as @samp{|}.
2978 @item special characters
2979 File names, file name components, and the value of @code{VPATH} should
2980 not contain shell metacharacters or white
2981 space.  @xref{Special Chars in Variables}.
2983 @item dependency on @file{Makefile}
2984 Since @code{edit} uses values that depend on the configuration specific
2985 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2986 the output depends on @file{Makefile}, not @file{configure.ac}.
2988 @item @samp{$@@}
2989 The main rule is generic, and uses @samp{$@@} extensively to
2990 avoid the need for multiple copies of the rule.
2992 @item Separated dependencies and single suffix rules
2993 You can't use them!  The above snippet cannot be (portably) rewritten
2996 @example
2997 autoconf autoheader: Makefile
2998 @group
2999 .in:
3000         rm -f $@@ $@@.tmp
3001         $(edit) $< >$@@.tmp
3002         chmod +x $@@.tmp
3003         mv $@@.tmp $@@
3004 @end group
3005 @end example
3007 @xref{Single Suffix Rules}, for details.
3009 @item @samp{$(srcdir)}
3010 Be sure to specify the name of the source directory,
3011 otherwise the package won't support separated builds.
3012 @end table
3014 For the more specific installation of Erlang libraries, the following variables
3015 are defined:
3017 @defvar ERLANG_INSTALL_LIB_DIR
3018 @ovindex ERLANG_INSTALL_LIB_DIR
3019 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
3020 The common parent directory of Erlang library installation directories.
3021 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
3022 macro in @file{configure.ac}.
3023 @end defvar
3025 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
3026 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
3027 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3028 The installation directory for Erlang library @var{library}.
3029 This variable is set by using the
3030 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
3031 macro in @file{configure.ac}.
3032 @end defvar
3034 @xref{Erlang Libraries}, for details.
3037 @node Changed Directory Variables
3038 @subsection Changed Directory Variables
3039 @cindex @file{datarootdir}
3041 In Autoconf 2.60, the set of directory variables has changed, and the
3042 defaults of some variables have been adjusted
3043 (@pxref{Installation Directory Variables}) to changes in the
3044 GNU Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
3045 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
3046 upgrading from an earlier Autoconf version, you may need to adjust your files
3047 to ensure that the directory variables are substituted correctly
3048 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
3049 in place.  For example, in a @file{Makefile.in}, adding
3051 @example
3052 datarootdir = @@datarootdir@@
3053 @end example
3055 @noindent
3056 is usually sufficient.  If you use Automake to create @file{Makefile.in},
3057 it will add this for you.
3059 To help with the transition, Autoconf warns about files that seem to use
3060 @code{datarootdir} without defining it.  In some cases, it then expands
3061 the value of @code{$datarootdir} in substitutions of the directory
3062 variables.  The following example shows such a warning:
3064 @example
3065 $ @kbd{cat configure.ac}
3066 AC_INIT
3067 AC_CONFIG_FILES([Makefile])
3068 AC_OUTPUT
3069 $ @kbd{cat Makefile.in}
3070 prefix = @@prefix@@
3071 datadir = @@datadir@@
3072 $ @kbd{autoconf}
3073 $ @kbd{configure}
3074 configure: creating ./config.status
3075 config.status: creating Makefile
3076 config.status: WARNING:
3077                Makefile.in seems to ignore the --datarootdir setting
3078 $ @kbd{cat Makefile}
3079 prefix = /usr/local
3080 datadir = $@{prefix@}/share
3081 @end example
3083 Usually one can easily change the file to accommodate both older and newer
3084 Autoconf releases:
3086 @example
3087 $ @kbd{cat Makefile.in}
3088 prefix = @@prefix@@
3089 datarootdir = @@datarootdir@@
3090 datadir = @@datadir@@
3091 $ @kbd{configure}
3092 configure: creating ./config.status
3093 config.status: creating Makefile
3094 $ @kbd{cat Makefile}
3095 prefix = /usr/local
3096 datarootdir = $@{prefix@}/share
3097 datadir = $@{datarootdir@}
3098 @end example
3100 @acindex{DATAROOTDIR_CHECKED}
3101 In some cases, however, the checks may not be able to detect that a suitable
3102 initialization of @code{datarootdir} is in place, or they may fail to detect
3103 that such an initialization is necessary in the output file.  If, after
3104 auditing your package, there are still spurious @file{configure} warnings about
3105 @code{datarootdir}, you may add the line
3107 @example
3108 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
3109 @end example
3111 @noindent
3112 to your @file{configure.ac} to disable the warnings.  This is an exception
3113 to the usual rule that you should not define a macro whose name begins with
3114 @code{AC_} (@pxref{Macro Names}).
3118 @node Build Directories
3119 @subsection Build Directories
3120 @cindex Build directories
3121 @cindex Directories, build
3123 You can support compiling a software package for several architectures
3124 simultaneously from the same copy of the source code.  The object files
3125 for each architecture are kept in their own directory.
3127 To support doing this, @command{make} uses the @code{VPATH} variable to
3128 find the files that are in the source directory.  GNU Make
3129 can do this.  Most other recent @command{make} programs can do this as
3130 well, though they may have difficulties and it is often simpler to
3131 recommend GNU @command{make} (@pxref{VPATH and Make}).  Older
3132 @command{make} programs do not support @code{VPATH}; when using them, the
3133 source code must be in the same directory as the object files.
3135 If you are using GNU Automake, the remaining details in this
3136 section are already covered for you, based on the contents of your
3137 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
3138 supporting @code{VPATH} requires the following in your
3139 @file{Makefile.in}:
3141 @example
3142 srcdir = @@srcdir@@
3143 VPATH = @@srcdir@@
3144 @end example
3146 Do not set @code{VPATH} to the value of another variable (@pxref{Variables
3147 listed in VPATH}.
3149 @command{configure} substitutes the correct value for @code{srcdir} when
3150 it produces @file{Makefile}.
3152 Do not use the @command{make} variable @code{$<}, which expands to the
3153 file name of the file in the source directory (found with @code{VPATH}),
3154 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
3155 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
3156 versions of @command{make} do not set @code{$<} in explicit rules; they
3157 expand it to an empty value.
3159 Instead, Make command lines should always refer to source
3160 files by prefixing them with @samp{$(srcdir)/}.  It's safer
3161 to quote the source directory name, in case it contains characters that
3162 are special to the shell.  Because @samp{$(srcdir)} is expanded by Make,
3163 single-quoting works and is safer than double-quoting.  For example:
3165 @example
3166 time.info: time.texinfo
3167         $(MAKEINFO) '$(srcdir)/time.texinfo'
3168 @end example
3170 @node Automatic Remaking
3171 @subsection Automatic Remaking
3172 @cindex Automatic remaking
3173 @cindex Remaking automatically
3175 You can put rules like the following in the top-level @file{Makefile.in}
3176 for a package to automatically update the configuration information when
3177 you change the configuration files.  This example includes all of the
3178 optional files, such as @file{aclocal.m4} and those related to
3179 configuration header files.  Omit from the @file{Makefile.in} rules for
3180 any of these files that your package does not use.
3182 The @samp{$(srcdir)/} prefix is included because of limitations in the
3183 @code{VPATH} mechanism.
3185 The @file{stamp-} files are necessary because the timestamps of
3186 @file{config.h.in} and @file{config.h} are not changed if remaking
3187 them does not change their contents.  This feature avoids unnecessary
3188 recompilation.  You should include the file @file{stamp-h.in} in your
3189 package's distribution, so that @command{make} considers
3190 @file{config.h.in} up to date.  Don't use @command{touch}
3191 (@pxref{touch, , Limitations of Usual Tools}); instead, use
3192 @command{echo} (using
3193 @command{date} would cause needless differences, hence CVS
3194 conflicts, etc.).
3196 @example
3197 @group
3198 $(srcdir)/configure: configure.ac aclocal.m4
3199         cd '$(srcdir)' && autoconf
3201 # autoheader might not change config.h.in, so touch a stamp file.
3202 $(srcdir)/config.h.in: stamp-h.in ;
3203 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3204         cd '$(srcdir)' && autoheader
3205         echo timestamp > '$(srcdir)/stamp-h.in'
3207 config.h: stamp-h ;
3208 stamp-h: config.h.in config.status
3209         ./config.status
3211 Makefile: Makefile.in config.status
3212         ./config.status
3214 config.status: configure
3215         ./config.status --recheck
3216 @end group
3217 @end example
3219 @noindent
3220 (Be careful if you copy these lines directly into your makefile, as you
3221 need to convert the indented lines to start with the tab character.)
3223 In addition, you should use
3225 @example
3226 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3227 @end example
3229 @noindent
3230 so @file{config.status} ensures that @file{config.h} is considered up to
3231 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3233 @xref{config.status Invocation}, for more examples of handling
3234 configuration-related dependencies.
3236 @node Configuration Headers
3237 @section Configuration Header Files
3238 @cindex Configuration Header
3239 @cindex @file{config.h}
3241 When a package contains more than a few tests that define C preprocessor
3242 symbols, the command lines to pass @option{-D} options to the compiler
3243 can get quite long.  This causes two problems.  One is that the
3244 @command{make} output is hard to visually scan for errors.  More
3245 seriously, the command lines can exceed the length limits of some
3246 operating systems.  As an alternative to passing @option{-D} options to
3247 the compiler, @command{configure} scripts can create a C header file
3248 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3249 macro selects this kind of output.  Though it can be called anywhere
3250 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3251 it right after @code{AC_INIT}.
3253 The package should @samp{#include} the configuration header file before
3254 any other header files, to prevent inconsistencies in declarations (for
3255 example, if it redefines @code{const}).
3257 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3258 option (or @option{-I..}; whichever directory contains @file{config.h}).
3259 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3260 the directory of the currently read file, i.e., the source directory, not
3261 the build directory.
3263 With the appropriate @option{-I} option, you can use
3264 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3265 because in the rare case when the source directory contains another
3266 @file{config.h}, the build directory should be searched first.
3269 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3270 @acindex{CONFIG_HEADERS}
3271 @cvindex HAVE_CONFIG_H
3272 This macro is one of the instantiating macros; see @ref{Configuration
3273 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3274 blank-or-newline-separated list @var{header} containing C preprocessor
3275 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3276 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3277 The usual name for @var{header} is @file{config.h}.
3279 If @var{header} already exists and its contents are identical to what
3280 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3281 making some changes in the configuration without needlessly causing
3282 object files that depend on the header file to be recompiled.
3284 Usually the input file is named @file{@var{header}.in}; however, you can
3285 override the input file name by appending to @var{header} a
3286 colon-separated list of input files.  For example, you might need to make
3287 the input file name acceptable to DOS variants:
3289 @example
3290 AC_CONFIG_HEADERS([config.h:config.hin])
3291 @end example
3293 @end defmac
3295 @defmac AH_HEADER
3296 @ahindex{HEADER}
3297 This macro is defined as the name of the first declared config header
3298 and undefined if no config headers have been declared up to this point.
3299 A third-party macro may, for example, require use of a config header
3300 without invoking AC_CONFIG_HEADERS twice, like this:
3302 @example
3303 AC_CONFIG_COMMANDS_PRE(
3304         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3305 @end example
3307 @end defmac
3309 @xref{Configuration Actions}, for more details on @var{header}.
3311 @menu
3312 * Header Templates::            Input for the configuration headers
3313 * autoheader Invocation::       How to create configuration templates
3314 * Autoheader Macros::           How to specify CPP templates
3315 @end menu
3317 @node Header Templates
3318 @subsection Configuration Header Templates
3319 @cindex Configuration Header Template
3320 @cindex Header templates
3321 @cindex @file{config.h.in}
3323 Your distribution should contain a template file that looks as you want
3324 the final header file to look, including comments, with @code{#undef}
3325 statements which are used as hooks.  For example, suppose your
3326 @file{configure.ac} makes these calls:
3328 @example
3329 AC_CONFIG_HEADERS([conf.h])
3330 AC_CHECK_HEADERS([unistd.h])
3331 @end example
3333 @noindent
3334 Then you could have code like the following in @file{conf.h.in}.
3335 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3336 to 1, if and only if the system has @file{unistd.h}.
3338 @example
3339 @group
3340 /* Define as 1 if you have unistd.h.  */
3341 #undef HAVE_UNISTD_H
3342 @end group
3343 @end example
3345 The format of the template file is stricter than what the C preprocessor
3346 is required to accept.  A directive line should contain only whitespace,
3347 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3348 instead of @samp{#undef}, or of comments on the same line as
3349 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3350 once.  Other preprocessor lines, such as @samp{#ifdef} or
3351 @samp{#include}, are copied verbatim from the template into the
3352 generated header.
3354 Since it is a tedious task to keep a template header up to date, you may
3355 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3357 During the instantiation of the header, each @samp{#undef} line in the
3358 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3359 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3360 been executed during the @command{configure} run, the @samp{#undef} line is
3361 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3362 on many systems, it can be implicitly defined by the compiler, and
3363 undefining it in the header would then break compilation of subsequent
3364 headers.)
3366 Currently, @emph{all} remaining @samp{#undef} lines in the header
3367 template are commented out, whether or not there was a corresponding
3368 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3369 for future releases of Autoconf.
3371 Generally speaking, since you should not use @samp{#define}, and you
3372 cannot guarantee whether a @samp{#undef} directive in the header
3373 template will be converted to a @samp{#define} or commented out in the
3374 generated header file, the template file cannot be used for conditional
3375 definition effects.  Consequently, if you need to use the construct
3377 @example
3378 @group
3379 #ifdef THIS
3380 # define THAT
3381 #endif
3382 @end group
3383 @end example
3385 @noindent
3386 you must place it outside of the template.
3387 If you absolutely need to hook it to the config header itself, please put
3388 the directives to a separate file, and @samp{#include} that file from the
3389 config header template.  If you are using @command{autoheader}, you would
3390 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3393 @node autoheader Invocation
3394 @subsection Using @command{autoheader} to Create @file{config.h.in}
3395 @cindex @command{autoheader}
3397 The @command{autoheader} program can create a template file of C
3398 @samp{#define} statements for @command{configure} to use.
3399 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3400 @file{configure} sources to determine the name of the template.
3401 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3402 input file name, @command{autoheader} uses the first one.)
3404 It is recommended that only one input file is used.  If you want to append
3405 a boilerplate code, it is preferable to use
3406 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3407 File @file{conf_post.h} is not processed during the configuration then,
3408 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3409 prepend a boilerplate code.
3411 In order to do its job, @command{autoheader} needs you to document all
3412 of the symbols that you might use.  Typically this is done via an
3413 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3414 is a literal symbol and whose third argument describes the symbol
3415 (@pxref{Defining Symbols}).  Alternatively, you can use
3416 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3417 suitable input file for a subsequent configuration header file.
3418 Symbols defined by Autoconf's builtin tests are already documented properly;
3419 you need to document only those that you
3420 define yourself.
3422 You might wonder why @command{autoheader} is needed: after all, why
3423 would @command{configure} need to ``patch'' a @file{config.h.in} to
3424 produce a @file{config.h} instead of just creating @file{config.h} from
3425 scratch?  Well, when everything rocks, the answer is just that we are
3426 wasting our time maintaining @command{autoheader}: generating
3427 @file{config.h} directly is all that is needed.  When things go wrong,
3428 however, you'll be thankful for the existence of @command{autoheader}.
3430 The fact that the symbols are documented is important in order to
3431 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3432 well-defined list of symbols that should be defined (or not) is
3433 also important for people who are porting packages to environments where
3434 @command{configure} cannot be run: they just have to @emph{fill in the
3435 blanks}.
3437 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3439 If you give @command{autoheader} an argument, it uses that file instead
3440 of @file{configure.ac} and writes the header file to the standard output
3441 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3442 argument of @option{-}, it reads the standard input instead of
3443 @file{configure.ac} and writes the header file to the standard output.
3445 @command{autoheader} accepts the following options:
3447 @table @option
3448 @item --help
3449 @itemx -h
3450 Print a summary of the command line options and exit.
3452 @item --version
3453 @itemx -V
3454 Print the version number of Autoconf and exit.
3456 @item --verbose
3457 @itemx -v
3458 Report processing steps.
3460 @item --debug
3461 @itemx -d
3462 Don't remove the temporary files.
3464 @item --force
3465 @itemx -f
3466 Remake the template file even if newer than its input files.
3468 @item --include=@var{dir}
3469 @itemx -I @var{dir}
3470 Append @var{dir} to the include path.  Multiple invocations accumulate.
3472 @item --prepend-include=@var{dir}
3473 @itemx -B @var{dir}
3474 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3476 @item --warnings=@var{category}
3477 @itemx -W @var{category}
3478 @evindex WARNINGS
3479 Report the warnings related to @var{category} (which can actually be a
3480 comma separated list).  Current categories include:
3482 @table @samp
3483 @item obsolete
3484 report the uses of obsolete constructs
3486 @item all
3487 report all the warnings
3489 @item none
3490 report none
3492 @item error
3493 treats warnings as errors
3495 @item no-@var{category}
3496 disable warnings falling into @var{category}
3497 @end table
3499 @end table
3503 @node Autoheader Macros
3504 @subsection Autoheader Macros
3505 @cindex Autoheader macros
3507 @command{autoheader} scans @file{configure.ac} and figures out which C
3508 preprocessor symbols it might define.  It knows how to generate
3509 templates for symbols defined by @code{AC_CHECK_HEADERS},
3510 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3511 symbol, you must define a template for it.  If there are missing
3512 templates, @command{autoheader} fails with an error message.
3514 The template for a @var{symbol} is created
3515 by @command{autoheader} from
3516 the @var{description} argument to an @code{AC_DEFINE};
3517 see @ref{Defining Symbols}.
3519 For special needs, you can use the following macros.
3522 @defmac AH_TEMPLATE (@var{key}, @var{description})
3523 @ahindex{TEMPLATE}
3524 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3525 generates standard templates just like @code{AC_DEFINE} when a
3526 @var{description} is given.
3528 For example:
3530 @example
3531 AH_TEMPLATE([CRAY_STACKSEG_END],
3532             [Define to one of _getb67, GETB67, getb67
3533              for Cray-2 and Cray-YMP systems.  This
3534              function is required for alloca.c support
3535              on those systems.])
3536 @end example
3538 @noindent
3539 generates the following template, with the description properly
3540 justified.
3542 @example
3543 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3544    Cray-YMP systems.  This function is required for alloca.c
3545    support on those systems.  */
3546 #undef CRAY_STACKSEG_END
3547 @end example
3548 @end defmac
3551 @defmac AH_VERBATIM (@var{key}, @var{template})
3552 @ahindex{VERBATIM}
3553 Tell @command{autoheader} to include the @var{template} as-is in the header
3554 template file.  This @var{template} is associated with the @var{key},
3555 which is used to sort all the different templates and guarantee their
3556 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3557 @end defmac
3560 @defmac AH_TOP (@var{text})
3561 @ahindex{TOP}
3562 Include @var{text} at the top of the header template file.
3563 @end defmac
3566 @defmac AH_BOTTOM (@var{text})
3567 @ahindex{BOTTOM}
3568 Include @var{text} at the bottom of the header template file.
3569 @end defmac
3572 Please note that @var{text} gets included ``verbatim'' to the template file,
3573 not to the resulting config header, so it can easily get mangled when the
3574 template is processed.  There is rarely a need for something other than
3576 @example
3577 AH_BOTTOM([#include <custom.h>])
3578 @end example
3582 @node Configuration Commands
3583 @section Running Arbitrary Configuration Commands
3584 @cindex Configuration commands
3585 @cindex Commands for configuration
3587 You can execute arbitrary commands before, during, and after
3588 @file{config.status} is run.  The three following macros accumulate the
3589 commands to run when they are called multiple times.
3590 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3591 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3593 @anchor{AC_CONFIG_COMMANDS}
3594 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3595 @acindex{CONFIG_COMMANDS}
3596 Specify additional shell commands to run at the end of
3597 @file{config.status}, and shell commands to initialize any variables
3598 from @command{configure}.  Associate the commands with @var{tag}.
3599 Since typically the @var{cmds} create a file, @var{tag} should
3600 naturally be the name of that file.  If needed, the directory hosting
3601 @var{tag} is created.  This macro is one of the instantiating macros;
3602 see @ref{Configuration Actions}.
3604 Here is an unrealistic example:
3605 @example
3606 fubar=42
3607 AC_CONFIG_COMMANDS([fubar],
3608                    [echo this is extra $fubar, and so on.],
3609                    [fubar=$fubar])
3610 @end example
3612 Here is a better one:
3613 @example
3614 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3615 @end example
3616 @end defmac
3618 The following two macros look similar, but in fact they are not of the same
3619 breed: they are executed directly by @file{configure}, so you cannot use
3620 @file{config.status} to rerun them.
3622 @c Yet it is good to leave them here.  The user sees them together and
3623 @c decides which best fits their needs.
3625 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3626 @acindex{CONFIG_COMMANDS_PRE}
3627 Execute the @var{cmds} right before creating @file{config.status}.
3629 This macro presents the last opportunity to call @code{AC_SUBST},
3630 @code{AC_DEFINE}, or @code{AC_CONFIG_@var{ITEMS}} macros.
3631 @end defmac
3633 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3634 @acindex{CONFIG_COMMANDS_POST}
3635 Execute the @var{cmds} right after creating @file{config.status}.
3636 @end defmac
3641 @node Configuration Links
3642 @section Creating Configuration Links
3643 @cindex Configuration links
3644 @cindex Links for configuration
3646 You may find it convenient to create links whose destinations depend upon
3647 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3648 creation of relative symbolic links can be delicate when the package is
3649 built in a directory different from the source directory.
3651 @anchor{AC_CONFIG_LINKS}
3652 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3653   @ovar{init-cmds})
3654 @acindex{CONFIG_LINKS}
3655 @cindex Links
3656 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3657 the corresponding link name @var{dest}.  Makes a symbolic link if
3658 possible, otherwise a hard link if possible, otherwise a copy.  The
3659 @var{dest} and @var{source} names should be relative to the top level
3660 source or build directory.  This macro is one of the instantiating
3661 macros; see @ref{Configuration Actions}.
3663 For example, this call:
3665 @example
3666 AC_CONFIG_LINKS([host.h:config/$machine.h
3667                 object.h:config/$obj_format.h])
3668 @end example
3670 @noindent
3671 creates in the current directory @file{host.h} as a link to
3672 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3673 link to @file{@var{srcdir}/config/$obj_format.h}.
3675 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3676 impossible for @samp{config.status} to guess the links to establish.
3678 One can then run:
3679 @example
3680 ./config.status host.h object.h
3681 @end example
3682 @noindent
3683 to create the links.
3684 @end defmac
3688 @node Subdirectories
3689 @section Configuring Other Packages in Subdirectories
3690 @cindex Configure subdirectories
3691 @cindex Subdirectory configure
3693 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3694 makefiles in subdirectories.  However, @command{configure} scripts
3695 that control more than one independent package can use
3696 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3697 packages in subdirectories.
3699 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3700 @acindex{CONFIG_SUBDIRS}
3701 @ovindex subdirs
3702 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3703 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3704 be a literal, i.e., please do not use:
3706 @example
3707 @c If you change this example, adjust tests/torture.at:Non-literal AC_CONFIG_SUBDIRS.
3708 if test "x$package_foo_enabled" = xyes; then
3709   my_subdirs="$my_subdirs foo"
3711 AC_CONFIG_SUBDIRS([$my_subdirs])
3712 @end example
3714 @noindent
3715 because this prevents @samp{./configure --help=recursive} from
3716 displaying the options of the package @code{foo}.  Instead, you should
3717 write:
3719 @example
3720 if test "x$package_foo_enabled" = xyes; then
3721   AC_CONFIG_SUBDIRS([foo])
3723 @end example
3725 If a given @var{dir} is not found at @command{configure} run time, a
3726 warning is reported; if the subdirectory is optional, write:
3728 @example
3729 if test -d "$srcdir/foo"; then
3730   AC_CONFIG_SUBDIRS([foo])
3732 @end example
3734 @c NB: Yes, below we mean configure.in, not configure.ac.
3735 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3736 of @command{configure}.  This is for packages that might use a
3737 non-Autoconf script @command{Configure}, which can't be called through a
3738 wrapper @command{configure} since it would be the same file on
3739 case-insensitive file systems.  Likewise, if a @var{dir} contains
3740 @file{configure.in} but no @command{configure}, the Cygnus
3741 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3743 The subdirectory @command{configure} scripts are given the same command
3744 line options that were given to this @command{configure} script, with minor
3745 changes if needed, which include:
3747 @itemize @minus
3748 @item
3749 adjusting a relative name for the cache file;
3751 @item
3752 adjusting a relative name for the source directory;
3754 @item
3755 propagating the current value of @code{$prefix}, including if it was
3756 defaulted, and if the default values of the top level and of the subdirectory
3757 @file{configure} differ.
3758 @end itemize
3760 This macro also sets the output variable @code{subdirs} to the list of
3761 directories @samp{@var{dir} @dots{}}.  Make rules can use
3762 this variable to determine which subdirectories to recurse into.
3764 This macro may be called multiple times.
3765 @end defmac
3767 @node Default Prefix
3768 @section Default Prefix
3769 @cindex Install prefix
3770 @cindex Prefix for install
3772 By default, @command{configure} sets the prefix for files it installs to
3773 @file{/usr/local}.  The user of @command{configure} can select a different
3774 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3775 There are two ways to change the default: when creating
3776 @command{configure}, and when running it.
3778 Some software packages might want to install in a directory other than
3779 @file{/usr/local} by default.  To accomplish that, use the
3780 @code{AC_PREFIX_DEFAULT} macro.
3782 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3783 @acindex{PREFIX_DEFAULT}
3784 Set the default installation prefix to @var{prefix} instead of
3785 @file{/usr/local}.
3786 @end defmac
3788 It may be convenient for users to have @command{configure} guess the
3789 installation prefix from the location of a related program that they
3790 have already installed.  If you wish to do that, you can call
3791 @code{AC_PREFIX_PROGRAM}.
3793 @anchor{AC_PREFIX_PROGRAM}
3794 @defmac AC_PREFIX_PROGRAM (@var{program})
3795 @acindex{PREFIX_PROGRAM}
3796 If the user did not specify an installation prefix (using the
3797 @option{--prefix} option), guess a value for it by looking for
3798 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3799 is found, set the prefix to the parent of the directory containing
3800 @var{program}, else default the prefix as described above
3801 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3802 @var{program} is @code{gcc} and the @env{PATH} contains
3803 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3804 @end defmac
3808 @c ======================================================== Existing tests
3810 @node Existing Tests
3811 @chapter Existing Tests
3813 These macros test for particular system features that packages might
3814 need or want to use.  If you need to test for a kind of feature that
3815 none of these macros check for, you can probably do it by calling
3816 primitive test macros with appropriate arguments (@pxref{Writing
3817 Tests}).
3819 These tests print messages telling the user which feature they're
3820 checking for, and what they find.  They cache their results for future
3821 @command{configure} runs (@pxref{Caching Results}).
3823 Some of these macros set output variables.  @xref{Makefile
3824 Substitutions}, for how to get their values.  The phrase ``define
3825 @var{name}'' is used below as a shorthand to mean ``define the C
3826 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3827 Symbols}, for how to get those symbol definitions into your program.
3829 @menu
3830 * Common Behavior::             Macros' standard schemes
3831 * Alternative Programs::        Selecting between alternative programs
3832 * Files::                       Checking for the existence of files
3833 * Libraries::                   Library archives that might be missing
3834 * Library Functions::           C library functions that might be missing
3835 * Header Files::                Header files that might be missing
3836 * Declarations::                Declarations that may be missing
3837 * Structures::                  Structures or members that might be missing
3838 * Types::                       Types that might be missing
3839 * Compilers and Preprocessors::  Checking for compiling programs
3840 * System Services::             Operating system services
3841 * Posix Variants::              Special kludges for specific Posix variants
3842 * Erlang Libraries::            Checking for the existence of Erlang libraries
3843 @end menu
3845 @node Common Behavior
3846 @section Common Behavior
3847 @cindex Common autoconf behavior
3849 Much effort has been expended to make Autoconf easy to learn.  The most
3850 obvious way to reach this goal is simply to enforce standard interfaces
3851 and behaviors, avoiding exceptions as much as possible.  Because of
3852 history and inertia, unfortunately, there are still too many exceptions
3853 in Autoconf; nevertheless, this section describes some of the common
3854 rules.
3856 @menu
3857 * Standard Symbols::            Symbols defined by the macros
3858 * Default Includes::            Includes used by the generic macros
3859 @end menu
3861 @node Standard Symbols
3862 @subsection Standard Symbols
3863 @cindex Standard symbols
3865 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3866 their test transform their @var{argument} values to a standard alphabet.
3867 First, @var{argument} is converted to upper case and any asterisks
3868 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3869 that are not alphanumeric are converted to underscores.
3871 For instance,
3873 @example
3874 AC_CHECK_TYPES([struct $Expensive*])
3875 @end example
3877 @noindent
3878 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3879 succeeds.
3882 @node Default Includes
3883 @subsection Default Includes
3884 @cindex Default includes
3885 @cindex Includes, default
3886 @hdrindex{assert.h}
3887 @hdrindex{ctype.h}
3888 @hdrindex{errno.h}
3889 @hdrindex{float.h}
3890 @hdrindex{iso646.h}
3891 @hdrindex{limits.h}
3892 @hdrindex{locale.h}
3893 @hdrindex{math.h}
3894 @hdrindex{setjmp.h}
3895 @hdrindex{signal.h}
3896 @hdrindex{stdarg.h}
3897 @hdrindex{stddef.h}
3898 @hdrindex{stdio.h}
3899 @hdrindex{stdlib.h}
3900 @hdrindex{string.h}
3901 @hdrindex{time.h}
3902 @hdrindex{wchar.h}
3903 @hdrindex{wctype.h}
3905 Test programs frequently need to include headers that may or may not be
3906 available on the system whose features are being tested.  Each test can
3907 use all the preprocessor macros that have been @code{AC_DEFINE}d by
3908 previous tests, so for example one may write
3910 @example
3911 @group
3912 #include <time.h>
3913 #ifdef HAVE_SYS_TIME_H
3914 # include <sys/time.h>
3915 #endif
3916 @end group
3917 @end example
3919 @noindent
3920 if @file{sys/time.h} has already been tested for.
3922 All hosted environments that are still of interest for portable code
3923 provide all of the headers specified in ISO C90 (as amended in 1995):
3924 @file{assert.h}, @file{ctype.h}, @file{errno.h}, @file{float.h},
3925 @file{iso646.h}, @file{limits.h}, @file{locale.h}, @file{math.h},
3926 @file{setjmp.h}, @file{signal.h}, @file{stdarg.h}, @file{stddef.h},
3927 @file{stdio.h}, @file{stdlib.h}, @file{string.h}, @file{time.h},
3928 @file{wchar.h}, and @file{wctype.h}.  Most programs can safely include
3929 these headers unconditionally.  All other headers, including all headers
3930 from later revisions of the C standard, need to be tested for
3931 (@pxref{Header Files}).
3933 If your program needs to be portable to a @emph{freestanding}
3934 environment, such as an embedded OS that doesn't provide all of the
3935 facilities of the C90 standard library, you may need to test for some of
3936 the above headers as well.  Note that many Autoconf macros internally
3937 assume that the complete set of C90 headers are available.
3939 Most generic macros use the following macro to provide a default set
3940 of includes:
3942 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3943 @acindex{INCLUDES_DEFAULT}
3944 Expand to @var{include-directives} if present and nonempty, otherwise to:
3946 @example
3947 @group
3948 #include <stddef.h>
3949 #include <stdio.h>
3950 #include <stdlib.h>
3951 #include <string.h>
3952 #ifdef HAVE_SYS_TYPES_H
3953 # include <sys/types.h>
3954 #endif
3955 #ifdef HAVE_SYS_STAT_H
3956 # include <sys/stat.h>
3957 #endif
3958 #ifdef HAVE_STRINGS_H
3959 # include <strings.h>
3960 #endif
3961 #ifdef HAVE_INTTYPES_H
3962 # include <inttypes.h>
3963 #endif
3964 #ifdef HAVE_STDINT_H
3965 # include <stdint.h>
3966 #endif
3967 #ifdef HAVE_UNISTD_H
3968 # include <unistd.h>
3969 #endif
3970 @end group
3971 @end example
3973 Using this macro without @var{include-directives} has the side effect of
3974 checking for @file{sys/types.h}, @file{sys/stat.h}, @file{strings.h},
3975 @file{inttypes.h}, @file{stdint.h}, and @file{unistd.h}, as if by
3976 @code{AC_CHECK_HEADERS}.  For backward compatibility's sake, it also
3977 unconditionally defines @code{HAVE_STRING_H}, @code{HAVE_STDLIB_H}, and
3978 @code{STDC_HEADERS}.  New code should not make use of these preprocessor
3979 macros.
3980 @end defmac
3982 @defmac AC_CHECK_INCLUDES_DEFAULT
3983 @acindex{CHECK_INCLUDES_DEFAULT}
3984 Check for all the headers that @code{AC_INCLUDES_DEFAULT} would check
3985 for as a side-effect, if this has not already happened.
3987 This macro mainly exists so that @code{autoupdate} can replace certain
3988 obsolete constructs with it. You should not need to use it yourself; in
3989 fact, it is likely to be safe to delete it from any script in which it
3990 appears.  (@code{autoupdate} does not know whether preprocessor macros
3991 such as @code{HAVE_STDINT_H} are used in the program, nor whether they
3992 would get defined as a side-effect of other checks.)
3993 @end defmac
3995 @node Alternative Programs
3996 @section Alternative Programs
3997 @cindex Programs, checking
3999 These macros check for the presence or behavior of particular programs.
4000 They are used to choose between several alternative programs and to
4001 decide what to do once one has been chosen.  If there is no macro
4002 specifically defined to check for a program you need, and you don't need
4003 to check for any special properties of it, then you can use one of the
4004 general program-check macros.
4006 @menu
4007 * Particular Programs::         Special handling to find certain programs
4008 * Generic Programs::            How to find other programs
4009 @end menu
4011 @node Particular Programs
4012 @subsection Particular Program Checks
4014 These macros check for particular programs---whether they exist, and
4015 in some cases whether they support certain features.
4017 @defmac AC_PROG_AWK
4018 @acindex{PROG_AWK}
4019 @ovindex AWK
4020 @caindex prog_AWK
4021 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
4022 order, and set output variable @code{AWK} to the first one that is found.
4023 It tries @code{gawk} first because that is reported to be the
4024 best implementation.  The result can be overridden by setting the
4025 variable @code{AWK} or the cache variable @code{ac_cv_prog_AWK}.
4027 Using this macro is sufficient to avoid the pitfalls of traditional
4028 @command{awk} (@pxref{awk, , Limitations of Usual Tools}).
4029 @end defmac
4031 @defmac AC_PROG_GREP
4032 @acindex{PROG_GREP}
4033 @ovindex GREP
4034 @caindex prog_GREP
4035 Look for the best available @code{grep} or @code{ggrep} that accepts the
4036 longest input lines possible, and that supports multiple @option{-e} options.
4037 Set the output variable @code{GREP} to whatever is chosen.
4038 @xref{grep, , Limitations of Usual Tools}, for more information about
4039 portability problems with the @command{grep} command family.  The result
4040 can be overridden by setting the @code{GREP} variable and is cached in the
4041 @code{ac_cv_path_GREP} variable.
4042 @end defmac
4044 @defmac AC_PROG_EGREP
4045 @acindex{PROG_EGREP}
4046 @ovindex EGREP
4047 @caindex prog_EGREP
4048 Check whether @code{$GREP -E} works, or else look for the best available
4049 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
4050 Set the output variable @code{EGREP} to whatever is chosen.  The result
4051 can be overridden by setting the @code{EGREP} variable and is cached in the
4052 @code{ac_cv_path_EGREP} variable.
4053 @end defmac
4055 @defmac AC_PROG_FGREP
4056 @acindex{PROG_FGREP}
4057 @ovindex FGREP
4058 @caindex prog_FGREP
4059 Check whether @code{$GREP -F} works, or else look for the best available
4060 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
4061 Set the output variable @code{FGREP} to whatever is chosen.  The result
4062 can be overridden by setting the @code{FGREP} variable and is cached in the
4063 @code{ac_cv_path_FGREP} variable.
4064 @end defmac
4066 @defmac AC_PROG_INSTALL
4067 @acindex{PROG_INSTALL}
4068 @ovindex INSTALL
4069 @ovindex INSTALL_PROGRAM
4070 @ovindex INSTALL_DATA
4071 @ovindex INSTALL_SCRIPT
4072 @caindex path_install
4073 Set output variable @code{INSTALL} to the name of a BSD-compatible
4074 @command{install} program, if one is found in the current @env{PATH}.
4075 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
4076 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
4077 default directories) to determine @var{dir} (@pxref{Output}).  Also set
4078 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
4079 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
4081 @samp{@@INSTALL@@} is special, as its value may vary for different
4082 configuration files.
4084 This macro screens out various instances of @command{install} known not to
4085 work.  It prefers to find a C program rather than a shell script, for
4086 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
4087 but that name is obsolete because some @command{make} programs have a rule
4088 that creates @file{install} from it if there is no makefile.  Further, this
4089 macro requires @command{install} to be able to install multiple files into a
4090 target directory in a single invocation.
4092 Autoconf comes with a copy of @file{install-sh} that you can use.  If
4093 you use @code{AC_PROG_INSTALL}, you must include either
4094 @file{install-sh} or @file{install.sh} in your distribution; otherwise
4095 @command{configure} produces an error message saying it can't find
4096 them---even if the system you're on has a good @command{install} program.
4097 This check is a safety measure to prevent you from accidentally leaving
4098 that file out, which would prevent your package from installing on
4099 systems that don't have a BSD-compatible @command{install} program.
4101 If you need to use your own installation program because it has features
4102 not found in standard @command{install} programs, there is no reason to use
4103 @code{AC_PROG_INSTALL}; just put the file name of your program into your
4104 @file{Makefile.in} files.
4106 The result of the test can be overridden by setting the variable
4107 @code{INSTALL} or the cache variable @code{ac_cv_path_install}.
4108 @end defmac
4110 @defmac AC_PROG_MKDIR_P
4111 @acindex{PROG_MKDIR_P}
4112 @ovindex MKDIR_P
4113 @caindex path_mkdir
4114 Set output variable @code{MKDIR_P} to a program that ensures that for
4115 each argument, a directory named by this argument exists, creating it
4116 and its parent directories if needed, and without race conditions when
4117 two instances of the program attempt to make the same directory at
4118 nearly the same time.
4120 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
4121 falls back on invoking @command{install-sh} with the @option{-d} option,
4122 so your package should
4123 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
4124 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
4125 is vulnerable to race conditions, so if you want to support parallel
4126 installs from
4127 different packages into the same directory you need to make sure you
4128 have an up-to-date @file{install-sh}.  In particular, be careful about
4129 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
4131 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
4132 in M4sh}), but it sets an output variable intended for use in other
4133 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
4134 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
4135 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
4136 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
4137 directory, and conversely a makefile should use @code{$(MKDIR_P) --
4138 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
4139 Finally, @code{AS_MKDIR_P} does not check for race condition
4140 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
4142 @samp{@@MKDIR_P@@} is special, as its value may vary for different
4143 configuration files.
4145 The result of the test can be overridden by setting the variable
4146 @code{MKDIR_P} or the cache variable @code{ac_cv_path_mkdir}.
4147 @end defmac
4149 @anchor{AC_PROG_LEX}
4150 @defmac AC_PROG_LEX
4151 @acindex{PROG_LEX}
4152 @ovindex LEX
4153 @ovindex LEXLIB
4154 @cvindex YYTEXT_POINTER
4155 @ovindex LEX_OUTPUT_ROOT
4156 @caindex prog_LEX
4157 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
4158 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
4159 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
4160 @option{-ll}, if found.  If neither variant is available, set @code{LEX}
4161 to @samp{:}; for packages that ship the generated @file{file.yy.c}
4162 alongside the source @file{file.l}, this default allows users without a
4163 lexer generator to still build the package even if the timestamp for
4164 @file{file.l} is inadvertently changed.
4166 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
4167 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
4168 the base of the file name that the lexer generates; usually
4169 @file{lex.yy}, but sometimes something else.  These results vary
4170 according to whether @code{lex} or @code{flex} is being used.
4172 You are encouraged to use Flex in your sources, since it is both more
4173 pleasant to use than plain Lex and the C source it produces is portable.
4174 In order to ensure portability, however, you must either provide a
4175 function @code{yywrap} or, if you don't use it (e.g., your scanner has
4176 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
4177 statement in the scanner's source.  Once this done, the scanner is
4178 portable (unless @emph{you} felt free to use nonportable constructs) and
4179 does not depend on any library.  In this case, and in this case only, it
4180 is suggested that you use this Autoconf snippet:
4182 @example
4183 AC_PROG_LEX
4184 if test "x$LEX" != xflex; then
4185   LEX="$SHELL $missing_dir/missing flex"
4186   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
4187   AC_SUBST([LEXLIB], [''])
4189 @end example
4191 The shell script @command{missing} can be found in the Automake
4192 distribution.
4194 Remember that the user may have supplied an alternate location in
4195 @env{LEX}, so if Flex is required, it is better to check that the user
4196 provided something sufficient by parsing the output of @samp{$LEX
4197 --version} than by simply relying on @code{test "x$LEX" = xflex}.
4199 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
4200 (indirectly) this macro twice, which causes an annoying but benign
4201 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
4202 of Automake will fix this issue; meanwhile, just ignore this message.
4204 As part of running the test, this macro may delete any file in the
4205 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
4207 The result of this test can be influenced by setting the variable
4208 @code{LEX} or the cache variable @code{ac_cv_prog_LEX}.
4209 @end defmac
4211 @anchor{AC_PROG_LN_S}
4212 @defmac AC_PROG_LN_S
4213 @acindex{PROG_LN_S}
4214 @ovindex LN_S
4215 If @samp{ln -s} works on the current file system (the operating system
4216 and file system support symbolic links), set the output variable
4217 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
4218 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -pR}.
4220 If you make a link in a directory other than the current directory, its
4221 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
4222 create links using @samp{$(LN_S)}, either find out which form is used
4223 and adjust the arguments, or always invoke @code{ln} in the directory
4224 where the link is to be created.
4226 In other words, it does not work to do:
4227 @example
4228 $(LN_S) foo /x/bar
4229 @end example
4231 Instead, do:
4233 @example
4234 (cd /x && $(LN_S) foo bar)
4235 @end example
4236 @end defmac
4238 @defmac AC_PROG_RANLIB
4239 @acindex{PROG_RANLIB}
4240 @ovindex RANLIB
4241 @c @caindex prog_RANLIB
4242 @c @caindex prog_ac_ct_RANLIB
4243 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
4244 is found, and otherwise to @samp{:} (do nothing).
4245 @end defmac
4247 @defmac AC_PROG_SED
4248 @acindex{PROG_SED}
4249 @ovindex SED
4250 @caindex path_SED
4251 Set output variable @code{SED} to a Sed implementation that conforms to
4252 Posix and does not have arbitrary length limits.  Report an error if no
4253 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
4254 information about portability problems with Sed.
4256 The result of this test can be overridden by setting the @code{SED} variable
4257 and is cached in the @code{ac_cv_path_SED} variable.
4258 @end defmac
4260 @defmac AC_PROG_YACC
4261 @acindex{PROG_YACC}
4262 @evindex YACC
4263 @evindex YFLAGS
4264 @ovindex YACC
4265 @caindex prog_YACC
4266 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
4267 -o y.tab.c}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4268 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4269 The result of this test can be influenced by setting the variable
4270 @code{YACC} or the cache variable @code{ac_cv_prog_YACC}.
4271 @end defmac
4273 @node Generic Programs
4274 @subsection Generic Program and File Checks
4276 These macros are used to find programs not covered by the ``particular''
4277 test macros.  If you need to check the behavior of a program as well as
4278 find out whether it is present, you have to write your own test for it
4279 (@pxref{Writing Tests}).  By default, these macros use the environment
4280 variable @env{PATH}.  If you need to check for a program that might not
4281 be in the user's @env{PATH}, you can pass a modified path to use
4282 instead, like this:
4284 @example
4285 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4286              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4287 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4288 @end example
4290 You are strongly encouraged to declare the @var{variable} passed to
4291 @code{AC_CHECK_PROG} etc.@: as precious.  @xref{Setting Output Variables},
4292 @code{AC_ARG_VAR}, for more details.
4294 @anchor{AC_CHECK_PROG}
4295 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4296   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4297   @ovar{reject})
4298 @acindex{CHECK_PROG}
4299 @caindex prog_@var{variable}
4300 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4301 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4302 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4303 absolute file name) even if it is the first found in the search path; in
4304 that case, set @var{variable} using the absolute file name of the
4305 @var{prog-to-check-for} found that is not @var{reject}.  If
4306 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4307 @var{variable}.  The result of this test can be overridden by setting the
4308 @var{variable} variable or the cache variable
4309 @code{ac_cv_prog_@var{variable}}.
4310 @end defmac
4312 @anchor{AC_CHECK_PROGS}
4313 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4314   @ovar{value-if-not-found}, @dvar{path, $PATH})
4315 @acindex{CHECK_PROGS}
4316 @caindex prog_@var{variable}
4317 Check for each program in the blank-separated list
4318 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4319 @var{variable} to the name of that program.  Otherwise, continue
4320 checking the next program in the list.  If none of the programs in the
4321 list are found, set @var{variable} to @var{value-if-not-found}; if
4322 @var{value-if-not-found} is not specified, the value of @var{variable}
4323 is not changed.  Calls @code{AC_SUBST} for @var{variable}.  The result of
4324 this test can be overridden by setting the @var{variable} variable or the
4325 cache variable @code{ac_cv_prog_@var{variable}}.
4326 @end defmac
4328 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4329   @ovar{value-if-not-found}, @dvar{path, $PATH})
4330 @acindex{CHECK_TARGET_TOOL}
4331 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4332 with a prefix of the target type as determined by
4333 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4334 If the tool cannot be found with a prefix, and if the build and target
4335 types are equal, then it is also searched for without a prefix.
4337 As noted in @ref{Specifying Target Triplets}, the
4338 target is rarely specified, because most of the time it is the same
4339 as the host: it is the type of system for which any compiler tool in
4340 the package produces code.  What this macro looks for is,
4341 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4342 compiler driver @r{(@command{gcc} for the GNU C Compiler)}
4343 uses to produce objects, archives or executables}.
4344 @end defmac
4346 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4347   @ovar{value-if-not-found}, @dvar{path, $PATH})
4348 @acindex{CHECK_TOOL}
4349 @c @caindex prog_@var{VARIABLE}
4350 @c @caindex prog_ac_ct_@var{VARIABLE}
4351 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4352 with a prefix of the host type as specified by @option{--host}, followed by a
4353 dash.  For example, if the user runs
4354 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4355 @example
4356 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4357 @end example
4358 @noindent
4359 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4360 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4361 @var{path}, or to @samp{:} if neither program exists.
4363 When cross-compiling, this macro will issue a warning if no program
4364 prefixed with the host type could be found.
4365 For more information, see @ref{Specifying Target Triplets}.
4366 @end defmac
4368 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4369   @ovar{value-if-not-found}, @dvar{path, $PATH})
4370 @acindex{CHECK_TARGET_TOOLS}
4371 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4372 @var{progs-to-check-for} are checked with a prefix of the target type as
4373 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4374 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4375 prefix, and if the build and target types are equal, then the first one
4376 without a prefix is used.  If a tool is found, set @var{variable} to
4377 the name of that program.  If none of the tools in the list are found,
4378 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4379 is not specified, the value of @var{variable} is not changed.  Calls
4380 @code{AC_SUBST} for @var{variable}.
4381 @end defmac
4383 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4384   @ovar{value-if-not-found}, @dvar{path, $PATH})
4385 @acindex{CHECK_TOOLS}
4386 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4387 @var{progs-to-check-for} are checked with a prefix of the host type as
4388 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4389 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4390 prefix, then the first one without a prefix is used.  If a tool is found,
4391 set @var{variable} to the name of that program.  If none of the tools in
4392 the list are found, set @var{variable} to @var{value-if-not-found}; if
4393 @var{value-if-not-found} is not specified, the value of @var{variable}
4394 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4396 When cross-compiling, this macro will issue a warning if no program
4397 prefixed with the host type could be found.
4398 For more information, see @ref{Specifying Target Triplets}.
4399 @end defmac
4401 @anchor{AC_PATH_PROG}
4402 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4403   @ovar{value-if-not-found}, @dvar{path, $PATH})
4404 @acindex{PATH_PROG}
4405 @caindex path_@var{variable}
4406 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4407 name of @var{prog-to-check-for} if found.  The result of this test
4408 can be overridden by setting the @var{variable} variable.  A positive
4409 result of this test is cached in the @code{ac_cv_path_@var{variable}}
4410 variable.
4411 @end defmac
4413 @anchor{AC_PATH_PROGS}
4414 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4415   @ovar{value-if-not-found}, @dvar{path, $PATH})
4416 @acindex{PATH_PROGS}
4417 @caindex path_@var{variable}
4418 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4419 are found, set @var{variable} to the absolute name of the program
4420 found.  The result of this test can be overridden by setting the
4421 @var{variable} variable.  A positive result of this test is cached in
4422 the @code{ac_cv_path_@var{variable}} variable.
4423 @end defmac
4425 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4426   @var{progs-to-check-for}, @var{feature-test}, @
4427   @ovar{action-if-not-found}, @dvar{path, $PATH})
4428 @acindex{PATH_PROGS_FEATURE_CHECK}
4429 @caindex path_@var{variable}
4430 @vrindex ac_path_@var{variable}
4431 @vrindex ac_path_@var{variable}_found
4432 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4433 empty, then set the cache variable @code{ac_cv_path_@var{variable}} to
4434 its value.  Otherwise, check for each program in the blank-separated
4435 list @var{progs-to-check-for} existing in @var{path}.  For each program
4436 found, execute @var{feature-test} with @code{ac_path_@var{variable}}
4437 set to the absolute name of the candidate program.  If no invocation of
4438 @var{feature-test} sets the shell variable
4439 @code{ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4440 executed.  @var{feature-test} will be run even when
4441 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4442 choose a better candidate found later in @var{path}; to accept the
4443 current setting and bypass all further checks, @var{feature-test} can
4444 execute @code{ac_path_@var{variable}_found=:}.
4446 Note that this macro has some subtle differences from
4447 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4448 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4449 particular, @var{variable} is not set to the final value of
4450 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4451 run.  Also, on failure, any action can be performed, whereas
4452 @code{AC_CHECK_PROGS} only performs
4453 @code{@var{variable}=@var{value-if-not-found}}.
4455 Here is an example, similar to what Autoconf uses in its own configure
4456 script.  It will search for an implementation of @command{m4} that
4457 supports the @code{indir} builtin, even if it goes by the name
4458 @command{gm4} or is not the first implementation on @env{PATH}.
4460 @example
4461 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4462   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4463     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4464       test "x$m4out" = x0 \
4465       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4466     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4467 AC_SUBST([M4], [$ac_cv_path_M4])
4468 @end example
4469 @end defmac
4471 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4472   @ovar{value-if-not-found}, @dvar{path, $PATH})
4473 @acindex{PATH_TARGET_TOOL}
4474 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4475 name of the program if it is found.
4476 @end defmac
4478 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4479   @ovar{value-if-not-found}, @dvar{path, $PATH})
4480 @acindex{PATH_TOOL}
4481 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4482 name of the program if it is found.
4484 When cross-compiling, this macro will issue a warning if no program
4485 prefixed with the host type could be found.
4486 For more information, see @ref{Specifying Target Triplets}.
4487 @end defmac
4490 @node Files
4491 @section Files
4492 @cindex File, checking
4494 You might also need to check for the existence of files.  Before using
4495 these macros, ask yourself whether a runtime test might not be a better
4496 solution.  Be aware that, like most Autoconf macros, they test a feature
4497 of the host machine, and therefore, they die when cross-compiling.
4499 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4500   @ovar{action-if-not-found})
4501 @acindex{CHECK_FILE}
4502 @caindex file_@var{file}
4503 Check whether file @var{file} exists on the native system.  If it is
4504 found, execute @var{action-if-found}, otherwise do
4505 @var{action-if-not-found}, if given.  Cache the result of this test
4506 in the @code{ac_cv_file_@var{file}} variable, with characters not
4507 suitable for a variable name mapped to underscores.
4508 @end defmac
4510 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4511   @ovar{action-if-not-found})
4512 @acindex{CHECK_FILES}
4513 @caindex file_@var{file}
4514 For each file listed in @var{files}, execute @code{AC_CHECK_FILE}
4515 and perform either @var{action-if-found} or @var{action-if-not-found}.
4516 Like @code{AC_CHECK_FILE}, this defines @samp{HAVE_@var{file}}
4517 (@pxref{Standard Symbols}) for each file found and caches the results of
4518 each test in the @code{ac_cv_file_@var{file}} variable, with characters
4519 not suitable for a variable name mapped to underscores.
4520 @end defmac
4523 @node Libraries
4524 @section Library Files
4525 @cindex Library, checking
4527 The following macros check for the presence of certain C, C++, Fortran,
4528 or Go library archive files.
4530 @anchor{AC_CHECK_LIB}
4531 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4532   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4533 @acindex{CHECK_LIB}
4534 @caindex lib_@var{library}_@var{function}
4535 Test whether the library @var{library} is available by trying to link
4536 a test program that calls function @var{function} with the library.
4537 @var{function} should be a function provided by the library.
4538 Use the base
4539 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4540 the @var{library} argument.
4542 @var{action-if-found} is a list of shell commands to run if the link
4543 with the library succeeds; @var{action-if-not-found} is a list of shell
4544 commands to run if the link fails.  If @var{action-if-found} is not
4545 specified, the default action prepends @option{-l@var{library}} to
4546 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4547 capitals).  This macro is intended to support building @code{LIBS} in
4548 a right-to-left (least-dependent to most-dependent) fashion such that
4549 library dependencies are satisfied as a natural side effect of
4550 consecutive tests.  Linkers are sensitive to library ordering
4551 so the order in which @code{LIBS} is generated is important to reliable
4552 detection of libraries.
4554 If linking with @var{library} results in unresolved symbols that would
4555 be resolved by linking with additional libraries, give those libraries
4556 as the @var{other-libraries} argument, separated by spaces:
4557 e.g., @option{-lXt -lX11}.  Otherwise, this macro may fail to detect
4558 that @var{library} is present, because linking the test program can
4559 fail with unresolved symbols.  The @var{other-libraries} argument
4560 should be limited to cases where it is desirable to test for one library
4561 in the presence of another that is not already in @code{LIBS}.
4563 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4564 in some common cases.  Many standard functions like @code{gethostbyname}
4565 appear in the standard C library on some hosts, and in special libraries
4566 like @code{nsl} on other hosts.  On some hosts the special libraries
4567 contain variant implementations that you may not want to use.  These
4568 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4569 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4571 The result of this test is cached in the
4572 @code{ac_cv_lib_@var{library}_@var{function}} variable.
4573 @end defmac
4575 @anchor{AC_SEARCH_LIBS}
4576 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4577   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4578 @acindex{SEARCH_LIBS}
4579 @caindex search_@var{function}
4580 Search for a library defining @var{function} if it's not already
4581 available.  This equates to calling
4582 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4583 no libraries, then for each library listed in @var{search-libs}.
4585 Prepend @option{-l@var{library}} to @code{LIBS} for the first library found
4586 to contain @var{function}, and run @var{action-if-found}.  If the
4587 function is not found, run @var{action-if-not-found}.
4589 If linking with @var{library} results in unresolved symbols that would
4590 be resolved by linking with additional libraries, give those libraries
4591 as the @var{other-libraries} argument, separated by spaces:
4592 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4593 that @var{function} is present, because linking the test program
4594 always fails with unresolved symbols.
4596 The result of this test is cached in the
4597 @code{ac_cv_search_@var{function}} variable as @samp{none required} if
4598 @var{function} is already available, as @samp{no} if no library
4599 containing @var{function} was found, otherwise as the
4600 @option{-l@var{library}} option that needs to be prepended to @code{LIBS}.
4601 @end defmac
4605 @node Library Functions
4606 @section Library Functions
4608 The following macros check for particular C library functions.
4609 If there is no macro specifically defined to check for a function you need,
4610 and you don't need to check for any special properties of
4611 it, then you can use one of the general function-check macros.
4613 @menu
4614 * Function Portability::        Pitfalls with usual functions
4615 * Particular Functions::        Special handling to find certain functions
4616 * Generic Functions::           How to find other functions
4617 @end menu
4619 @node Function Portability
4620 @subsection Portability of C Functions
4621 @cindex Portability of C functions
4622 @cindex C function portability
4624 Most usual functions can either be missing, or be buggy, or be limited
4625 on some architectures.  This section tries to make an inventory of these
4626 portability issues.  By definition, this list always requires
4627 additions.  A much more complete list is maintained by the Gnulib
4628 project (@pxref{Gnulib}), covering @ref{Function Substitutes, ,
4629 Current Posix Functions, gnulib, GNU gnulib}, @ref{Legacy Function
4630 Substitutes, , Legacy Functions, gnulib, GNU gnulib}, and @ref{Glibc
4631 Function Substitutes, , Glibc Functions, gnulib, GNU gnulib}.  Please
4632 help us keep the gnulib list as complete as possible.
4634 @table @asis
4635 @item @code{exit}
4636 @c @fuindex exit
4637 @prindex @code{exit}
4638 On ancient hosts, @code{exit} returned @code{int}.
4639 This is because @code{exit} predates @code{void}, and there was a long
4640 tradition of it returning @code{int}.
4642 On current hosts, the problem more likely is that @code{exit} is not
4643 declared, due to C++ problems of some sort or another.  For this reason
4644 we suggest that test programs not invoke @code{exit}, but return from
4645 @code{main} instead.
4647 @item @code{free}
4648 @c @fuindex free
4649 @prindex @code{free}
4650 The C standard says a call @code{free (NULL)} does nothing, but
4651 some old systems don't support this (e.g., NextStep).
4653 @item @code{isinf}
4654 @itemx @code{isnan}
4655 @c @fuindex isinf
4656 @c @fuindex isnan
4657 @prindex @code{isinf}
4658 @prindex @code{isnan}
4659 In C99 and later, @code{isinf} and @code{isnan} are
4660 macros.  On some systems just macros are available
4661 (e.g., HP-UX and Solaris 10), on
4662 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4663 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4664 these functions are declared in nonstandard headers like
4665 @code{<sunmath.h>} and defined in non-default libraries like
4666 @option{-lm} or @option{-lsunmath}.
4668 In C99 and later, @code{isinf} and @code{isnan} macros work correctly with
4669 @code{long double} arguments, but pre-C99 systems that use functions
4670 typically assume @code{double} arguments.  On such a system,
4671 @code{isinf} incorrectly returns true for a finite @code{long double}
4672 argument that is outside the range of @code{double}.
4674 The best workaround for these issues is to use gnulib modules
4675 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4676 solution involves code like the following.
4678 @smallexample
4679 #include <math.h>
4681 #ifndef isnan
4682 # define isnan(x) \
4683     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4684      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4685      : isnan_f (x))
4686 static int isnan_f  (float       x) @{ return x != x; @}
4687 static int isnan_d  (double      x) @{ return x != x; @}
4688 static int isnan_ld (long double x) @{ return x != x; @}
4689 #endif
4691 #ifndef isinf
4692 # define isinf(x) \
4693     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4694      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4695      : isinf_f (x))
4696 static int isinf_f  (float       x)
4697 @{ return !isnan (x) && isnan (x - x); @}
4698 static int isinf_d  (double      x)
4699 @{ return !isnan (x) && isnan (x - x); @}
4700 static int isinf_ld (long double x)
4701 @{ return !isnan (x) && isnan (x - x); @}
4702 #endif
4703 @end smallexample
4705 Some optimizing compilers mishandle these definitions, but systems with that bug
4706 typically have many other floating point corner-case compliance problems
4707 anyway, so it's probably not worth worrying about.
4709 @item @code{malloc}
4710 @c @fuindex malloc
4711 @prindex @code{malloc}
4712 The C standard says a call @code{malloc (0)} is implementation
4713 dependent.  It can return either @code{NULL} or a new non-null pointer.
4714 The latter is more common (e.g., the GNU C Library) but is by
4715 no means universal.  @code{AC_FUNC_MALLOC}
4716 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4718 @item @code{putenv}
4719 @c @fuindex putenv
4720 @prindex @code{putenv}
4721 Posix prefers @code{setenv} to @code{putenv}; among other things,
4722 @code{putenv} is not required of all Posix implementations, but
4723 @code{setenv} is.
4725 Posix specifies that @code{putenv} puts the given string directly in
4726 @code{environ}, but some systems make a copy of it instead (e.g.,
4727 glibc 2.0, or BSD).  And when a copy is made, @code{unsetenv} might
4728 not free it, causing a memory leak (e.g., FreeBSD 4).
4730 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4731 environment, but this is not standard usage and it dumps core
4732 on some systems (e.g., AIX).
4734 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4735 environment, rather than inserting it with an empty value.
4737 @item @code{realloc}
4738 @c @fuindex realloc
4739 @prindex @code{realloc}
4740 The C standard says a call @code{realloc (NULL, size)} is equivalent
4741 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4742 NextStep).
4744 @item @code{signal} handler
4745 @c @fuindex signal
4746 @prindex @code{signal}
4747 @prindex @code{sigaction}
4748 Normally @code{signal} takes a handler function with a return type of
4749 @code{void}, but some old systems required @code{int} instead.  Any
4750 actual @code{int} value returned is not used; this is only a
4751 difference in the function prototype demanded.
4753 All systems we know of in current use return @code{void}.  The
4754 @code{int} was to support K&R C, where of course @code{void} is not
4755 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4756 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4757 all cases.
4759 In most cases, it is more robust to use @code{sigaction} when it is
4760 available, rather than @code{signal}.
4762 @item @code{snprintf}
4763 @c @fuindex snprintf
4764 @prindex @code{snprintf}
4765 @c @fuindex vsnprintf
4766 @prindex @code{vsnprintf}
4767 In C99 and later, if the output array isn't big enough
4768 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4769 truncate the output and return the number of bytes that ought to have
4770 been produced.  Some older systems return the truncated length (e.g.,
4771 GNU C Library 2.0.x or IRIX 6.5), some a negative value
4772 (e.g., earlier GNU C Library versions), and some the buffer
4773 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4774 older systems ignore the length and overrun the buffer (e.g., 64-bit
4775 Solaris 7).
4777 @item @code{sprintf}
4778 @c @fuindex sprintf
4779 @prindex @code{sprintf}
4780 @c @fuindex vsprintf
4781 @prindex @code{vsprintf}
4782 The C standard says @code{sprintf} and @code{vsprintf} return the
4783 number of bytes written.  On some ancient systems (SunOS 4 for
4784 instance) they return the buffer pointer instead, but these no
4785 longer need to be worried about.
4787 @item @code{sscanf}
4788 @c @fuindex sscanf
4789 @prindex @code{sscanf}
4790 On various old systems, e.g., HP-UX 9, @code{sscanf} requires
4791 that its
4792 input string be writable (though it doesn't actually change it).  This
4793 can be a problem when using @command{gcc} since it normally puts
4794 constant strings in read-only memory (@pxref{Incompatibilities,
4795 Incompatibilities of GCC, , gcc, Using and
4796 Porting the GNU Compiler Collection}).  Apparently in some cases even
4797 having format strings read-only can be a problem.
4799 @item @code{strerror_r}
4800 @c @fuindex strerror_r
4801 @prindex @code{strerror_r}
4802 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4803 systems (e.g., GNU C Library version 2.2.4) provide a
4804 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4805 can detect which is in use (@pxref{Particular Functions}).
4807 @item @code{strnlen}
4808 @c @fuindex strnlen
4809 @prindex @code{strnlen}
4810 AIX 4.3 provides a broken version which produces the
4811 following results:
4813 @example
4814 strnlen ("foobar", 0) = 0
4815 strnlen ("foobar", 1) = 3
4816 strnlen ("foobar", 2) = 2
4817 strnlen ("foobar", 3) = 1
4818 strnlen ("foobar", 4) = 0
4819 strnlen ("foobar", 5) = 6
4820 strnlen ("foobar", 6) = 6
4821 strnlen ("foobar", 7) = 6
4822 strnlen ("foobar", 8) = 6
4823 strnlen ("foobar", 9) = 6
4824 @end example
4826 @item @code{sysconf}
4827 @c @fuindex sysconf
4828 @prindex @code{sysconf}
4829 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., HP-UX
4830 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4831 @code{#ifdef}.
4833 @item @code{unlink}
4834 @c @fuindex unlink
4835 @prindex @code{unlink}
4836 The Posix spec says that @code{unlink} causes the given file to be
4837 removed only after there are no more open file handles for it.  Some
4838 non-Posix hosts have trouble with this requirement, though,
4839 and some DOS variants even corrupt the file system.
4841 @item @code{unsetenv}
4842 @c @fuindex unsetenv
4843 @prindex @code{unsetenv}
4844 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4845 can be removed with a call @code{putenv ("FOO=")}, as described under
4846 @code{putenv} above.
4848 @item @code{va_copy}
4849 @c @fuindex va_copy
4850 @prindex @code{va_copy}
4851 C99 and later provide @code{va_copy} for copying
4852 @code{va_list} variables.  It may be available in older environments
4853 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4854 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4855 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4856 portability.
4858 @item @code{va_list}
4859 @c @fuindex va_list
4860 @prindex @code{va_list}
4861 @code{va_list} is not necessarily just a pointer.  It can be a
4862 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4863 not portable.  Or it can be an array (e.g., @command{gcc} in some
4864 PowerPC configurations), which means as a function parameter it can be
4865 effectively call-by-reference and library routines might modify the
4866 value back in the caller (e.g., @code{vsnprintf} in the GNU C Library
4867 2.1).
4869 @item Signed @code{>>}
4870 Normally the C @code{>>} right shift of a signed type replicates the
4871 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4872 taken since Standard C doesn't require that behavior.  On those
4873 few processors without a native arithmetic shift (for instance Cray
4874 vector systems) zero bits may be shifted in, the same as a shift of an
4875 unsigned type.
4877 @item Integer @code{/}
4878 C divides signed integers by truncating their quotient toward zero,
4879 yielding the same result as Fortran.  However, before C99 the standard
4880 allowed C implementations to take the floor or ceiling of the quotient
4881 in some cases.  Hardly any implementations took advantage of this
4882 freedom, though, and it's probably not worth worrying about this issue
4883 nowadays.
4884 @end table
4887 @node Particular Functions
4888 @subsection Particular Function Checks
4889 @cindex Function, checking
4891 These macros check for particular C functions---whether they exist, and
4892 in some cases how they respond when given certain arguments.
4894 @anchor{AC_FUNC_ALLOCA}
4895 @defmac AC_FUNC_ALLOCA
4896 @acindex{FUNC_ALLOCA}
4897 @cvindex C_ALLOCA
4898 @cvindex HAVE_ALLOCA_H
4899 @ovindex ALLOCA
4900 @c @fuindex alloca
4901 @prindex @code{alloca}
4902 @hdrindex{alloca.h}
4903 @c @caindex working_alloca_h
4904 Check for the @code{alloca} function.  Define @code{HAVE_ALLOCA_H} if
4905 @file{alloca.h} defines a working @code{alloca}.  If not, look for a
4906 builtin alternative.  If either method succeeds, define
4907 @code{HAVE_ALLOCA}.  Otherwise, set the output variable @code{ALLOCA} to
4908 @samp{$@{LIBOBJDIR@}alloca.o} and define
4909 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4910 garbage collect).  This variable is separate from @code{LIBOBJS} so
4911 multiple programs can share the value of @code{ALLOCA} without needing
4912 to create an actual library, in case only some of them use the code in
4913 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4914 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4916 Source files that use @code{alloca} should start with a piece of code
4917 like the following, to declare it properly.
4919 @example
4920 @group
4921 #include <stdlib.h>
4922 #include <stddef.h>
4923 #ifdef HAVE_ALLOCA_H
4924 # include <alloca.h>
4925 #elif !defined alloca
4926 # ifdef __GNUC__
4927 #  define alloca __builtin_alloca
4928 # elif defined _MSC_VER
4929 #  include <malloc.h>
4930 #  define alloca _alloca
4931 # elif !defined HAVE_ALLOCA
4932 #  ifdef  __cplusplus
4933 extern "C"
4934 #  endif
4935 void *alloca (size_t);
4936 # endif
4937 #endif
4938 @end group
4939 @end example
4940 @end defmac
4942 @defmac AC_FUNC_CHOWN
4943 @acindex{FUNC_CHOWN}
4944 @cvindex HAVE_CHOWN
4945 @c @fuindex chown
4946 @prindex @code{chown}
4947 @caindex func_chown_works
4948 If the @code{chown} function is available and works (in particular, it
4949 should accept @option{-1} for @code{uid} and @code{gid}), define
4950 @code{HAVE_CHOWN}.  The result of this macro is cached in the
4951 @code{ac_cv_func_chown_works} variable.
4952 @end defmac
4954 @anchor{AC_FUNC_CLOSEDIR_VOID}
4955 @defmac AC_FUNC_CLOSEDIR_VOID
4956 @acindex{FUNC_CLOSEDIR_VOID}
4957 @cvindex CLOSEDIR_VOID
4958 @c @fuindex closedir
4959 @prindex @code{closedir}
4960 @caindex func_closedir_void
4961 If the @code{closedir} function does not return a meaningful value,
4962 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4963 return value for an error indicator.
4965 Currently this test is implemented by running a test program.  When
4966 cross compiling the pessimistic assumption that @code{closedir} does not
4967 return a meaningful value is made.
4969 The result of this macro is cached in the @code{ac_cv_func_closedir_void}
4970 variable.
4972 This macro is obsolescent, as @code{closedir} returns a meaningful value
4973 on current systems.  New programs need not use this macro.
4974 @end defmac
4976 @defmac AC_FUNC_ERROR_AT_LINE
4977 @acindex{FUNC_ERROR_AT_LINE}
4978 @c @fuindex error_at_line
4979 @prindex @code{error_at_line}
4980 @caindex lib_error_at_line
4981 If the @code{error_at_line} function is not found, require an
4982 @code{AC_LIBOBJ} replacement of @samp{error}.
4984 The result of this macro is cached in the @code{ac_cv_lib_error_at_line}
4985 variable.
4987 The @code{AC_FUNC_ERROR_AT_LINE} macro is obsolescent.  New programs
4988 should use Gnulib's @code{error} module.  @xref{Gnulib}.
4989 @end defmac
4991 @defmac AC_FUNC_FNMATCH
4992 @acindex{FUNC_FNMATCH}
4993 @c @fuindex fnmatch
4994 @prindex @code{fnmatch}
4995 @caindex func_fnmatch_works
4996 If the @code{fnmatch} function conforms to Posix, define
4997 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4998 the bugs in Solaris 2.4.
5000 Unlike the other specific
5001 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
5002 broken/missing @code{fnmatch}.  This is for historical reasons.
5003 See @code{AC_REPLACE_FNMATCH} below.
5005 The result of this macro is cached in the @code{ac_cv_func_fnmatch_works}
5006 variable.
5008 This macro is obsolescent.  New programs should use Gnulib's
5009 @code{fnmatch-posix} module.  @xref{Gnulib}.
5010 @end defmac
5012 @defmac AC_FUNC_FNMATCH_GNU
5013 @acindex{FUNC_FNMATCH_GNU}
5014 @c @fuindex fnmatch
5015 @prindex @code{fnmatch}
5016 @caindex func_fnmatch_gnu
5017 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
5018 whether @code{fnmatch} supports GNU extensions.  Detect common
5019 implementation bugs, for example, the bugs in the GNU C
5020 Library 2.1.
5022 The result of this macro is cached in the @code{ac_cv_func_fnmatch_gnu}
5023 variable.
5025 This macro is obsolescent.  New programs should use Gnulib's
5026 @code{fnmatch-gnu} module.  @xref{Gnulib}.
5027 @end defmac
5029 @anchor{AC_FUNC_FORK}
5030 @defmac AC_FUNC_FORK
5031 @acindex{FUNC_FORK}
5032 @cvindex HAVE_VFORK_H
5033 @cvindex HAVE_WORKING_FORK
5034 @cvindex HAVE_WORKING_VFORK
5035 @cvindex vfork
5036 @c @fuindex fork
5037 @prindex @code{fork}
5038 @c @fuindex vfork
5039 @prindex @code{vfork}
5040 @hdrindex{vfork.h}
5041 @c @caindex func_fork
5042 @c @caindex func_fork_works
5043 This macro checks for the @code{fork} and @code{vfork} functions.  If a
5044 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
5045 checks whether @code{fork} is just a stub by trying to run it.
5047 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
5048 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
5049 define @code{vfork} to be @code{fork} for backward compatibility with
5050 previous versions of @command{autoconf}.  This macro checks for several known
5051 errors in implementations of @code{vfork} and considers the system to not
5052 have a working @code{vfork} if it detects any of them.
5054 Since this macro defines @code{vfork} only for backward compatibility with
5055 previous versions of @command{autoconf} you're encouraged to define it
5056 yourself in new code:
5057 @example
5058 @group
5059 #ifndef HAVE_WORKING_VFORK
5060 # define vfork fork
5061 #endif
5062 @end group
5063 @end example
5065 The results of this macro are cached in the @code{ac_cv_func_fork_works}
5066 and @code{ac_cv_func_vfork_works} variables.  In order to override the
5067 test, you also need to set the @code{ac_cv_func_fork} and
5068 @code{ac_cv_func_vfork} variables.
5069 @end defmac
5071 @defmac AC_FUNC_FSEEKO
5072 @acindex{FUNC_FSEEKO}
5073 @cvindex _LARGEFILE_SOURCE
5074 @cvindex HAVE_FSEEKO
5075 @c @fuindex fseeko
5076 @prindex @code{fseeko}
5077 @c @fuindex ftello
5078 @prindex @code{ftello}
5079 @c @caindex sys_largefile_source
5080 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
5081 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
5082 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
5083 may occur when compiling with @code{AC_SYS_LARGEFILE} on
5084 largefile-sensitive systems where @code{off_t} does not default to a
5085 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
5086 @end defmac
5088 @defmac AC_FUNC_GETGROUPS
5089 @acindex{FUNC_GETGROUPS}
5090 @cvindex HAVE_GETGROUPS
5091 @ovindex GETGROUPS_LIBS
5092 @c @fuindex getgroups
5093 @prindex @code{getgroups}
5094 @caindex func_getgroups_works
5095 If the @code{getgroups} function is available and works (unlike on
5096 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
5097 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
5098 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
5099 @end defmac
5101 @anchor{AC_FUNC_GETLOADAVG}
5102 @defmac AC_FUNC_GETLOADAVG
5103 @acindex{FUNC_GETLOADAVG}
5104 @cvindex SVR4
5105 @cvindex DGUX
5106 @cvindex UMAX
5107 @cvindex UMAX4_3
5108 @cvindex HAVE_NLIST_H
5109 @cvindex NLIST_NAME_UNION
5110 @cvindex GETLOADAVG_PRIVILEGED
5111 @cvindex NEED_SETGID
5112 @cvindex C_GETLOADAVG
5113 @ovindex LIBOBJS
5114 @ovindex NEED_SETGID
5115 @ovindex KMEM_GROUP
5116 @ovindex GETLOADAVG_LIBS
5117 @c @fuindex getloadavg
5118 @prindex @code{getloadavg}
5119 Check how to get the system load averages.  To perform its tests
5120 properly, this macro needs the file @file{getloadavg.c}; therefore, be
5121 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
5122 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
5124 If the system has the @code{getloadavg} function, define
5125 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
5126 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
5127 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
5128 @samp{getloadavg} and possibly define several other C preprocessor
5129 macros and output variables:
5131 @enumerate
5132 @item
5133 Define @code{C_GETLOADAVG}.
5135 @item
5136 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
5137 those systems.
5139 @item
5140 @hdrindex{nlist.h}
5141 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
5143 @item
5144 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
5145 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
5146 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
5148 @item
5149 Programs may need to be installed set-group-ID (or set-user-ID) for
5150 @code{getloadavg} to work.  In this case, define
5151 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
5152 to @samp{true} (and otherwise to @samp{false}), and set
5153 @code{KMEM_GROUP} to the name of the group that should own the installed
5154 program.
5155 @end enumerate
5157 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
5158 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
5159 @end defmac
5161 @anchor{AC_FUNC_GETMNTENT}
5162 @defmac AC_FUNC_GETMNTENT
5163 @acindex{FUNC_GETMNTENT}
5164 @cvindex HAVE_GETMNTENT
5165 @c @fuindex getmntent
5166 @prindex @code{getmntent}
5167 @caindex search_getmntent
5168 Check for @code{getmntent} in the standard C library, and then in the
5169 @file{sun}, @file{seq}, and @file{gen} libraries, for UNICOS,
5170 IRIX 4, PTX, and UnixWare, respectively.  Then, if
5171 @code{getmntent} is available, define @code{HAVE_GETMNTENT} and set
5172 @code{ac_cv_func_getmntent} to @code{yes}.  Otherwise set
5173 @code{ac_cv_func_getmntent} to @code{no}.
5175 The result of this macro can be overridden by setting the cache variable
5176 @code{ac_cv_search_getmntent}.
5177 @end defmac
5179 @defmac AC_FUNC_GETPGRP
5180 @acindex{FUNC_GETPGRP}
5181 @cvindex GETPGRP_VOID
5182 @c @fuindex getpgid
5183 @c @fuindex getpgrp
5184 @prindex @code{getpgid}
5185 @prindex @code{getpgrp}
5186 @caindex func_getpgrp_void
5187 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
5188 @code{getpgrp}; this is the Posix behavior.  On older BSD
5189 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
5190 behaves like Posix's @code{getpgid}.
5192 @example
5193 #ifdef GETPGRP_VOID
5194   pid = getpgrp ();
5195 #else
5196   pid = getpgrp (0);
5197 #endif
5198 @end example
5200 This macro does not check whether
5201 @code{getpgrp} exists at all; if you need to work in that situation,
5202 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
5204 The result of this macro is cached in the @code{ac_cv_func_getpgrp_void}
5205 variable.
5207 This macro is obsolescent, as current systems have a @code{getpgrp}
5208 whose signature conforms to Posix.  New programs need not use this macro.
5209 @end defmac
5211 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
5212 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
5213 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
5214 @c @fuindex lstat
5215 @prindex @code{lstat}
5216 @caindex func_lstat_dereferences_slashed_symlink
5217 If @file{link} is a symbolic link, then @code{lstat} should treat
5218 @file{link/} the same as @file{link/.}.  However, many older
5219 @code{lstat} implementations incorrectly ignore trailing slashes.
5221 It is safe to assume that if @code{lstat} incorrectly ignores
5222 trailing slashes, then other symbolic-link-aware functions like
5223 @code{unlink} also incorrectly ignore trailing slashes.
5225 If @code{lstat} behaves properly, define
5226 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
5227 @code{AC_LIBOBJ} replacement of @code{lstat}.
5229 The result of this macro is cached in the
5230 @code{ac_cv_func_lstat_dereferences_slashed_symlink} variable.
5232 The @code{AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK} macro is obsolescent.
5233 New programs should use Gnulib's @code{lstat} module.  @xref{Gnulib}.
5234 @end defmac
5236 @defmac AC_FUNC_MALLOC
5237 @acindex{FUNC_MALLOC}
5238 @cvindex HAVE_MALLOC
5239 @cvindex malloc
5240 @c @fuindex malloc
5241 @prindex @code{malloc}
5242 @caindex func_malloc_0_nonnull
5243 If the @code{malloc} function is compatible with the GNU C
5244 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
5245 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
5246 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5247 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
5248 native @code{malloc} is not used in the main project.
5250 Typically, the replacement file @file{malloc.c} should look like (note
5251 the @samp{#undef malloc}):
5253 @verbatim
5254 #include <config.h>
5255 #undef malloc
5257 #include <sys/types.h>
5259 void *malloc ();
5261 /* Allocate an N-byte block of memory from the heap.
5262    If N is zero, allocate a 1-byte block.  */
5264 void *
5265 rpl_malloc (size_t n)
5267   if (n == 0)
5268     n = 1;
5269   return malloc (n);
5271 @end verbatim
5273 The result of this macro is cached in the
5274 @code{ac_cv_func_malloc_0_nonnull} variable.
5275 @end defmac
5277 @defmac AC_FUNC_MBRTOWC
5278 @acindex{FUNC_MBRTOWC}
5279 @cvindex HAVE_MBRTOWC
5280 @c @fuindex mbrtowc
5281 @prindex @code{mbrtowc}
5282 @caindex func_mbrtowc
5283 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
5284 type @code{mbstate_t} are properly declared.
5286 The result of this macro is cached in the @code{ac_cv_func_mbrtowc}
5287 variable.
5288 @end defmac
5290 @defmac AC_FUNC_MEMCMP
5291 @acindex{FUNC_MEMCMP}
5292 @ovindex LIBOBJS
5293 @c @fuindex memcmp
5294 @prindex @code{memcmp}
5295 @caindex func_memcmp_working
5296 If the @code{memcmp} function is not available, or does not work on
5297 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
5298 bytes or more and with at least one buffer not starting on a 4-byte
5299 boundary (such as the one on NeXT x86 OpenStep), require an
5300 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
5302 The result of this macro is cached in the
5303 @code{ac_cv_func_memcmp_working} variable.
5305 This macro is obsolescent, as current systems have a working
5306 @code{memcmp}.  New programs need not use this macro.
5307 @end defmac
5309 @defmac AC_FUNC_MKTIME
5310 @acindex{FUNC_MKTIME}
5311 @ovindex LIBOBJS
5312 @c @fuindex mktime
5313 @prindex @code{mktime}
5314 @caindex func_working_mktime
5315 If the @code{mktime} function is not available, or does not work
5316 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
5317 For the purposes of this test, @code{mktime} should conform to the
5318 Posix standard and should be the inverse of
5319 @code{localtime}.
5321 The result of this macro is cached in the
5322 @code{ac_cv_func_working_mktime} variable.
5324 The @code{AC_FUNC_MKTIME} macro is obsolescent.  New programs should
5325 use Gnulib's @code{mktime} module.  @xref{Gnulib}.
5326 @end defmac
5328 @anchor{AC_FUNC_MMAP}
5329 @defmac AC_FUNC_MMAP
5330 @acindex{FUNC_MMAP}
5331 @cvindex HAVE_MMAP
5332 @c @fuindex mmap
5333 @prindex @code{mmap}
5334 @caindex func_mmap_fixed_mapped
5335 If the @code{mmap} function exists and works correctly, define
5336 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
5337 memory.
5339 The result of this macro is cached in the
5340 @code{ac_cv_func_mmap_fixed_mapped} variable.
5341 @end defmac
5343 @defmac AC_FUNC_OBSTACK
5344 @acindex{FUNC_OBSTACK}
5345 @cvindex HAVE_OBSTACK
5346 @cindex obstack
5347 @caindex func_obstack
5348 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
5349 @code{AC_LIBOBJ} replacement for @samp{obstack}.
5351 The result of this macro is cached in the @code{ac_cv_func_obstack}
5352 variable.
5353 @end defmac
5355 @defmac AC_FUNC_REALLOC
5356 @acindex{FUNC_REALLOC}
5357 @cvindex HAVE_REALLOC
5358 @cvindex realloc
5359 @c @fuindex realloc
5360 @prindex @code{realloc}
5361 @caindex func_realloc_0_nonnull
5362 If the @code{realloc} function is compatible with the GNU C
5363 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
5364 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
5365 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
5366 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
5367 the native @code{realloc} is not used in the main project.  See
5368 @code{AC_FUNC_MALLOC} for details.
5370 The result of this macro is cached in the
5371 @code{ac_cv_func_realloc_0_nonnull} variable.
5372 @end defmac
5374 @defmac AC_FUNC_SELECT_ARGTYPES
5375 @acindex{FUNC_SELECT_ARGTYPES}
5376 @cvindex SELECT_TYPE_ARG1
5377 @cvindex SELECT_TYPE_ARG234
5378 @cvindex SELECT_TYPE_ARG5
5379 @c @fuindex select
5380 @prindex @code{select}
5381 @c @caindex func_select_args
5382 Determines the correct type to be passed for each of the
5383 @code{select} function's arguments, and defines those types
5384 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5385 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5386 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5387 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5389 This macro is obsolescent, as current systems have a @code{select} whose
5390 signature conforms to Posix.  New programs need not use this macro.
5391 @end defmac
5393 @defmac AC_FUNC_SETPGRP
5394 @acindex{FUNC_SETPGRP}
5395 @cvindex SETPGRP_VOID
5396 @c @fuindex setpgrp
5397 @prindex @code{setpgrp}
5398 @caindex func_setpgrp_void
5399 If @code{setpgrp} takes no argument (the Posix version), define
5400 @code{SETPGRP_VOID}.  Otherwise, it is the BSD version, which takes
5401 two process IDs as arguments.  This macro does not check whether
5402 @code{setpgrp} exists at all; if you need to work in that situation,
5403 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5405 The result of this macro is cached in the @code{ac_cv_func_setpgrp_void}
5406 variable.
5408 This macro is obsolescent, as current systems have a @code{setpgrp}
5409 whose signature conforms to Posix.  New programs need not use this macro.
5410 @end defmac
5412 @defmac AC_FUNC_STAT
5413 @defmacx AC_FUNC_LSTAT
5414 @acindex{FUNC_STAT}
5415 @acindex{FUNC_LSTAT}
5416 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5417 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5418 @c @fuindex stat
5419 @prindex @code{stat}
5420 @c @fuindex lstat
5421 @prindex @code{lstat}
5422 @caindex func_stat_empty_string_bug
5423 @caindex func_lstat_empty_string_bug
5424 Determine whether @code{stat} or @code{lstat} have the bug that it
5425 succeeds when given the zero-length file name as argument.  The @code{stat}
5426 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5427 this.
5429 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5430 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5431 replacement of it.
5433 The results of these macros are cached in the
5434 @code{ac_cv_func_stat_empty_string_bug} and the
5435 @code{ac_cv_func_lstat_empty_string_bug} variables, respectively.
5437 These macros are obsolescent, as no current systems have the bug.
5438 New programs need not use these macros.
5439 @end defmac
5441 @anchor{AC_FUNC_STRCOLL}
5442 @defmac AC_FUNC_STRCOLL
5443 @acindex{FUNC_STRCOLL}
5444 @cvindex HAVE_STRCOLL
5445 @c @fuindex strcoll
5446 @prindex @code{strcoll}
5447 @caindex func_strcoll_works
5448 If the @code{strcoll} function exists and works correctly, define
5449 @code{HAVE_STRCOLL}.  This does a bit more than
5450 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5451 definitions of @code{strcoll} that should not be used.
5453 The result of this macro is cached in the @code{ac_cv_func_strcoll_works}
5454 variable.
5455 @end defmac
5457 @defmac AC_FUNC_STRERROR_R
5458 @acindex{FUNC_STRERROR_R}
5459 @cvindex HAVE_STRERROR_R
5460 @cvindex HAVE_DECL_STRERROR_R
5461 @cvindex STRERROR_R_CHAR_P
5462 @c @fuindex strerror_r
5463 @caindex func_strerror_r_char_p
5464 @prindex @code{strerror_r}
5465 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5466 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5467 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5468 returns an @code{int} error number.  The Thread-Safe Functions option of
5469 Posix requires @code{strerror_r} to return @code{int}, but
5470 many systems (including, for example, version 2.2.4 of the GNU C
5471 Library) return a @code{char *} value that is not necessarily equal to
5472 the buffer argument.
5474 The result of this macro is cached in the
5475 @code{ac_cv_func_strerror_r_char_p} variable.
5476 @end defmac
5478 @anchor{AC_FUNC_STRFTIME}
5479 @defmac AC_FUNC_STRFTIME
5480 @acindex{FUNC_STRFTIME}
5481 @cvindex HAVE_STRFTIME
5482 @c @fuindex strftime
5483 @prindex @code{strftime}
5484 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5485 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5487 This macro is obsolescent, as no current systems require the @file{intl}
5488 library for @code{strftime}.  New programs need not use this macro.
5489 @end defmac
5491 @defmac AC_FUNC_STRTOD
5492 @acindex{FUNC_STRTOD}
5493 @ovindex POW_LIB
5494 @c @fuindex strtod
5495 @prindex @code{strtod}
5496 @caindex func_strtod
5497 @caindex func_pow
5498 If the @code{strtod} function does not exist or doesn't work correctly,
5499 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5500 because @file{strtod.c} is likely to need @samp{pow}, set the output
5501 variable @code{POW_LIB} to the extra library needed.
5503 This macro caches its result in the @code{ac_cv_func_strtod} variable
5504 and depends upon the result in the @code{ac_cv_func_pow} variable.
5506 The @code{AC_FUNC_STRTOD} macro is obsolescent.  New programs should
5507 use Gnulib's @code{strtod} module.  @xref{Gnulib}.
5508 @end defmac
5510 @defmac AC_FUNC_STRTOLD
5511 @acindex{FUNC_STRTOLD}
5512 @cvindex HAVE_STRTOLD
5513 @prindex @code{strtold}
5514 @caindex func_strtold
5515 If the @code{strtold} function exists and conforms to C99 or later, define
5516 @code{HAVE_STRTOLD}.
5518 This macro caches its result in the @code{ac_cv_func_strtold} variable.
5519 @end defmac
5521 @defmac AC_FUNC_STRNLEN
5522 @acindex{FUNC_STRNLEN}
5523 @cvindex HAVE_STRNLEN
5524 @c @fuindex strnlen
5525 @prindex @code{strnlen}
5526 @caindex func_strnlen_working
5527 If the @code{strnlen} function is not available, or is buggy (like the one
5528 from AIX 4.3), require an @code{AC_LIBOBJ} replacement for it.
5530 This macro caches its result in the @code{ac_cv_func_strnlen_working}
5531 variable.
5532 @end defmac
5534 @anchor{AC_FUNC_UTIME_NULL}
5535 @defmac AC_FUNC_UTIME_NULL
5536 @acindex{FUNC_UTIME_NULL}
5537 @cvindex HAVE_UTIME_NULL
5538 @c @fuindex utime
5539 @prindex @code{utime}
5540 @caindex func_utime_null
5541 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5542 the present, define @code{HAVE_UTIME_NULL}.
5544 This macro caches its result in the @code{ac_cv_func_utime_null}
5545 variable.
5547 This macro is obsolescent, as all current systems have a @code{utime}
5548 that behaves this way.  New programs need not use this macro.
5549 @end defmac
5551 @anchor{AC_FUNC_VPRINTF}
5552 @defmac AC_FUNC_VPRINTF
5553 @acindex{FUNC_VPRINTF}
5554 @cvindex HAVE_VPRINTF
5555 @cvindex HAVE_DOPRNT
5556 @c @fuindex vprintf
5557 @prindex @code{vprintf}
5558 @c @fuindex vsprintf
5559 @prindex @code{vsprintf}
5560 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5561 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5562 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5563 are also available.)
5565 This macro is obsolescent, as all current systems have @code{vprintf}.
5566 New programs need not use this macro.
5567 @end defmac
5569 @defmac AC_REPLACE_FNMATCH
5570 @acindex{REPLACE_FNMATCH}
5571 @c @fuindex fnmatch
5572 @prindex @code{fnmatch}
5573 @hdrindex{fnmatch.h}
5574 @caindex func_fnmatch_works
5575 If the @code{fnmatch} function does not conform to Posix (see
5576 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5578 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5579 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5580 copy of the source code of GNU @code{fnmatch}.  If necessary,
5581 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5582 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5583 included in place of the system @code{<fnmatch.h>}.
5585 This macro caches its result in the @code{ac_cv_func_fnmatch_works}
5586 variable.
5588 This macro is obsolescent, as it assumes the use of particular source
5589 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5590 which provides this macro along with the source files.  @xref{Gnulib}.
5591 @end defmac
5595 @node Generic Functions
5596 @subsection Generic Function Checks
5598 These macros are used to find functions not covered by the ``particular''
5599 test macros.  If the functions might be in libraries other than the
5600 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5601 If you need to check the behavior of a function as well as find out
5602 whether it is present, you have to write your own test for
5603 it (@pxref{Writing Tests}).
5605 @anchor{AC_CHECK_FUNC}
5606 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5607   @ovar{action-if-not-found})
5608 @acindex{CHECK_FUNC}
5609 @caindex func_@var{function}
5610 If C function @var{function} is available, run shell commands
5611 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5612 want to define a symbol if the function is available, consider using
5613 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5614 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5615 standardized than C++.  (@pxref{Language Choice}, for more information
5616 about selecting the language for checks.)
5618 This macro caches its result in the @code{ac_cv_func_@var{function}}
5619 variable.
5620 @end defmac
5622 @anchor{AC_CHECK_FUNCS}
5623 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5624   @ovar{action-if-not-found})
5625 @acindex{CHECK_FUNCS}
5626 @cvindex HAVE_@var{function}
5627 For each @var{function} enumerated in the blank-or-newline-separated argument
5628 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5629 If @var{action-if-found} is given, it is additional shell code to
5630 execute when one of the functions is found.  You can give it a value of
5631 @samp{break} to break out of the loop on the first match.  If
5632 @var{action-if-not-found} is given, it is executed when one of the
5633 functions is not found.
5635 Results are cached for each @var{function} as in @code{AC_CHECK_FUNC}.
5636 @end defmac
5638 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5639 @acindex{CHECK_FUNCS_ONCE}
5640 @cvindex HAVE_@var{function}
5641 For each @var{function} enumerated in the blank-or-newline-separated argument
5642 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5643 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5644 checking code at most once, so that @command{configure} is smaller and
5645 faster; but the checks cannot be conditionalized and are always done once,
5646 early during the @command{configure} run.
5647 @end defmac
5649 @sp 1
5651 Autoconf follows a philosophy that was formed over the years by those
5652 who have struggled for portability: isolate the portability issues in
5653 specific files, and then program as if you were in a Posix
5654 environment.  Some functions may be missing or unfixable, and your
5655 package must be ready to replace them.
5657 Suitable replacements for many such problem functions are available from
5658 Gnulib (@pxref{Gnulib}).
5660 @defmac AC_LIBOBJ (@var{function})
5661 @acindex{LIBOBJ}
5662 @ovindex LIBOBJS
5663 Specify that @samp{@var{function}.c} must be included in the executables
5664 to replace a missing or broken implementation of @var{function}.
5666 @vrindex ac_objext
5667 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5668 variable @code{LIBOBJS} if it is not already in, and calls
5669 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5670 directly change @code{LIBOBJS}, since this is not traceable.
5671 @end defmac
5673 @defmac AC_LIBSOURCE (@var{file})
5674 @acindex{LIBSOURCE}
5675 Specify that @var{file} might be needed to compile the project.  If you
5676 need to know what files might be needed by a @file{configure.ac}, you
5677 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5679 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5680 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5681 that case, since shell variables cannot be traced statically, you must
5682 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5683 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5684 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5685 @code{"foo"} or @code{"bar"}, you should do:
5687 @example
5688 AC_LIBSOURCE([foo.c])
5689 AC_LIBSOURCE([bar.c])
5690 AC_LIBOBJ([$foo_or_bar])
5691 @end example
5693 @noindent
5694 There is usually a way to avoid this, however, and you are encouraged to
5695 simply call @code{AC_LIBOBJ} with literal arguments.
5697 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5698 slightly different semantics: the old macro took the function name,
5699 e.g., @code{foo}, as its argument rather than the file name.
5700 @end defmac
5702 @defmac AC_LIBSOURCES (@var{files})
5703 @acindex{LIBSOURCES}
5704 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5705 comma-separated M4 list.  Thus, the above example might be rewritten:
5707 @example
5708 AC_LIBSOURCES([foo.c, bar.c])
5709 AC_LIBOBJ([$foo_or_bar])
5710 @end example
5711 @end defmac
5713 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5714 @acindex{CONFIG_LIBOBJ_DIR}
5715 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5716 @var{directory}, a name relative to the top level of the
5717 source tree.  The replacement directory defaults to @file{.}, the top
5718 level directory, and the most typical value is @file{lib}, corresponding
5719 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5721 @command{configure} might need to know the replacement directory for the
5722 following reasons: (i) some checks use the replacement files, (ii) some
5723 macros bypass broken system headers by installing links to the
5724 replacement headers (iii) when used in conjunction with Automake,
5725 within each makefile, @var{directory} is used as a relative path
5726 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5727 @code{LTLIBOBJS}, etc.
5728 @end defmac
5730 @sp 1
5732 It is common to merely check for the existence of a function, and ask
5733 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5734 a convenient shorthand.
5736 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5737 @acindex{REPLACE_FUNCS}
5738 @cvindex HAVE_@var{function}
5739 @ovindex LIBOBJS
5740 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5741 @var{action-if-not-found}.  You can declare your replacement function by
5742 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5743 system has the function, it probably declares it in a header file you
5744 should be including, so you shouldn't redeclare it lest your declaration
5745 conflict.
5746 @end defmac
5748 @node Header Files
5749 @section Header Files
5750 @cindex Header, checking
5752 The following macros check for the presence of certain C header files.
5753 If there is no macro specifically defined to check for a header file you need,
5754 and you don't need to check for any special properties of
5755 it, then you can use one of the general header-file check macros.
5757 @menu
5758 * Header Portability::          Collected knowledge on common headers
5759 * Particular Headers::          Special handling to find certain headers
5760 * Generic Headers::             How to find other headers
5761 @end menu
5763 @node Header Portability
5764 @subsection Portability of Headers
5765 @cindex Portability of headers
5766 @cindex Header portability
5768 This section documents some collected knowledge about common headers,
5769 and the problems they cause.  By definition, this list always requires
5770 additions.  A much more complete list is maintained by the Gnulib
5771 project (@pxref{Gnulib}), covering @ref{Header File Substitutes, ,
5772 Posix Headers, gnulib, GNU gnulib} and @ref{Glibc Header File
5773 Substitutes, , Glibc Headers, gnulib, GNU gnulib}.  Please help us keep
5774 the gnulib list as complete as possible.
5776 When we say that a header ``may require'' some set of other headers, we
5777 mean that it may be necessary for you to manually include those other
5778 headers first, or the contents of the header under test will fail to
5779 compile.  When checking for these headers, you must provide the
5780 potentially-required headers in the @var{includes} argument to
5781 @code{AC_CHECK_HEADER} or @code{AC_CHECK_HEADERS}, or the check will
5782 fail spuriously.  @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes})
5783 arranges to include a number of common requirements and should normally
5784 come first in your @var{includes}.  For example, @file{net/if.h} may
5785 require @file{sys/types.h}, @file{sys/socket.h}, or both, and
5786 @code{AC_INCLUDES_DEFAULT} handles @file{sys/types.h} but not
5787 @file{sys/socket.h}, so you should check for it like this:
5789 @example
5790 AC_CHECK_HEADERS([sys/socket.h])
5791 AC_CHECK_HEADERS([net/if.h], [], [],
5792 [AC_INCLUDES_DEFAULT[
5793 #ifdef HAVE_SYS_SOCKET_H
5794 # include <sys/socket.h>
5795 #endif
5797 @end example
5799 Note that the example mixes single quoting (for@code{AC_INCLUDES_DEFAULT},
5800 so that it gets expanded) and double quoting (to ensure that each
5801 preprocessor @code{#} gets treated as a literal string rather than a
5802 comment).
5804 @table @asis
5806 @item @file{limits.h}
5807 In C99 and later, @file{limits.h} defines @code{LLONG_MIN},
5808 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5809 environments (e.g., default GCC 4.0.2 + glibc 2.4) do not
5810 define them.
5812 @item @file{memory.h}
5813 @hdrindex{memory.h}
5814 This header file is obsolete; use @file{string.h} instead.
5816 @item @file{strings.h}
5817 @hdrindex{strings.h}
5818 On some systems, this is the only header that declares
5819 @code{strcasecmp}, @code{strncasecmp}, and @code{ffs}.
5821 This header may or may not include @file{string.h} for you.  However, on
5822 all recent systems it is safe to include both @file{string.h} and
5823 @file{strings.h}, in either order, in the same source file.
5825 @item @file{inttypes.h} vs.@: @file{stdint.h}
5826 @hdrindex{inttypes.h}
5827 @hdrindex{stdint.h}
5828 C99 specifies that @file{inttypes.h} includes @file{stdint.h}, so there's
5829 no need to include @file{stdint.h} separately in a standard environment.
5830 However, some implementations have @file{inttypes.h} but not @file{stdint.h}
5831 (e.g., Solaris 7), and some have @file{stdint.h} but not @file{inttypes.h}
5832 (e.g. MSVC 2012).  Therefore, it is necessary to check for each and include
5833 each only if available.
5835 @item @file{linux/irda.h}
5836 @hdrindex{linux/irda.h}
5837 This header may require @file{linux/types.h} and/or @file{sys/socket.h}.
5839 @item @file{linux/random.h}
5840 @hdrindex{linux/random.h}
5841 This header may require @file{linux/types.h}.
5843 @item @file{net/if.h}
5844 @hdrindex{net/if.h}
5845 This header may require @file{sys/types.h} and/or @file{sys/socket.h}.
5847 @item @file{netinet/if_ether.h}
5848 @hdrindex{netinet/if_ether.h}
5849 This header may require some combination of @file{sys/types.h},
5850 @file{sys/socket.h}, @file{netinet/in.h}, and @file{net/if.h}.
5852 @item @file{sys/mount.h}
5853 @hdrindex{sys/mount.h}
5854 This header may require @file{sys/params.h}.
5856 @item @file{sys/ptem.h}
5857 @hdrindex{sys/ptem.h}
5858 This header may require @file{sys/stream.h}.
5860 @item @file{sys/socket.h}
5861 @hdrindex{sys/socket.h}
5862 This header may require @file{sys/types.h}.
5864 @item @file{sys/ucred.h}
5865 @hdrindex{sys/ucred.h}
5866 This header may require @file{sys/types.h}.
5868 @item @file{X11/extensions/scrnsaver.h}
5869 @hdrindex{X11/extensions/scrnsaver.h}
5870 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5871 so required that you might not even consider looking for it.
5873 @end table
5876 @node Particular Headers
5877 @subsection Particular Header Checks
5879 These macros check for particular system header files---whether they
5880 exist, and in some cases whether they declare certain symbols.
5882 @defmac AC_CHECK_HEADER_STDBOOL
5883 @acindex{CHECK_HEADER_STDBOOL}
5884 @cvindex HAVE__BOOL
5885 @hdrindex{stdbool.h}
5886 @caindex header_stdbool_h
5887 Check whether @file{stdbool.h} exists and conforms to C99 or later,
5888 and cache the result in the @code{ac_cv_header_stdbool_h} variable.
5889 If the type @code{_Bool} is defined, define @code{HAVE__BOOL} to 1.
5891 This macro is intended for use by Gnulib (@pxref{Gnulib}) and other
5892 packages that supply a substitute @file{stdbool.h} on platforms lacking
5893 a conforming one.  The @code{AC_HEADER_STDBOOL} macro is better for code
5894 that explicitly checks for @file{stdbool.h}.
5895 @end defmac
5897 @defmac AC_HEADER_ASSERT
5898 @acindex{HEADER_ASSERT}
5899 @cvindex NDEBUG
5900 @hdrindex{assert.h}
5901 Check whether to enable assertions in the style of @file{assert.h}.
5902 Assertions are enabled by default, but the user can override this by
5903 invoking @command{configure} with the @option{--disable-assert} option.
5904 @end defmac
5906 @anchor{AC_HEADER_DIRENT}
5907 @defmac AC_HEADER_DIRENT
5908 @acindex{HEADER_DIRENT}
5909 @cvindex HAVE_DIRENT_H
5910 @cvindex HAVE_NDIR_H
5911 @cvindex HAVE_SYS_DIR_H
5912 @cvindex HAVE_SYS_NDIR_H
5913 @hdrindex{dirent.h}
5914 @hdrindex{sys/ndir.h}
5915 @hdrindex{sys/dir.h}
5916 @hdrindex{ndir.h}
5917 Check for the following header files.  For the first one that is
5918 found and defines @samp{DIR}, define the listed C preprocessor macro:
5920 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5921 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5922 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5923 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5924 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5925 @end multitable
5927 The directory-library declarations in your source code should look
5928 something like the following:
5930 @example
5931 @group
5932 #include <sys/types.h>
5933 #ifdef HAVE_DIRENT_H
5934 # include <dirent.h>
5935 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5936 #else
5937 # define dirent direct
5938 # define NAMLEN(dirent) ((dirent)->d_namlen)
5939 # ifdef HAVE_SYS_NDIR_H
5940 #  include <sys/ndir.h>
5941 # endif
5942 # ifdef HAVE_SYS_DIR_H
5943 #  include <sys/dir.h>
5944 # endif
5945 # ifdef HAVE_NDIR_H
5946 #  include <ndir.h>
5947 # endif
5948 #endif
5949 @end group
5950 @end example
5952 Using the above declarations, the program would declare variables to be
5953 of type @code{struct dirent}, not @code{struct direct}, and would access
5954 the length of a directory entry name by passing a pointer to a
5955 @code{struct dirent} to the @code{NAMLEN} macro.
5957 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5959 This macro is obsolescent, as all current systems with directory
5960 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5962 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5963 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5964 @end defmac
5966 @anchor{AC_HEADER_MAJOR}
5967 @defmac AC_HEADER_MAJOR
5968 @acindex{HEADER_MAJOR}
5969 @cvindex MAJOR_IN_MKDEV
5970 @cvindex MAJOR_IN_SYSMACROS
5971 @hdrindex{sys/mkdev.h}
5972 @hdrindex{sys/sysmacros.h}
5973 Detect the headers required to use @code{makedev}, @code{major}, and
5974 @code{minor}.  These functions may be defined by @file{sys/mkdev.h},
5975 @code{sys/sysmacros.h}, or @file{sys/types.h}.
5977 @code{AC_HEADER_MAJOR} defines @code{MAJOR_IN_MKDEV} if they are in
5978 @file{sys/mkdev.h}, or @code{MAJOR_IN_SYSMACROS} if they are in
5979 @file{sys/sysmacros.h}.  If neither macro is defined, they are either in
5980 @file{sys/types.h} or unavailable.
5982 To properly use these functions, your code should contain something
5983 like:
5985 @verbatim
5986 #include <sys/types.h>
5987 #ifdef MAJOR_IN_MKDEV
5988 # include <sys/mkdev.h>
5989 #elif MAJOR_IN_SYSMACROS
5990 # include <sys/sysmacros.h>
5991 #endif
5992 @end verbatim
5994 Note: Configure scripts built with Autoconf 2.69 or earlier will not
5995 detect a problem if @file{sys/types.h} contains definitions of
5996 @code{major}, @code{minor}, and/or @code{makedev} that trigger compiler
5997 warnings upon use.  This is known to occur with GNU libc 2.25, where
5998 those definitions are being deprecated to reduce namespace pollution.
5999 If it is not practical to use Autoconf 2.70 to regenerate the configure
6000 script of affected software, you can work around the problem by setting
6001 @samp{ac_cv_header_sys_types_h_makedev=no}, as an argument to
6002 @command{configure} or as part of a @file{config.site} site default file
6003 (@pxref{Site Defaults}).
6004 @end defmac
6006 @defmac AC_HEADER_RESOLV
6007 @acindex{HEADER_RESOLV}
6008 @cvindex HAVE_RESOLV_H
6009 @hdrindex{resolv.h}
6010 Checks for header @file{resolv.h}, checking for prerequisites first.
6011 To properly use @file{resolv.h}, your code should contain something like
6012 the following:
6014 @verbatim
6015 #ifdef HAVE_SYS_TYPES_H
6016 #  include <sys/types.h>
6017 #endif
6018 #ifdef HAVE_NETINET_IN_H
6019 #  include <netinet/in.h>   /* inet_ functions / structs */
6020 #endif
6021 #ifdef HAVE_ARPA_NAMESER_H
6022 #  include <arpa/nameser.h> /* DNS HEADER struct */
6023 #endif
6024 #ifdef HAVE_NETDB_H
6025 #  include <netdb.h>
6026 #endif
6027 #include <resolv.h>
6028 @end verbatim
6029 @end defmac
6031 @anchor{AC_HEADER_STAT}
6032 @defmac AC_HEADER_STAT
6033 @acindex{HEADER_STAT}
6034 @cvindex STAT_MACROS_BROKEN
6035 @hdrindex{sys/stat.h}
6036 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
6037 @file{sys/stat.h} do not work properly (returning false positives),
6038 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
6039 Amdahl UTS and Motorola System V/88.
6041 This macro is obsolescent, as no current systems have the bug.
6042 New programs need not use this macro.
6043 @end defmac
6045 @defmac AC_HEADER_STDBOOL
6046 @acindex{HEADER_STDBOOL}
6047 @cvindex HAVE_STDBOOL_H
6048 @cvindex HAVE__BOOL
6049 @hdrindex{stdbool.h}
6050 @caindex header_stdbool_h
6051 If @file{stdbool.h} exists and conforms to C99 or later, define
6052 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
6053 @code{HAVE__BOOL} to 1.  To fulfill the standard's requirements, your
6054 program could contain the following code:
6056 @example
6057 @group
6058 #ifdef HAVE_STDBOOL_H
6059 # include <stdbool.h>
6060 #else
6061 # ifndef HAVE__BOOL
6062 #  ifdef __cplusplus
6063 typedef bool _Bool;
6064 #  else
6065 #   define _Bool signed char
6066 #  endif
6067 # endif
6068 # define bool _Bool
6069 # define false 0
6070 # define true 1
6071 # define __bool_true_false_are_defined 1
6072 #endif
6073 @end group
6074 @end example
6076 Alternatively you can use the @samp{stdbool} package of Gnulib
6077 (@pxref{Gnulib}).  It simplifies your code so that it can say just
6078 @code{#include <stdbool.h>}, and it adds support for less-common
6079 platforms.
6081 This macro caches its result in the @code{ac_cv_header_stdbool_h}
6082 variable.
6084 This macro differs from @code{AC_CHECK_HEADER_STDBOOL} only in that it
6085 defines @code{HAVE_STDBOOL_H} whereas @code{AC_CHECK_HEADER_STDBOOL}
6086 does not.
6087 @end defmac
6089 @anchor{AC_HEADER_STDC}
6090 @defmac AC_HEADER_STDC
6091 @acindex{HEADER_STDC}
6092 @cvindex STDC_HEADERS
6093 @caindex header_stdc
6095 This macro is obsolescent.  Its sole effect is to make sure that all the
6096 headers that are included by @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6097 Includes}), but not part of ISO C90, have been checked for.
6099 All hosted environments that are still of interest for portable code
6100 provide all of the headers specified in ISO C90 (as amended in 1995).
6101 @end defmac
6103 @defmac AC_HEADER_SYS_WAIT
6104 @acindex{HEADER_SYS_WAIT}
6105 @cvindex HAVE_SYS_WAIT_H
6106 @hdrindex{sys/wait.h}
6107 @caindex header_sys_wait_h
6108 If @file{sys/wait.h} exists and is compatible with Posix, define
6109 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
6110 does not exist, or if it uses the old BSD @code{union wait} instead
6111 of @code{int} to store a status value.  If @file{sys/wait.h} is not
6112 Posix compatible, then instead of including it, define the
6113 Posix macros with their usual interpretations.  Here is an
6114 example:
6116 @example
6117 @group
6118 #include <sys/types.h>
6119 #ifdef HAVE_SYS_WAIT_H
6120 # include <sys/wait.h>
6121 #endif
6122 #ifndef WEXITSTATUS
6123 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
6124 #endif
6125 #ifndef WIFEXITED
6126 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
6127 #endif
6128 @end group
6129 @end example
6131 @noindent
6132 This macro caches its result in the @code{ac_cv_header_sys_wait_h}
6133 variable.
6135 This macro is obsolescent, as current systems are compatible with Posix.
6136 New programs need not use this macro.
6137 @end defmac
6139 @cvindex _POSIX_VERSION
6140 @hdrindex{unistd.h}
6141 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
6142 Posix systems.  If there is no @file{unistd.h}, it is definitely
6143 not a Posix system.  However, some non-Posix systems do
6144 have @file{unistd.h}.
6146 The way to check whether the system supports Posix is:
6148 @example
6149 @group
6150 #ifdef HAVE_UNISTD_H
6151 # include <sys/types.h>
6152 # include <unistd.h>
6153 #endif
6155 #ifdef _POSIX_VERSION
6156 /* Code for Posix systems.  */
6157 #endif
6158 @end group
6159 @end example
6161 @defmac AC_HEADER_TIOCGWINSZ
6162 @acindex{HEADER_TIOCGWINSZ}
6163 @cvindex GWINSZ_IN_SYS_IOCTL
6164 @hdrindex{sys/ioctl.h}
6165 @hdrindex{termios.h}
6166 @c FIXME: I need clarifications from Jim.
6167 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
6168 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
6169 found in @file{<termios.h>}.
6171 Use:
6173 @example
6174 @group
6175 #ifdef HAVE_TERMIOS_H
6176 # include <termios.h>
6177 #endif
6179 #ifdef GWINSZ_IN_SYS_IOCTL
6180 # include <sys/ioctl.h>
6181 #endif
6182 @end group
6183 @end example
6184 @end defmac
6186 @node Generic Headers
6187 @subsection Generic Header Checks
6189 These macros are used to find system header files not covered by the
6190 ``particular'' test macros.  If you need to check the contents of a header
6191 as well as find out whether it is present, you have to write your own
6192 test for it (@pxref{Writing Tests}).
6194 @anchor{AC_CHECK_HEADER}
6195 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
6196   @ovar{action-if-not-found}, @ovar{includes})
6197 @acindex{CHECK_HEADER}
6198 @caindex header_@var{header-file}
6199 If the system header file @var{header-file} is compilable, execute shell
6200 commands @var{action-if-found}, otherwise execute
6201 @var{action-if-not-found}.  If you just want to define a symbol if the
6202 header file is available, consider using @code{AC_CHECK_HEADERS}
6203 instead.
6205 @var{includes} should be the appropriate @dfn{prerequisite} code, i.e.@:
6206 whatever might be required to appear above
6207 @samp{#include <@var{header-file}>} for it to compile without error.
6208 This can be anything, but will normally be additional @samp{#include}
6209 directives. If @var{includes} is omitted or empty, @file{configure} will
6210 use the contents of the macro @code{AC_INCLUDES_DEFAULT}.
6211 @xref{Default Includes}.
6213 This macro used to check only for the @emph{presence} of a header, not
6214 whether its contents were acceptable to the compiler.  Some older
6215 @command{configure} scripts rely on this behavior, so it is still
6216 available by specifying @samp{-} as @var{includes}.  This mechanism is
6217 deprecated as of Autoconf 2.70; situations where a preprocessor-only
6218 check is required should use @code{AC_PREPROC_IFELSE}.
6219 @xref{Running the Preprocessor}.
6221 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6222 variable, with characters not suitable for a variable name mapped to
6223 underscores.
6224 @end defmac
6226 @anchor{AC_CHECK_HEADERS}
6227 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
6228   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6229   @ovar{includes})
6230 @acindex{CHECK_HEADERS}
6231 @cvindex HAVE_@var{header}
6232 @caindex header_@var{header-file}
6233 For each given system header file @var{header-file} in the
6234 blank-separated argument list that exists, define
6235 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
6236 is given, it is additional shell code to execute when one of the header
6237 files is found.  You can give it a value of @samp{break} to break out of
6238 the loop on the first match.  If @var{action-if-not-found} is given, it
6239 is executed when one of the header files is not found.
6241 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
6242 choose the set of preprocessor directives supplied before the header
6243 under test.
6245 This macro caches its result in the @code{ac_cv_header_@var{header-file}}
6246 variable, with characters not suitable for a variable name mapped to
6247 underscores.
6248 @end defmac
6250 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
6251 @acindex{CHECK_HEADERS_ONCE}
6252 @cvindex HAVE_@var{header}
6253 For each given system header file @var{header-file} in the
6254 blank-separated argument list that exists, define
6255 @code{HAVE_@var{header-file}} (in all capitals).
6257 If you do not need the full power of @code{AC_CHECK_HEADERS}, this
6258 variant generates smaller, faster @command{configure} files.  All
6259 headers passed to @code{AC_CHECK_HEADERS_ONCE} are checked for in one
6260 pass, early during the @command{configure} run.  The checks cannot be
6261 conditionalized, you cannot specify an @var{action-if-found} or
6262 @var{action-if-not-found}, and @code{AC_INCLUDES_DEFAULT} is always used
6263 for the prerequisites.
6264 @end defmac
6266 In previous versions of Autoconf, these macros merely checked whether
6267 the header was accepted by the preprocessor.  This was changed because
6268 the old test was inappropriate for typical uses.  Headers are typically
6269 used to compile, not merely to preprocess, and the old behavior
6270 sometimes accepted headers that clashed at compile-time
6271 (@pxref{Present But Cannot Be Compiled}).  If for some reason it is
6272 inappropriate to check whether a header is compilable, you should use
6273 @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}) instead of
6274 these macros.
6276 Requiring each header to compile improves the robustness of the test,
6277 but it also requires you to make sure that the @var{includes} are
6278 correct.  Most system headers nowadays make sure to @code{#include}
6279 whatever they require, or else have their dependencies satisfied by
6280 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), but
6281 @pxref{Header Portability}, for known exceptions.  In general, if you
6282 are looking for @file{bar.h}, which requires that @file{foo.h} be
6283 included first if it exists, you should do something like this:
6285 @example
6286 AC_CHECK_HEADERS([foo.h])
6287 AC_CHECK_HEADERS([bar.h], [], [],
6288 [#ifdef HAVE_FOO_H
6289 # include <foo.h>
6290 #endif
6292 @end example
6294 @node Declarations
6295 @section Declarations
6296 @cindex Declaration, checking
6298 The following macros check for the declaration of variables and
6299 functions.  If there is no macro specifically defined to check for a
6300 symbol you need, then you can use the general macros (@pxref{Generic
6301 Declarations}) or, for more complex tests, you may use
6302 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6304 @menu
6305 * Particular Declarations::     Macros to check for certain declarations
6306 * Generic Declarations::        How to find other declarations
6307 @end menu
6309 @node Particular Declarations
6310 @subsection Particular Declaration Checks
6312 There are no specific macros for declarations.
6314 @node Generic Declarations
6315 @subsection Generic Declaration Checks
6317 These macros are used to find declarations not covered by the ``particular''
6318 test macros.
6320 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
6321   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6322 @acindex{CHECK_DECL}
6323 @caindex have_decl_@var{symbol}
6324 If @var{symbol} (a function, variable, or constant) is not declared in
6325 @var{includes} and a declaration is needed, run the shell commands
6326 @var{action-if-not-found}, otherwise @var{action-if-found}.
6327 @var{includes} is a series of include directives, defaulting to
6328 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6329 prior to the declaration under test.
6331 This macro actually tests whether @var{symbol} is defined as a macro or
6332 can be used as an r-value, not whether it is really declared, because it
6333 is much safer to avoid introducing extra declarations when they are not
6334 needed.  In order to facilitate use of C++ and overloaded function
6335 declarations, it is possible to specify function argument types in
6336 parentheses for types which can be zero-initialized:
6338 @example
6339 AC_CHECK_DECL([basename(char *)])
6340 @end example
6342 Some compilers don't indicate every missing declaration by the error
6343 status.  This macro checks the standard error from such compilers and
6344 considers a declaration missing if any warnings have been reported.  For
6345 most compilers, though, warnings do not affect this macro's outcome
6346 unless @code{AC_LANG_WERROR} is also specified.
6348 This macro caches its result in the @code{ac_cv_have_decl_@var{symbol}}
6349 variable, with characters not suitable for a variable name mapped to
6350 underscores.
6351 @end defmac
6353 @anchor{AC_CHECK_DECLS}
6354 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
6355   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6356 @acindex{CHECK_DECLS}
6357 @cvindex HAVE_DECL_@var{symbol}
6358 @caindex have_decl_@var{symbol}
6359 For each of the @var{symbols} (@emph{comma}-separated list with optional
6360 function argument types for C++ overloads), define
6361 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6362 @var{symbol} is declared, otherwise to @samp{0}.  If
6363 @var{action-if-not-found} is given, it is additional shell code to
6364 execute when one of the function declarations is needed, otherwise
6365 @var{action-if-found} is executed.
6367 @var{includes} is a series of include directives, defaulting to
6368 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6369 prior to the declarations under test.
6371 This macro uses an M4 list as first argument:
6372 @example
6373 AC_CHECK_DECLS([strdup])
6374 AC_CHECK_DECLS([strlen])
6375 AC_CHECK_DECLS([malloc, realloc, calloc, free])
6376 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
6377 AC_CHECK_DECLS([[basename(char *)], [dirname(char *)]])
6378 @end example
6380 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
6381 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
6382 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
6383 @emph{sure} that the check was performed, use
6384 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6386 @example
6387 #if !HAVE_DECL_SYMBOL
6388 extern char *symbol;
6389 #endif
6390 @end example
6392 @noindent
6393 If the test may have not been performed, however, because it is safer
6394 @emph{not} to declare a symbol than to use a declaration that conflicts
6395 with the system's one, you should use:
6397 @example
6398 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6399 void *malloc (size_t *s);
6400 #endif
6401 @end example
6403 @noindent
6404 You fall into the second category only in extreme situations: either
6405 your files may be used without being configured, or they are used during
6406 the configuration.  In most cases the traditional approach is enough.
6408 Some compilers don't indicate every missing declaration by the error
6409 status.  This macro checks the standard error from such compilers and
6410 considers a declaration missing if any warnings have been reported.  For
6411 most compilers, though, warnings do not affect this macro's outcome
6412 unless @code{AC_LANG_WERROR} is also specified.
6414 This macro caches its results in @code{ac_cv_have_decl_@var{symbol}}
6415 variables, with characters not suitable for a variable name mapped to
6416 underscores.
6417 @end defmac
6419 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6420 @acindex{CHECK_DECLS_ONCE}
6421 @cvindex HAVE_DECL_@var{symbol}
6422 For each of the @var{symbols} (@emph{comma}-separated list), define
6423 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6424 @var{symbol} is declared in the default include files, otherwise to
6425 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6426 generates the checking code at most once, so that @command{configure} is
6427 smaller and faster; but the checks cannot be conditionalized and are
6428 always done once, early during the @command{configure} run.
6429 @end defmac
6432 @node Structures
6433 @section Structures
6434 @cindex Structure, checking
6436 The following macros check for the presence of certain members in C
6437 structures.  If there is no macro specifically defined to check for a
6438 member you need, then you can use the general structure-member macros
6439 (@pxref{Generic Structures}) or, for more complex tests, you may use
6440 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6442 @menu
6443 * Particular Structures::       Macros to check for certain structure members
6444 * Generic Structures::          How to find other structure members
6445 @end menu
6447 @node Particular Structures
6448 @subsection Particular Structure Checks
6450 The following macros check for certain structures or structure members.
6452 @defmac AC_STRUCT_DIRENT_D_INO
6453 @acindex{STRUCT_DIRENT_D_INO}
6454 @cvindex HAVE_STRUCT_DIRENT_D_INO
6455 @c @caindex header_dirent_dirent_h
6456 @c @caindex member_struct_dirent_d_ino
6457 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6458 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6459 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6461 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6462 @code{d_ino}, not whether its contents are always reliable.
6463 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6464 though current systems hide this detail from the user and never return
6465 zero @code{d_ino} values.
6466 Many current systems report an incorrect @code{d_ino} for a directory
6467 entry that is a mount point.
6468 @end defmac
6470 @defmac AC_STRUCT_DIRENT_D_TYPE
6471 @acindex{STRUCT_DIRENT_D_TYPE}
6472 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6473 @c @caindex header_dirent_dirent_h
6474 @c @caindex member_struct_dirent_d_type
6475 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6476 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6477 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6478 @end defmac
6480 @anchor{AC_STRUCT_ST_BLOCKS}
6481 @defmac AC_STRUCT_ST_BLOCKS
6482 @acindex{STRUCT_ST_BLOCKS}
6483 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6484 @cvindex HAVE_ST_BLOCKS
6485 @ovindex LIBOBJS
6486 @caindex member_struct_stat_st_blocks
6487 If @code{struct stat} contains an @code{st_blocks} member, define
6488 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6489 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6490 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6491 future.
6493 This macro caches its result in the @code{ac_cv_member_struct_stat_st_blocks}
6494 variable.
6495 @end defmac
6497 @defmac AC_STRUCT_TM
6498 @acindex{STRUCT_TM}
6499 @cvindex TM_IN_SYS_TIME
6500 @hdrindex{time.h}
6501 @hdrindex{sys/time.h}
6502 If @file{time.h} does not define @code{struct tm}, define
6503 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6504 had better define @code{struct tm}.
6506 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6507 current systems.  New programs need not use this macro.
6508 @end defmac
6510 @anchor{AC_STRUCT_TIMEZONE}
6511 @defmac AC_STRUCT_TIMEZONE
6512 @acindex{STRUCT_TIMEZONE}
6513 @cvindex HAVE_DECL_TZNAME
6514 @cvindex HAVE_STRUCT_TM_TM_ZONE
6515 @cvindex HAVE_TM_ZONE
6516 @cvindex HAVE_TZNAME
6517 @c @caindex member_struct_tm_tm_zone
6518 @c @caindex struct_tm
6519 Figure out how to get the current timezone.  If @code{struct tm} has a
6520 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6521 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6522 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6523 define @code{HAVE_DECL_TZNAME}.
6524 @end defmac
6526 @node Generic Structures
6527 @subsection Generic Structure Checks
6529 These macros are used to find structure members not covered by the
6530 ``particular'' test macros.
6532 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6533   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6534   @dvar{includes, AC_INCLUDES_DEFAULT})
6535 @acindex{CHECK_MEMBER}
6536 @caindex member_@var{aggregate}_@var{member}
6537 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6538 If no @var{includes} are specified, the default includes are used
6539 (@pxref{Default Includes}).
6541 @example
6542 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6543                 [AC_MSG_ERROR([we need 'passwd.pw_gecos'])],
6544                 [[#include <pwd.h>]])
6545 @end example
6547 You can use this macro for submembers:
6549 @example
6550 AC_CHECK_MEMBER(struct top.middle.bot)
6551 @end example
6553 This macro caches its result in the
6554 @code{ac_cv_member_@var{aggregate}_@var{member}} variable, with
6555 characters not suitable for a variable name mapped to underscores.
6556 @end defmac
6558 @anchor{AC_CHECK_MEMBERS}
6559 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6560   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6561 @acindex{CHECK_MEMBERS}
6562 @cvindex HAVE_@var{aggregate}_@var{member}
6563 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6564 @var{members} using the previous macro.  When @var{member} belongs to
6565 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6566 capitals, with spaces and dots replaced by underscores).  If
6567 @var{action-if-found} is given, it is executed for each of the found
6568 members.  If @var{action-if-not-found} is given, it is executed for each
6569 of the members that could not be found.
6571 @var{includes} is a series of include directives, defaulting to
6572 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6573 prior to the members under test.
6575 This macro uses M4 lists:
6576 @example
6577 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6578 @end example
6579 @end defmac
6582 @node Types
6583 @section Types
6584 @cindex Types
6585 @cindex C types
6587 The following macros check for C types, either builtin or typedefs.  If
6588 there is no macro specifically defined to check for a type you need, and
6589 you don't need to check for any special properties of it, then you can
6590 use a general type-check macro.
6592 @menu
6593 * Particular Types::            Special handling to find certain types
6594 * Generic Types::               How to find other types
6595 @end menu
6597 @node Particular Types
6598 @subsection Particular Type Checks
6600 @hdrindex{sys/types.h}
6601 @hdrindex{stdlib.h}
6602 @hdrindex{stdint.h}
6603 @hdrindex{inttypes.h}
6604 These macros check for particular C types in @file{sys/types.h},
6605 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6606 exist.
6608 The Gnulib @code{stdint} module is an alternate way to define many of
6609 these symbols; it is useful if you prefer your code to assume a
6610 C99-or-better environment.  @xref{Gnulib}.
6612 @anchor{AC_TYPE_GETGROUPS}
6613 @defmac AC_TYPE_GETGROUPS
6614 @acindex{TYPE_GETGROUPS}
6615 @cvindex GETGROUPS_T
6616 @caindex type_getgroups
6617 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6618 is the base type of the array argument to @code{getgroups}.
6620 This macro caches the base type in the @code{ac_cv_type_getgroups}
6621 variable.
6622 @end defmac
6624 @defmac AC_TYPE_INT8_T
6625 @acindex{TYPE_INT8_T}
6626 @cvindex HAVE_INT8_T
6627 @cvindex int8_t
6628 @caindex c_int8_t
6629 If @file{stdint.h} or @file{inttypes.h} does not define the type
6630 @code{int8_t}, define @code{int8_t} to a signed
6631 integer type that is exactly 8 bits wide and that uses two's complement
6632 representation, if such a type exists.
6633 If you are worried about porting to hosts that lack such a type, you can
6634 use the results of this macro in C89-or-later code as follows:
6636 @example
6637 #if HAVE_STDINT_H
6638 # include <stdint.h>
6639 #endif
6640 #if defined INT8_MAX || defined int8_t
6641  @emph{code using int8_t}
6642 #else
6643  @emph{complicated alternative using >8-bit 'signed char'}
6644 #endif
6645 @end example
6647 This macro caches the type in the @code{ac_cv_c_int8_t} variable.
6648 @end defmac
6650 @defmac AC_TYPE_INT16_T
6651 @acindex{TYPE_INT16_T}
6652 @cvindex HAVE_INT16_T
6653 @cvindex int16_t
6654 @caindex c_int16_t
6655 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6656 @end defmac
6658 @defmac AC_TYPE_INT32_T
6659 @acindex{TYPE_INT32_T}
6660 @cvindex HAVE_INT32_T
6661 @cvindex int32_t
6662 @caindex c_int32_t
6663 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6664 @end defmac
6666 @defmac AC_TYPE_INT64_T
6667 @acindex{TYPE_INT64_T}
6668 @cvindex HAVE_INT64_T
6669 @cvindex int64_t
6670 @caindex c_int64_t
6671 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6672 @end defmac
6674 @defmac AC_TYPE_INTMAX_T
6675 @acindex{TYPE_INTMAX_T}
6676 @cvindex HAVE_INTMAX_T
6677 @cvindex intmax_t
6678 @c @caindex type_intmax_t
6679 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6680 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6681 widest signed integer type.
6682 @end defmac
6684 @defmac AC_TYPE_INTPTR_T
6685 @acindex{TYPE_INTPTR_T}
6686 @cvindex HAVE_INTPTR_T
6687 @cvindex intptr_t
6688 @c @caindex type_intptr_t
6689 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6690 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6691 signed integer type wide enough to hold a pointer, if such a type
6692 exists.
6693 @end defmac
6695 @defmac AC_TYPE_LONG_DOUBLE
6696 @acindex{TYPE_LONG_DOUBLE}
6697 @cvindex HAVE_LONG_DOUBLE
6698 @caindex type_long_double
6699 If the C compiler supports a working @code{long double} type, define
6700 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6701 same range and precision as @code{double}.
6703 This macro caches its result in the @code{ac_cv_type_long_double}
6704 variable.
6706 This macro is obsolescent, as current C compilers support @code{long
6707 double}.  New programs need not use this macro.
6708 @end defmac
6710 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6711 @acindex{TYPE_LONG_DOUBLE_WIDER}
6712 @cvindex HAVE_LONG_DOUBLE_WIDER
6713 @caindex type_long_double_wider
6714 If the C compiler supports a working @code{long double} type with more
6715 range or precision than the @code{double} type, define
6716 @code{HAVE_LONG_DOUBLE_WIDER}.
6718 This macro caches its result in the @code{ac_cv_type_long_double_wider}
6719 variable.
6720 @end defmac
6722 @defmac AC_TYPE_LONG_LONG_INT
6723 @acindex{TYPE_LONG_LONG_INT}
6724 @cvindex HAVE_LONG_LONG_INT
6725 @caindex type_long_long_int
6726 If the C compiler supports a working @code{long long int} type, define
6727 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6728 @code{long long int} values in preprocessor @code{#if} expressions,
6729 because too many compilers mishandle such expressions.
6730 @xref{Preprocessor Arithmetic}.
6732 This macro caches its result in the @code{ac_cv_type_long_long_int}
6733 variable.
6734 @end defmac
6736 @defmac AC_TYPE_MBSTATE_T
6737 @acindex{TYPE_MBSTATE_T}
6738 @cvindex mbstate_t
6739 @hdrindex{wchar.h}
6740 @caindex type_mbstate_t
6741 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6742 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6743 @code{<wchar.h>} does not declare it.
6745 This macro caches its result in the @code{ac_cv_type_mbstate_t}
6746 variable.
6747 @end defmac
6749 @anchor{AC_TYPE_MODE_T}
6750 @defmac AC_TYPE_MODE_T
6751 @acindex{TYPE_MODE_T}
6752 @cvindex mode_t
6753 @caindex type_mode_t
6754 Define @code{mode_t} to a suitable type, if standard headers do not
6755 define it.
6757 This macro caches its result in the @code{ac_cv_type_mode_t} variable.
6758 @end defmac
6760 @anchor{AC_TYPE_OFF_T}
6761 @defmac AC_TYPE_OFF_T
6762 @acindex{TYPE_OFF_T}
6763 @cvindex off_t
6764 @caindex type_off_t
6765 Define @code{off_t} to a suitable type, if standard headers do not
6766 define it.
6768 This macro caches its result in the @code{ac_cv_type_off_t} variable.
6769 @end defmac
6771 @anchor{AC_TYPE_PID_T}
6772 @defmac AC_TYPE_PID_T
6773 @acindex{TYPE_PID_T}
6774 @cvindex pid_t
6775 @caindex type_pid_t
6776 Define @code{pid_t} to a suitable type, if standard headers do not
6777 define it.
6779 This macro caches its result in the @code{ac_cv_type_pid_t} variable.
6780 @end defmac
6782 @anchor{AC_TYPE_SIZE_T}
6783 @defmac AC_TYPE_SIZE_T
6784 @acindex{TYPE_SIZE_T}
6785 @cvindex size_t
6786 @caindex type_size_t
6787 Define @code{size_t} to a suitable type, if standard headers do not
6788 define it.
6790 This macro caches its result in the @code{ac_cv_type_size_t} variable.
6791 @end defmac
6793 @defmac AC_TYPE_SSIZE_T
6794 @acindex{TYPE_SSIZE_T}
6795 @cvindex ssize_t
6796 @caindex type_ssize_t
6797 Define @code{ssize_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_ssize_t} variable.
6801 @end defmac
6803 @anchor{AC_TYPE_UID_T}
6804 @defmac AC_TYPE_UID_T
6805 @acindex{TYPE_UID_T}
6806 @cvindex uid_t
6807 @cvindex gid_t
6808 @caindex type_uid_t
6809 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6810 headers do not define them.
6812 This macro caches its result in the @code{ac_cv_type_uid_t} variable.
6813 @end defmac
6815 @defmac AC_TYPE_UINT8_T
6816 @acindex{TYPE_UINT8_T}
6817 @cvindex HAVE_UINT8_T
6818 @cvindex uint8_t
6819 @caindex c_uint8_t
6820 If @file{stdint.h} or @file{inttypes.h} does not define the type
6821 @code{uint8_t}, define @code{uint8_t} to an
6822 unsigned integer type that is exactly 8 bits wide, if such a type
6823 exists.
6824 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6825 @end defmac
6827 @defmac AC_TYPE_UINT16_T
6828 @acindex{TYPE_UINT16_T}
6829 @cvindex HAVE_UINT16_T
6830 @cvindex uint16_t
6831 @caindex c_uint16_t
6832 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6833 @end defmac
6835 @defmac AC_TYPE_UINT32_T
6836 @acindex{TYPE_UINT32_T}
6837 @cvindex HAVE_UINT32_T
6838 @cvindex uint32_t
6839 @caindex c_uint32_t
6840 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6841 @end defmac
6843 @defmac AC_TYPE_UINT64_T
6844 @acindex{TYPE_UINT64_T}
6845 @cvindex HAVE_UINT64_T
6846 @cvindex uint64_t
6847 @caindex c_uint64_t
6848 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6849 @end defmac
6851 @defmac AC_TYPE_UINTMAX_T
6852 @acindex{TYPE_UINTMAX_T}
6853 @cvindex HAVE_UINTMAX_T
6854 @cvindex uintmax_t
6855 @c @caindex type_uintmax_t
6856 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6857 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6858 widest unsigned integer type.
6859 @end defmac
6861 @defmac AC_TYPE_UINTPTR_T
6862 @acindex{TYPE_UINTPTR_T}
6863 @cvindex HAVE_UINTPTR_T
6864 @cvindex uintptr_t
6865 @c @caindex type_uintptr_t
6866 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6867 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6868 unsigned integer type wide enough to hold a pointer, if such a type
6869 exists.
6870 @end defmac
6872 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6873 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6874 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6875 @caindex type_unsigned_long_long_int
6876 If the C compiler supports a working @code{unsigned long long int} type,
6877 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6878 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6879 because too many compilers mishandle such expressions.
6880 @xref{Preprocessor Arithmetic}.
6882 This macro caches its result in the @code{ac_cv_type_unsigned_long_long_int}
6883 variable.
6884 @end defmac
6886 @node Generic Types
6887 @subsection Generic Type Checks
6889 These macros are used to check for types not covered by the ``particular''
6890 test macros.
6892 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6893   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6894 @acindex{CHECK_TYPE}
6895 @caindex type_@var{type}
6896 Check whether @var{type} is defined.  It may be a compiler builtin type
6897 or defined by the @var{includes}.  @var{includes} is a series of include
6898 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6899 Includes}), which are used prior to the type under test.
6901 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6902 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6903 same test is applied when compiling for C++, which means that in C++
6904 @var{type} should be a type-id and should not be an anonymous
6905 @samp{struct} or @samp{union}.
6907 This macro caches its result in the @code{ac_cv_type_@var{type}}
6908 variable, with @samp{*} mapped to @samp{p} and other characters not
6909 suitable for a variable name mapped to underscores.
6910 @end defmac
6913 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6914   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6915 @acindex{CHECK_TYPES}
6916 @cvindex HAVE_@var{type}
6917 For each @var{type} of the @var{types} that is defined, define
6918 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6919 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6920 specified, the default includes are used (@pxref{Default Includes}).  If
6921 @var{action-if-found} is given, it is additional shell code to execute
6922 when one of the types is found.  If @var{action-if-not-found} is given,
6923 it is executed when one of the types is not found.
6925 This macro uses M4 lists:
6926 @example
6927 AC_CHECK_TYPES([ptrdiff_t])
6928 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6929 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6930 @end example
6932 @end defmac
6934 Autoconf, up to 2.13, used to provide to another version of
6935 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6936 compatibility, a simple heuristic, quite safe but not totally, is
6937 implemented.  In case of doubt, read the documentation of the former
6938 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6941 @node Compilers and Preprocessors
6942 @section Compilers and Preprocessors
6943 @cindex Compilers
6944 @cindex Preprocessors
6946 @ovindex EXEEXT
6947 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6948 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6949 the output of the compiler, typically to the empty string if
6950 Posix and @samp{.exe} if a DOS variant.
6952 @ovindex OBJEXT
6953 They also define the output variable @code{OBJEXT} based on the
6954 output of the compiler, after @file{.c} files have been excluded, typically
6955 to @samp{o} if Posix, @samp{obj} if a DOS variant.
6957 If the compiler being used does not produce executables, the tests fail.  If
6958 the executables can't be run, and cross-compilation is not enabled, they
6959 fail too.  @xref{Manual Configuration}, for more on support for cross
6960 compiling.
6962 @menu
6963 * Specific Compiler Characteristics::  Some portability issues
6964 * Generic Compiler Characteristics::  Language independent tests and features
6965 * C Compiler::                  Checking its characteristics
6966 * C++ Compiler::                Likewise
6967 * Objective C Compiler::        Likewise
6968 * Objective C++ Compiler::      Likewise
6969 * Erlang Compiler and Interpreter::  Likewise
6970 * Fortran Compiler::            Likewise
6971 * Go Compiler::                 Likewise
6972 @end menu
6974 @node Specific Compiler Characteristics
6975 @subsection Specific Compiler Characteristics
6977 Some compilers exhibit different behaviors.
6979 @table @asis
6980 @item Static/Dynamic Expressions
6981 Autoconf relies on a trick to extract one bit of information from the C
6982 compiler: using negative array sizes.  For instance the following
6983 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6984 bytes wide:
6986 @example
6987 static int test_array[sizeof (int) == 4 ? 1 : -1];
6988 @end example
6990 @noindent
6991 To our knowledge, there is a single compiler that does not support this
6992 trick: the HP C compilers (the real ones, not only the
6993 ``bundled'') on HP-UX 11.00.
6994 They incorrectly reject the above program with the diagnostic
6995 ``Variable-length arrays cannot have static storage.''
6996 This bug comes from HP compilers' mishandling of @code{sizeof (int)},
6997 not from the @code{? 1 : -1}, and
6998 Autoconf works around this problem by casting @code{sizeof (int)} to
6999 @code{long int} before comparing it.
7000 @end table
7002 @node Generic Compiler Characteristics
7003 @subsection Generic Compiler Characteristics
7005 @anchor{AC_CHECK_SIZEOF}
7006 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
7007   @dvar{includes, AC_INCLUDES_DEFAULT})
7008 @acindex{CHECK_SIZEOF}
7009 @cvindex SIZEOF_@var{type-or-expr}
7010 @caindex sizeof_@var{type-or-expr}
7011 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
7012 the size in bytes of @var{type-or-expr}, which may be either a type or
7013 an expression returning a value that has a size.  If the expression
7014 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
7015 @var{includes} is a series of include directives, defaulting to
7016 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
7017 prior to the expression under test.
7019 This macro now works even when cross-compiling.  The @var{unused}
7020 argument was used when cross-compiling.
7022 For example, the call
7024 @example
7025 @c If you change this example, adjust tests/semantics.at:AC_CHECK_SIZEOF struct.
7026 AC_CHECK_SIZEOF([int *])
7027 @end example
7029 @noindent
7030 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
7032 This macro caches its result in the @code{ac_cv_sizeof_@var{type-or-expr}}
7033 variable, with @samp{*} mapped to @samp{p} and other characters not
7034 suitable for a variable name mapped to underscores.
7035 @end defmac
7037 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
7038 @acindex{CHECK_ALIGNOF}
7039 @cvindex ALIGNOF_@var{type}
7040 @caindex alignof_@var{type-or-expr}
7041 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
7042 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
7043 a structure member declaration.  If @samp{type} is unknown, the result
7044 is 0.  If no @var{includes} are specified, the default includes are used
7045 (@pxref{Default Includes}).
7047 This macro caches its result in the @code{ac_cv_alignof_@var{type-or-expr}}
7048 variable, with @samp{*} mapped to @samp{p} and other characters not
7049 suitable for a variable name mapped to underscores.
7050 @end defmac
7052 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
7053   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
7054 @acindex{COMPUTE_INT}
7055 Store into the shell variable @var{var} the value of the integer
7056 @var{expression}.  The
7057 value should fit in an initializer in a C variable of type @code{signed
7058 long}.  To support cross compilation (in which case, the macro only works on
7059 hosts that use twos-complement arithmetic), it should be possible to evaluate
7060 the expression at compile-time.  If no @var{includes} are specified, the
7061 default includes are used (@pxref{Default Includes}).
7063 Execute @var{action-if-fails} if the value cannot be determined correctly.
7064 @end defmac
7066 @defmac AC_LANG_WERROR
7067 @acindex{LANG_WERROR}
7068 Normally Autoconf ignores warnings generated by the compiler, linker, and
7069 preprocessor.  If this macro is used, warnings count as fatal
7070 errors for the current language.  This macro is useful when the
7071 results of configuration are used where warnings are unacceptable; for
7072 instance, if parts of a program are built with the GCC
7073 @option{-Werror}
7074 option.  If the whole program is built using @option{-Werror} it is
7075 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
7076 etc.).
7077 @end defmac
7079 @defmac AC_OPENMP
7080 @acindex{OPENMP}
7081 @cvindex _OPENMP
7082 @ovindex OPENMP_CFLAGS
7083 @ovindex OPENMP_CXXFLAGS
7084 @ovindex OPENMP_FFLAGS
7085 @ovindex OPENMP_FCFLAGS
7086 @caindex prog_c_openmp
7087 @caindex prog_cxx_openmp
7088 @caindex prog_f77_openmp
7089 @caindex prog_fc_openmp
7090 @uref{http://@/www.openmp.org/, OpenMP} specifies extensions of C, C++,
7091 and Fortran that simplify optimization of shared memory parallelism,
7092 which is a common problem on multicore CPUs.
7094 If the current language is C, the macro @code{AC_OPENMP} sets the
7095 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
7096 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
7097 compiler already supports OpenMP, if it has no way to activate OpenMP
7098 support, or if the user rejects OpenMP support by invoking
7099 @samp{configure} with the @samp{--disable-openmp} option.
7101 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
7102 preprocessing program source, and when linking programs.  Therefore you
7103 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
7104 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
7105 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
7106 OpenMP support is revealed at compile time by the preprocessor macro
7107 @code{_OPENMP}.
7109 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
7110 shared library to the program's dependencies, so its use is recommended
7111 only on programs that actually require OpenMP.
7113 If the current language is C++, @code{AC_OPENMP} sets the variable
7114 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
7115 hold as for C.
7117 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
7118 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
7119 respectively.  Similar remarks as for C hold, except that
7120 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
7121 signals OpenMP support.
7123 For portability, it is best to avoid spaces between @samp{#} and
7124 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
7125 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
7126 latter.
7128 This macro caches its result in the @code{ac_cv_prog_c_openmp},
7129 @code{ac_cv_prog_cxx_openmp}, @code{ac_cv_prog_f77_openmp}, or
7130 @code{ac_cv_prog_fc_openmp} variable, depending on the current language.
7131 @end defmac
7133 @node C Compiler
7134 @subsection C Compiler Characteristics
7136 The following macros provide ways to find and exercise a C Compiler.
7137 There are a few constructs that ought to be avoided, but do not deserve
7138 being checked for, since they can easily be worked around.
7140 @table @asis
7141 @item Don't use lines containing solitary backslashes
7142 They tickle a bug in the HP-UX C compiler (checked on
7143 HP-UX 10.20,
7144 11.00, and 11i).  When given the following source:
7146 @example
7147 #ifdef __STDC__
7149 * A comment with backslash-newlines in it.  %@{ %@} *\
7152 char str[] = "\\
7153 " A string with backslash-newlines in it %@{ %@} \\
7155 char apostrophe = '\\
7159 #endif
7160 @end example
7162 @noindent
7163 the compiler incorrectly fails with the diagnostics ``Non-terminating
7164 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
7165 Removing the lines with solitary backslashes solves the problem.
7167 @item Don't compile several files at once if output matters to you
7168 Some compilers, such as HP's, report names of files being
7169 compiled when given more than one file operand.  For instance:
7171 @example
7172 $ @kbd{cc a.c b.c}
7173 a.c:
7174 b.c:
7175 @end example
7177 @noindent
7178 This can cause problems if you observe the output of the compiler to
7179 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
7180 b.o} solves the issue.
7182 @item Don't rely on @code{#error} failing
7183 The IRIX C compiler does not fail when #error is preprocessed; it
7184 simply emits a diagnostic and continues, exiting successfully.  So,
7185 instead of an error directive like @code{#error "Unsupported word size"}
7186 it is more portable to use an invalid directive like @code{#Unsupported
7187 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
7188 OK, since installers with inadequate compilers like IRIX can simply
7189 examine these compilers' diagnostic output.
7191 @item Don't rely on correct @code{#line} support
7192 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
7193 diagnoses @code{#line} directives whose line
7194 numbers are greater than 32767.  Nothing in Posix
7195 makes this invalid.  That is why Autoconf stopped issuing
7196 @code{#line} directives.
7197 @end table
7199 @anchor{AC_PROG_CC}
7200 @defmac AC_PROG_CC (@ovar{compiler-search-list})
7201 @acindex{PROG_CC}
7202 @evindex CC
7203 @evindex CFLAGS
7204 @ovindex CC
7205 @ovindex CFLAGS
7206 @caindex prog_cc_stdc
7207 Determine a C compiler to use.  If @code{CC} is not already set in the
7208 environment, check for @code{gcc} and @code{cc}, then for other C
7209 compilers.  Set output variable @code{CC} to the name of the compiler
7210 found.
7212 This macro may, however, be invoked with an optional first argument
7213 which, if specified, must be a blank-separated list of C compilers to
7214 search for.  This just gives the user an opportunity to specify an
7215 alternative search list for the C compiler.  For example, if you didn't
7216 like the default order, then you could invoke @code{AC_PROG_CC} like
7217 this:
7219 @example
7220 AC_PROG_CC([gcc cl cc])
7221 @end example
7223 If necessary, add an option to output variable @code{CC} to enable
7224 support for ISO Standard C features with extensions.  Prefer the newest
7225 C standard that is supported.  Currently the newest standard is ISO C11,
7226 with ISO C99 and ANSI C89 (ISO C90) being the older versions.
7227 After calling this macro you can check whether the C compiler has been
7228 set to accept Standard C; if not, the shell variable
7229 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
7231 When attempting to add compiler options, prefer extended functionality
7232 to strict conformance: the goal is to enable whatever standard features
7233 that are available, not to check for full conformance to the standard or
7234 to prohibit incompatible extensions.  Test for C11 support by checking
7235 for @code{_Alignas}, @code{_Alignof}, @code{_Noreturn},
7236 @code{_Static_assert}, UTF-8 string literals, duplicate @code{typedef}s,
7237 and anonymous structures and unions.  Test for C99 support by checking
7238 for @code{_Bool}, @code{//} comments, flexible array members,
7239 @code{inline}, signed and unsigned @code{long long int}, mixed code and
7240 declarations, named initialization of structs, @code{restrict},
7241 @code{va_copy}, varargs macros, variable declarations in @code{for}
7242 loops, and variable length arrays.  Test for C89 support by checking for
7243 function prototypes.
7245 If using a compiler that supports GNU C, set shell variable @code{GCC} to
7246 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
7247 it to @option{-g -O2} for a GNU C compiler (@option{-O2} on systems
7248 where the compiler does not accept @option{-g}), or @option{-g} for
7249 other compilers.  If your package does not like this default, then it is
7250 acceptable to insert the line @samp{: $@{CFLAGS=""@}} after @code{AC_INIT}
7251 and before @code{AC_PROG_CC} to select an empty default instead.
7253 Many Autoconf macros use a compiler, and thus call
7254 @samp{AC_REQUIRE([AC_PROG_CC])} to ensure that the compiler has been
7255 determined before the body of the outermost @code{AC_DEFUN} macro.
7256 @code{AC_PROG_CC} is therefore defined via @code{AC_DEFUN_ONCE} to avoid
7257 needless reexpansion (@pxref{One-Shot Macros}).
7258 @end defmac
7260 @anchor{AC_PROG_CC_C_O}
7261 @defmac AC_PROG_CC_C_O
7262 @acindex{PROG_CC_C_O}
7263 @cvindex NO_MINUS_C_MINUS_O
7264 @caindex prog_cc_@var{compiler}_c_o
7265 If the C compiler does not accept the @option{-c} and @option{-o} options
7266 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
7267 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
7268 the first @code{cc} in the path.  The test fails if one fails.  This
7269 macro was created for GNU Make to choose the default C compilation
7270 rule.
7272 For the compiler @var{compiler}, this macro caches its result in the
7273 @code{ac_cv_prog_cc_@var{compiler}_c_o} variable.
7274 @end defmac
7277 @defmac AC_PROG_CPP
7278 @acindex{PROG_CPP}
7279 @evindex CPP
7280 @ovindex CPP
7281 Set output variable @code{CPP} to a command that runs the
7282 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
7283 It is only portable to run @code{CPP} on files with a @file{.c}
7284 extension.
7286 Some preprocessors don't indicate missing include files by the error
7287 status.  For such preprocessors an internal variable is set that causes
7288 other macros to check the standard error from the preprocessor and
7289 consider the test failed if any warnings have been reported.
7290 For most preprocessors, though, warnings do not cause include-file
7291 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
7292 @end defmac
7294 @defmac AC_PROG_CPP_WERROR
7295 @acindex{PROG_CPP_WERROR}
7296 @ovindex CPP
7297 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
7298 preprocessor as errors even if the preprocessor exit status indicates
7299 success.  This is useful for avoiding headers that generate mandatory
7300 warnings, such as deprecation notices.
7301 @end defmac
7304 The following macros check for C compiler or machine architecture
7305 features.  To check for characteristics not listed here, use
7306 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7307 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
7309 @defmac AC_C_BACKSLASH_A
7310 @acindex{C_BACKSLASH_A}
7311 @cvindex HAVE_C_BACKSLASH_A
7312 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
7313 @samp{\a}.
7315 This macro is obsolescent, as current C compilers understand @samp{\a}.
7316 New programs need not use this macro.
7317 @end defmac
7319 @anchor{AC_C_BIGENDIAN}
7320 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
7321   @ovar{action-if-unknown}, @ovar{action-if-universal})
7322 @acindex{C_BIGENDIAN}
7323 @cvindex WORDS_BIGENDIAN
7324 @cindex Endianness
7325 If words are stored with the most significant byte first (like Motorola
7326 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
7327 the least significant byte first (like Intel and VAX CPUs), execute
7328 @var{action-if-false}.
7330 This macro runs a test-case if endianness cannot be determined from the
7331 system header files.  When cross-compiling, the test-case is not run but
7332 grep'ed for some magic values.  @var{action-if-unknown} is executed if
7333 the latter case fails to determine the byte sex of the host system.
7335 In some cases a single run of a compiler can generate code for multiple
7336 architectures.  This can happen, for example, when generating Mac OS X
7337 universal binary files, which work on both PowerPC and Intel
7338 architectures.  In this case, the different variants might be for
7339 different architectures whose endiannesses differ.  If
7340 @command{configure} detects this, it executes @var{action-if-universal}
7341 instead of @var{action-if-unknown}.
7343 The default for @var{action-if-true} is to define
7344 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
7345 nothing.  The default for @var{action-if-unknown} is to
7346 abort configure and tell the installer how to bypass this test.
7347 And finally, the default for @var{action-if-universal} is to ensure that
7348 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
7349 detected and the current code is big-endian; this default works only if
7350 @command{autoheader} is used (@pxref{autoheader Invocation}).
7352 If you use this macro without specifying @var{action-if-universal}, you
7353 should also use @code{AC_CONFIG_HEADERS}; otherwise
7354 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
7355 binary files.
7356 @end defmac
7358 @anchor{AC_C_CONST}
7359 @defmac AC_C_CONST
7360 @acindex{C_CONST}
7361 @cvindex const
7362 @caindex c_const
7363 If the C compiler does not fully support the @code{const} keyword,
7364 define @code{const} to be empty.  Some C compilers that do
7365 not define @code{__STDC__} do support @code{const}; some compilers that
7366 define @code{__STDC__} do not completely support @code{const}.  Programs
7367 can simply use @code{const} as if every C compiler supported it; for
7368 those that don't, the makefile or configuration header file
7369 defines it as empty.
7371 Occasionally installers use a C++ compiler to compile C code, typically
7372 because they lack a C compiler.  This causes problems with @code{const},
7373 because C and C++ treat @code{const} differently.  For example:
7375 @example
7376 const int foo;
7377 @end example
7379 @noindent
7380 is valid in C but not in C++.  These differences unfortunately cannot be
7381 papered over by defining @code{const} to be empty.
7383 If @command{autoconf} detects this situation, it leaves @code{const} alone,
7384 as this generally yields better results in practice.  However, using a
7385 C++ compiler to compile C code is not recommended or supported, and
7386 installers who run into trouble in this area should get a C compiler
7387 like GCC to compile their C code.
7389 This macro caches its result in the @code{ac_cv_c_const} variable.
7391 This macro is obsolescent, as current C compilers support @code{const}.
7392 New programs need not use this macro.
7393 @end defmac
7395 @defmac AC_C__GENERIC
7396 @acindex{C__GENERIC}
7397 @cvindex _Generic
7398 If the C compiler supports C11-style generic selection using the
7399 @code{_Generic} keyword, define @code{HAVE_C__GENERIC}.
7400 @end defmac
7402 @defmac AC_C_RESTRICT
7403 @acindex{C_RESTRICT}
7404 @cvindex restrict
7405 @caindex c_restrict
7406 If the C compiler recognizes a variant spelling for the @code{restrict}
7407 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
7408 then define @code{restrict} to that; this is more likely to do the right
7409 thing with compilers that support language variants where plain
7410 @code{restrict} is not a keyword.  Otherwise, if the C compiler
7411 recognizes the @code{restrict} keyword, don't do anything.
7412 Otherwise, define @code{restrict} to be empty.
7413 Thus, programs may simply use @code{restrict} as if every C compiler
7414 supported it; for those that do not, the makefile
7415 or configuration header defines it away.
7417 Although support in C++ for the @code{restrict} keyword is not
7418 required, several C++ compilers do accept the keyword.
7419 This macro works for them, too.
7421 This macro caches @samp{no} in the @code{ac_cv_c_restrict} variable
7422 if @code{restrict} is not supported, and a supported spelling otherwise.
7423 @end defmac
7425 @defmac AC_C_VOLATILE
7426 @acindex{C_VOLATILE}
7427 @cvindex volatile
7428 If the C compiler does not understand the keyword @code{volatile},
7429 define @code{volatile} to be empty.  Programs can simply use
7430 @code{volatile} as if every C compiler supported it; for those that do
7431 not, the makefile or configuration header defines it as
7432 empty.
7434 If the correctness of your program depends on the semantics of
7435 @code{volatile}, simply defining it to be empty does, in a sense, break
7436 your code.  However, given that the compiler does not support
7437 @code{volatile}, you are at its mercy anyway.  At least your
7438 program compiles, when it wouldn't before.
7439 @xref{Volatile Objects}, for more about @code{volatile}.
7441 In general, the @code{volatile} keyword is a standard C feature, so
7442 you might expect that @code{volatile} is available only when
7443 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
7444 support volatile, but does not define @code{__STDC__}.
7446 This macro is obsolescent, as current C compilers support @code{volatile}.
7447 New programs need not use this macro.
7448 @end defmac
7450 @anchor{AC_C_INLINE}
7451 @defmac AC_C_INLINE
7452 @acindex{C_INLINE}
7453 @cvindex inline
7454 If the C compiler supports the keyword @code{inline}, do nothing.
7455 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
7456 if it accepts one of those, otherwise define @code{inline} to be empty.
7457 @end defmac
7459 @anchor{AC_C_CHAR_UNSIGNED}
7460 @defmac AC_C_CHAR_UNSIGNED
7461 @acindex{C_CHAR_UNSIGNED}
7462 @cvindex __CHAR_UNSIGNED__
7463 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
7464 unless the C compiler predefines it.
7466 These days, using this macro is not necessary.  The same information can
7467 be determined by this portable alternative, thus avoiding the use of
7468 preprocessor macros in the namespace reserved for the implementation.
7470 @example
7471 #include <limits.h>
7472 #if CHAR_MIN == 0
7473 # define CHAR_UNSIGNED 1
7474 #endif
7475 @end example
7476 @end defmac
7478 @defmac AC_C_STRINGIZE
7479 @acindex{C_STRINGIZE}
7480 @cvindex HAVE_STRINGIZE
7481 If the C preprocessor supports the stringizing operator, define
7482 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
7483 found in macros such as this:
7485 @example
7486 #define x(y) #y
7487 @end example
7489 This macro is obsolescent, as current C compilers support the
7490 stringizing operator.  New programs need not use this macro.
7491 @end defmac
7493 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7494 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7495 @cvindex FLEXIBLE_ARRAY_MEMBER
7496 If the C compiler supports flexible array members, define
7497 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7498 That way, a declaration like this:
7500 @example
7501 struct s
7502   @{
7503     size_t n_vals;
7504     double val[FLEXIBLE_ARRAY_MEMBER];
7505   @};
7506 @end example
7508 @noindent
7509 will let applications use the ``struct hack'' even with compilers that
7510 do not support flexible array members.  To allocate and use such an
7511 object, you can use code like this:
7513 @example
7514 size_t i;
7515 size_t n = compute_value_count ();
7516 struct s *p =
7517    malloc (offsetof (struct s, val)
7518            + n * sizeof (double));
7519 p->n_vals = n;
7520 for (i = 0; i < n; i++)
7521   p->val[i] = compute_value (i);
7522 @end example
7523 @end defmac
7525 @defmac AC_C_VARARRAYS
7526 @acindex{C_VARARRAYS}
7527 @cvindex __STDC_NO_VLA__
7528 @cvindex HAVE_C_VARARRAYS
7529 If the C compiler does not support variable-length arrays, define the
7530 macro @code{__STDC_NO_VLA__} to be 1 if it is not already defined.  A
7531 variable-length array is an array of automatic storage duration whose
7532 length is determined at run time, when the array is declared.  For
7533 backward compatibility this macro also defines @code{HAVE_C_VARARRAYS}
7534 if the C compiler supports variable-length arrays, but this usage is
7535 obsolescent and new programs should use @code{__STDC_NO_VLA__}.
7536 @end defmac
7538 @defmac AC_C_TYPEOF
7539 @acindex{C_TYPEOF}
7540 @cvindex HAVE_TYPEOF
7541 @cvindex typeof
7542 If the C compiler supports GNU C's @code{typeof} syntax either
7543 directly or
7544 through a different spelling of the keyword (e.g., @code{__typeof__}),
7545 define @code{HAVE_TYPEOF}.  If the support is available only through a
7546 different spelling, define @code{typeof} to that spelling.
7547 @end defmac
7549 @defmac AC_C_PROTOTYPES
7550 @acindex{C_PROTOTYPES}
7551 @cvindex PROTOTYPES
7552 @cvindex __PROTOTYPES
7553 @cvindex PARAMS
7554 If function prototypes are understood by the compiler (as determined by
7555 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7556 Defining @code{__PROTOTYPES} is for the benefit of
7557 header files that cannot use macros that infringe on user name space.
7559 This macro is obsolescent, as current C compilers support prototypes.
7560 New programs need not use this macro.
7561 @end defmac
7563 @anchor{AC_PROG_GCC_TRADITIONAL}
7564 @defmac AC_PROG_GCC_TRADITIONAL
7565 @acindex{PROG_GCC_TRADITIONAL}
7566 @ovindex CC
7567 Add @option{-traditional} to output variable @code{CC} if using a
7568 GNU C compiler and @code{ioctl} does not work properly without
7569 @option{-traditional}.  That usually happens when the fixed header files
7570 have not been installed on an old system.
7572 This macro is obsolescent, since current versions of the GNU C
7573 compiler fix the header files automatically when installed.
7574 @end defmac
7577 @node C++ Compiler
7578 @subsection C++ Compiler Characteristics
7581 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7582 @acindex{PROG_CXX}
7583 @evindex CXX
7584 @evindex CXXFLAGS
7585 @ovindex CXX
7586 @ovindex CXXFLAGS
7587 Determine a C++ compiler to use.  Check whether the environment variable
7588 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7589 variable @code{CXX} to its value.
7591 Otherwise, if the macro is invoked without an argument, then search for
7592 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7593 then other names).  If none of those checks succeed, then as a last
7594 resort set @code{CXX} to @code{g++}.
7596 This macro may, however, be invoked with an optional first argument
7597 which, if specified, must be a blank-separated list of C++ compilers to
7598 search for.  This just gives the user an opportunity to specify an
7599 alternative search list for the C++ compiler.  For example, if you
7600 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7601 like this:
7603 @example
7604 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7605 @end example
7607 If necessary, add an option to output variable @code{CXX} to enable
7608 support for ISO Standard C++ features with extensions.  Prefer the
7609 newest C++ standard that is supported.  Currently the newest standard is
7610 ISO C++11, with ISO C++98 being the previous standard.  After calling
7611 this macro you can check whether the C++ compiler has been set to accept
7612 Standard C++; if not, the shell variable @code{ac_cv_prog_cxx_stdcxx} is
7613 set to @samp{no}.  If the C++ compiler will not accept C++11, the shell
7614 variable @code{ac_cv_prog_cxx_cxx11} is set to @samp{no}, and if it will
7615 not accept C++98, the shell variable @code{ac_cv_prog_cxx_cxx98} is set
7616 to @samp{no}.
7618 When attempting to add compiler options, prefer extended functionality
7619 to strict conformance: the goal is to enable whatever standard features
7620 that are available, not to check for full conformance to the standard or
7621 to prohibit incompatible extensions.  Test for C++11 support by checking
7622 for the language features @code{auto}, @code{constexpr},
7623 @code{decltype}, @code{default}ed and @code{delete}ed constructors,
7624 delegate constructors, @code{final}, initializer lists, lambda
7625 functions, @code{nullptr}, @code{override}, range-based for loops,
7626 template brackets without spaces and unicode literals, and library
7627 features @code{std::array}, @code{std::shared_ptr},
7628 @code{std::weak_ptr}, @code{std::regex} and @code{std::tuple}.  Test for
7629 C++98 support using basic features of the @code{std} namespace including
7630 @code{std::string}, containers (@code{std::list}, @code{std::map},
7631 @code{std::set}, @code{std::vector}), streams (fstreams, iostreams,
7632 stringstreams, iomanip), @code{std::pair}, exceptions (@code{try},
7633 @code{catch} and @code{std::runtime_error}) and algorithms.  Tests for
7634 more recent standards include all the tests for older standards.
7636 If using the GNU C++ compiler, set shell variable @code{GXX} to
7637 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7638 it to @option{-g -O2} for the GNU C++ compiler (@option{-O2} on
7639 systems where G++ does not accept @option{-g}), or @option{-g} for other
7640 compilers.  If your package does not like this default, then it is
7641 acceptable to insert the line @samp{: $@{CXXFLAGS=""@}} after @code{AC_INIT}
7642 and before @code{AC_PROG_CXX} to select an empty default instead.
7643 @end defmac
7645 @defmac AC_PROG_CXXCPP
7646 @acindex{PROG_CXXCPP}
7647 @evindex CXXCPP
7648 @ovindex CXXCPP
7649 Set output variable @code{CXXCPP} to a command that runs the C++
7650 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7651 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7652 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7654 Some preprocessors don't indicate missing include files by the error
7655 status.  For such preprocessors an internal variable is set that causes
7656 other macros to check the standard error from the preprocessor and
7657 consider the test failed if any warnings have been reported.  However,
7658 it is not known whether such broken preprocessors exist for C++.
7659 @end defmac
7661 @defmac AC_PROG_CXX_C_O
7662 @acindex{PROG_CXX_C_O}
7663 @cvindex CXX_NO_MINUS_C_MINUS_O
7664 Test whether the C++ compiler accepts the options @option{-c} and
7665 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7666 if it does not.
7667 @end defmac
7670 @node Objective C Compiler
7671 @subsection Objective C Compiler Characteristics
7674 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7675 @acindex{PROG_OBJC}
7676 @evindex OBJC
7677 @evindex OBJCFLAGS
7678 @ovindex OBJC
7679 @ovindex OBJCFLAGS
7680 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7681 set in the environment, check for Objective C compilers.  Set output
7682 variable @code{OBJC} to the name of the compiler found.
7684 This macro may, however, be invoked with an optional first argument
7685 which, if specified, must be a blank-separated list of Objective C compilers to
7686 search for.  This just gives the user an opportunity to specify an
7687 alternative search list for the Objective C compiler.  For example, if you
7688 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7689 like this:
7691 @example
7692 AC_PROG_OBJC([gcc objcc objc])
7693 @end example
7695 If using a compiler that supports GNU Objective C, set shell variable
7696 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7697 already set, set it to @option{-g -O2} for a GNU Objective C
7698 compiler (@option{-O2} on systems where the compiler does not accept
7699 @option{-g}), or @option{-g} for other compilers.
7700 @end defmac
7702 @defmac AC_PROG_OBJCPP
7703 @acindex{PROG_OBJCPP}
7704 @evindex OBJCPP
7705 @ovindex OBJCPP
7706 Set output variable @code{OBJCPP} to a command that runs the Objective C
7707 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7708 @end defmac
7711 @node Objective C++ Compiler
7712 @subsection Objective C++ Compiler Characteristics
7715 @defmac AC_PROG_OBJCXX (@ovar{compiler-search-list})
7716 @acindex{PROG_OBJCXX}
7717 @evindex OBJCXX
7718 @evindex OBJCXXFLAGS
7719 @ovindex OBJCXX
7720 @ovindex OBJCXXFLAGS
7721 Determine an Objective C++ compiler to use.  If @code{OBJCXX} is not already
7722 set in the environment, check for Objective C++ compilers.  Set output
7723 variable @code{OBJCXX} to the name of the compiler found.
7725 This macro may, however, be invoked with an optional first argument
7726 which, if specified, must be a blank-separated list of Objective C++ compilers
7727 to search for.  This just gives the user an opportunity to specify an
7728 alternative search list for the Objective C++ compiler.  For example, if you
7729 didn't like the default order, then you could invoke @code{AC_PROG_OBJCXX}
7730 like this:
7732 @example
7733 AC_PROG_OBJCXX([gcc g++ objcc++ objcxx])
7734 @end example
7736 If using a compiler that supports GNU Objective C++, set shell variable
7737 @code{GOBJCXX} to @samp{yes}.  If output variable @code{OBJCXXFLAGS} was not
7738 already set, set it to @option{-g -O2} for a GNU Objective C++
7739 compiler (@option{-O2} on systems where the compiler does not accept
7740 @option{-g}), or @option{-g} for other compilers.
7741 @end defmac
7743 @defmac AC_PROG_OBJCXXCPP
7744 @acindex{PROG_OBJCXXCPP}
7745 @evindex OBJCXXCPP
7746 @ovindex OBJCXXCPP
7747 Set output variable @code{OBJCXXCPP} to a command that runs the Objective C++
7748 preprocessor.  If @samp{$OBJCXX -E} doesn't work, @file{/lib/cpp} is used.
7749 @end defmac
7752 @node Erlang Compiler and Interpreter
7753 @subsection Erlang Compiler and Interpreter Characteristics
7754 @cindex Erlang
7756 Autoconf defines the following macros for determining paths to the essential
7757 Erlang/OTP programs:
7759 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7760 @acindex{ERLANG_PATH_ERLC}
7761 @evindex ERLC
7762 @evindex ERLCFLAGS
7763 @ovindex ERLC
7764 @ovindex ERLCFLAGS
7765 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7766 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7767 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7768 is not set in the environment, set it to an empty value.
7770 The two optional arguments have the same meaning as the two last arguments of
7771 macro @code{AC_PATH_PROG} for looking for the @command{erlc} program.  For
7772 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7773 directory:
7775 @example
7776 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7777 @end example
7778 @end defmac
7780 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7781 @acindex{ERLANG_NEED_ERLC}
7782 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7783 error message and exits the @command{configure} script if the @command{erlc}
7784 program is not found.
7785 @end defmac
7787 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7788 @acindex{ERLANG_PATH_ERL}
7789 @evindex ERL
7790 @ovindex ERL
7791 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7792 set in the
7793 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7794 complete path of the interpreter command found.
7796 The two optional arguments have the same meaning as the two last arguments of
7797 macro @code{AC_PATH_PROG} for looking for the @command{erl} program.  For
7798 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7799 directory:
7801 @example
7802 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7803 @end example
7804 @end defmac
7806 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7807 @acindex{ERLANG_NEED_ERL}
7808 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7809 error message and exits the @command{configure} script if the @command{erl}
7810 program is not found.
7811 @end defmac
7814 @node Fortran Compiler
7815 @subsection Fortran Compiler Characteristics
7816 @cindex Fortran
7817 @cindex F77
7819 The Autoconf Fortran support is divided into two categories: legacy
7820 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7821 The former are intended for traditional Fortran 77 code, and have output
7822 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7823 are for newer programs that can (or must) compile under the newer
7824 Fortran standards, and have output variables like @code{FC},
7825 @code{FCFLAGS}, and @code{FCLIBS}.
7827 Except for the macros @code{AC_FC_SRCEXT}, @code{AC_FC_FREEFORM},
7828 @code{AC_FC_FIXEDFORM}, and @code{AC_FC_LINE_LENGTH} (see below), the
7829 @code{FC} and @code{F77} macros behave almost identically, and so they
7830 are documented together in this section.
7833 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7834 @acindex{PROG_F77}
7835 @evindex F77
7836 @evindex FFLAGS
7837 @ovindex F77
7838 @ovindex FFLAGS
7839 @caindex f77_compiler_gnu
7840 @caindex prog_f77_g
7841 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7842 set in the environment, then check for @code{g77} and @code{f77}, and
7843 then some other names.  Set the output variable @code{F77} to the name
7844 of the compiler found.
7846 This macro may, however, be invoked with an optional first argument
7847 which, if specified, must be a blank-separated list of Fortran 77
7848 compilers to search for.  This just gives the user an opportunity to
7849 specify an alternative search list for the Fortran 77 compiler.  For
7850 example, if you didn't like the default order, then you could invoke
7851 @code{AC_PROG_F77} like this:
7853 @example
7854 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7855 @end example
7857 If using a compiler that supports GNU Fortran 77,
7858 set the shell variable @code{G77} to @samp{yes}.
7859 If the output variable @code{FFLAGS} was not already set in the
7860 environment, set it to @option{-g -02} for @code{g77} (or @option{-O2}
7861 where the GNU Fortran 77 compiler does not accept @option{-g}), or
7862 @option{-g} for other compilers.
7864 The result of the GNU test is cached in the
7865 @code{ac_cv_f77_compiler_gnu} variable, acceptance of @option{-g} in the
7866 @code{ac_cv_prog_f77_g} variable.
7867 @end defmac
7869 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7870 @acindex{PROG_FC}
7871 @evindex FC
7872 @evindex FCFLAGS
7873 @ovindex FC
7874 @ovindex FCFLAGS
7875 @caindex fc_compiler_gnu
7876 @caindex prog_fc_g
7877 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7878 the environment, then @code{dialect} is a hint to indicate what Fortran
7879 dialect to search for; the default is to search for the newest available
7880 dialect.  Set the output variable @code{FC} to the name of the compiler
7881 found.
7883 By default, newer dialects are preferred over older dialects, but if
7884 @code{dialect} is specified then older dialects are preferred starting
7885 with the specified dialect.  @code{dialect} can currently be one of
7886 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7887 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7888 and no attempt is made to guarantee that a particular language standard
7889 is actually supported.  Thus, it is preferable that you avoid the
7890 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7891 the latest Fortran standard.
7893 This macro may, alternatively, be invoked with an optional first argument
7894 which, if specified, must be a blank-separated list of Fortran
7895 compilers to search for, just as in @code{AC_PROG_F77}.
7897 If using a compiler that supports GNU Fortran,
7898 set the shell variable @code{GFC} to @samp{yes}.
7899 If the output variable @code{FCFLAGS} was not already set in the
7900 environment, then set it to @option{-g -02} for a GNU Fortran compiler (or
7901 @option{-O2} where the compiler does not accept @option{-g}), or
7902 @option{-g} for other compilers.
7904 The result of the GNU test is cached in the @code{ac_cv_fc_compiler_gnu}
7905 variable, acceptance of @option{-g} in the @code{ac_cv_prog_fc_g}
7906 variable.
7907 @end defmac
7909 @defmac AC_PROG_F77_C_O
7910 @defmacx AC_PROG_FC_C_O
7911 @acindex{PROG_F77_C_O}
7912 @acindex{PROG_FC_C_O}
7913 @cvindex F77_NO_MINUS_C_MINUS_O
7914 @cvindex FC_NO_MINUS_C_MINUS_O
7915 @caindex prog_f77_c_o
7916 @caindex prog_fc_c_o
7917 Test whether the Fortran compiler accepts the options @option{-c} and
7918 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7919 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7921 The result of the test is cached in the @code{ac_cv_prog_f77_c_o} or
7922 @code{ac_cv_prog_fc_c_o} variable, respectively.
7923 @end defmac
7925 The following macros check for Fortran compiler characteristics.
7926 To check for characteristics not listed here, use
7927 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7928 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7929 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7930 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7933 @defmac AC_F77_LIBRARY_LDFLAGS
7934 @defmacx AC_FC_LIBRARY_LDFLAGS
7935 @acindex{F77_LIBRARY_LDFLAGS}
7936 @ovindex FLIBS
7937 @acindex{FC_LIBRARY_LDFLAGS}
7938 @ovindex FCLIBS
7939 @caindex prog_f77_v
7940 @caindex prog_fc_v
7941 @caindex f77_libs
7942 @caindex fc_libs
7943 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7944 @dfn{Fortran intrinsic and runtime libraries} that are required to
7945 successfully link a Fortran program or shared library.  The output
7946 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7947 should be included after @code{LIBS} when linking).
7949 This macro is intended to be used in those situations when it is
7950 necessary to mix, e.g., C++ and Fortran source code in a single
7951 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7952 automake, GNU Automake}).
7954 For example, if object files from a C++ and Fortran compiler must be
7955 linked together, then the C++ compiler/linker must be used for linking
7956 (since special C++-ish things need to happen at link time like calling
7957 global constructors, instantiating templates, enabling exception
7958 support, etc.).
7960 However, the Fortran intrinsic and runtime libraries must be linked in
7961 as well, but the C++ compiler/linker doesn't know by default how to add
7962 these Fortran 77 libraries.  Hence, this macro was created to determine
7963 these Fortran libraries.
7965 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7966 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7967 link C/C++ with Fortran; see below.  Further, it is highly recommended
7968 that you use @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers})
7969 because the complex defines that the function wrapper macros create
7970 may not work with C/C++ compiler drivers.
7972 These macros internally compute the flag needed to verbose linking
7973 output and cache it in @code{ac_cv_prog_f77_v} or @code{ac_cv_prog_fc_v}
7974 variables, respectively.  The computed linker flags are cached in
7975 @code{ac_cv_f77_libs} or @code{ac_cv_fc_libs}, respectively.
7976 @end defmac
7978 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @
7979   @dvar{action-if-not-found, AC_MSG_FAILURE})
7980 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @
7981   @dvar{action-if-not-found, AC_MSG_FAILURE})
7982 @acindex{F77_DUMMY_MAIN}
7983 @cvindex F77_DUMMY_MAIN
7984 @acindex{FC_DUMMY_MAIN}
7985 @cvindex FC_DUMMY_MAIN
7986 @caindex f77_dummy_main
7987 @caindex fc_dummy_main
7988 With many compilers, the Fortran libraries detected by
7989 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7990 their own @code{main} entry function that initializes things like
7991 Fortran I/O, and which then calls a user-provided entry function named
7992 (say) @code{MAIN__} to run the user's program.  The
7993 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7994 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7995 this interaction.
7997 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7998 one prefers to provide one's own @code{main} and skip the Fortran
7999 library initializations.  In this case, however, one may still need to
8000 provide a dummy @code{MAIN__} routine in order to prevent linking errors
8001 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
8002 detects whether any such routine is @emph{required} for linking, and
8003 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
8004 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
8005 was found, and @code{none} when no such dummy main is needed.
8007 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
8008 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
8009 @emph{if} it is required.  @var{action-if-not-found} defaults to
8010 exiting with an error.
8012 In order to link with Fortran routines, the user's C/C++ program should
8013 then include the following code to define the dummy main if it is
8014 needed:
8016 @example
8017 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8018 #ifdef F77_DUMMY_MAIN
8019 #  ifdef __cplusplus
8020      extern "C"
8021 #  endif
8022    int F77_DUMMY_MAIN () @{ return 1; @}
8023 #endif
8024 @end example
8026 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8028 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
8029 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
8030 explicitly unless one wants to change the default actions.
8032 The result of this macro is cached in the @code{ac_cv_f77_dummy_main} or
8033 @code{ac_cv_fc_dummy_main} variable, respectively.
8034 @end defmac
8036 @defmac AC_F77_MAIN
8037 @defmacx AC_FC_MAIN
8038 @acindex{F77_MAIN}
8039 @cvindex F77_MAIN
8040 @acindex{FC_MAIN}
8041 @cvindex FC_MAIN
8042 @caindex f77_main
8043 @caindex fc_main
8044 As discussed above, many Fortran libraries allow you to provide an entry
8045 point called (say) @code{MAIN__} instead of the usual @code{main}, which
8046 is then called by a @code{main} function in the Fortran libraries that
8047 initializes things like Fortran I/O@.  The
8048 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
8049 @emph{possible} to utilize such an alternate main function, and defines
8050 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
8051 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
8052 simply defined to @code{main}.)
8054 Thus, when calling Fortran routines from C that perform things like I/O,
8055 one should use this macro and declare the "main" function like so:
8057 @example
8058 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8059 #ifdef __cplusplus
8060   extern "C"
8061 #endif
8062 int F77_MAIN (int argc, char *argv[]);
8063 @end example
8065 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8067 The result of this macro is cached in the @code{ac_cv_f77_main} or
8068 @code{ac_cv_fc_main} variable, respectively.
8069 @end defmac
8071 @defmac AC_F77_WRAPPERS
8072 @defmacx AC_FC_WRAPPERS
8073 @acindex{F77_WRAPPERS}
8074 @cvindex F77_FUNC
8075 @cvindex F77_FUNC_
8076 @acindex{FC_WRAPPERS}
8077 @cvindex FC_FUNC
8078 @cvindex FC_FUNC_
8079 @caindex f77_mangling
8080 @caindex fc_mangling
8081 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
8082 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
8083 mangle the names of C/C++ identifiers, and identifiers with underscores,
8084 respectively, so that they match the name-mangling scheme used by the
8085 Fortran compiler.
8087 Fortran is case-insensitive, and in order to achieve this the Fortran
8088 compiler converts all identifiers into a canonical case and format.  To
8089 call a Fortran subroutine from C or to write a C function that is
8090 callable from Fortran, the C program must explicitly use identifiers in
8091 the format expected by the Fortran compiler.  In order to do this, one
8092 simply wraps all C identifiers in one of the macros provided by
8093 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
8094 you have the following Fortran 77 subroutine:
8096 @example
8097 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8098       subroutine foobar (x, y)
8099       double precision x, y
8100       y = 3.14159 * x
8101       return
8102       end
8103 @end example
8105 You would then declare its prototype in C or C++ as:
8107 @example
8108 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8109 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
8110 #ifdef __cplusplus
8111 extern "C"  /* prevent C++ name mangling */
8112 #endif
8113 void FOOBAR_F77 (double *x, double *y);
8114 @end example
8116 Note that we pass both the lowercase and uppercase versions of the
8117 function name to @code{F77_FUNC} so that it can select the right one.
8118 Note also that all parameters to Fortran 77 routines are passed as
8119 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, GNU
8120 Automake}).
8122 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
8124 Although Autoconf tries to be intelligent about detecting the
8125 name-mangling scheme of the Fortran compiler, there may be Fortran
8126 compilers that it doesn't support yet.  In this case, the above code
8127 generates a compile-time error, but some other behavior
8128 (e.g., disabling Fortran-related features) can be induced by checking
8129 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
8131 Now, to call that routine from a C program, we would do something like:
8133 @example
8134 @c If you change this example, adjust tests/fortran.at:AC_F77_DUMMY_MAIN usage.
8136     double x = 2.7183, y;
8137     FOOBAR_F77 (&x, &y);
8139 @end example
8141 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
8142 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
8143 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
8144 because some Fortran compilers mangle names differently if they contain
8145 an underscore.
8147 The name mangling scheme is encoded in the @code{ac_cv_f77_mangling} or
8148 @code{ac_cv_fc_mangling} cache variable, respectively, and also used for
8149 the @code{AC_F77_FUNC} and @code{AC_FC_FUNC} macros described below.
8150 @end defmac
8152 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
8153 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
8154 @acindex{F77_FUNC}
8155 @acindex{FC_FUNC}
8156 Given an identifier @var{name}, set the shell variable @var{shellvar} to
8157 hold the mangled version @var{name} according to the rules of the
8158 Fortran linker (see also @code{AC_F77_WRAPPERS} or
8159 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
8160 supplied, the shell variable is simply @var{name}.  The purpose of
8161 this macro is to give the caller a way to access the name-mangling
8162 information other than through the C preprocessor as above, for example,
8163 to call Fortran routines from some language other than C/C++.
8164 @end defmac
8166 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8167   @dvar{action-if-failure, AC_MSG_FAILURE})
8168 @defmacx AC_FC_PP_SRCEXT (@var{ext}, @ovar{action-if-success}, @
8169   @dvar{action-if-failure, AC_MSG_FAILURE})
8170 @acindex{FC_SRCEXT}
8171 @acindex{FC_PP_SRCEXT}
8172 @caindex fc_srcext_@var{ext}
8173 @caindex fc_pp_srcext_@var{ext}
8174 By default, the @code{FC} macros perform their tests using a @file{.f}
8175 extension for source-code files.  Some compilers, however, only enable
8176 newer language features for appropriately named files, e.g., Fortran 90
8177 features only for @file{.f90} files, or preprocessing only with
8178 @file{.F} files or maybe other upper-case extensions.  On the other
8179 hand, some other compilers expect all source files to end in @file{.f}
8180 and require special flags to support other file name extensions.  The
8181 @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros deal with these
8182 issues.
8184 The @code{AC_FC_SRCEXT} macro tries to get the @code{FC} compiler to
8185 accept files ending with the extension @file{.@var{ext}} (i.e.,
8186 @var{ext} does @emph{not} contain the dot).  If any special compiler
8187 flags are needed for this, it stores them in the output variable
8188 @code{FCFLAGS_@var{ext}}.  This extension and these flags are then used
8189 for all subsequent @code{FC} tests (until @code{AC_FC_SRCEXT} or
8190 @code{AC_FC_PP_SRCEXT} is called another time).
8192 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
8193 @file{.f90} extension in future tests, and it would set the
8194 @code{FCFLAGS_f90} output variable with any extra flags that are needed
8195 to compile such files.
8197 Similarly, the @code{AC_FC_PP_SRCEXT} macro tries to get the @code{FC}
8198 compiler to preprocess and compile files with the extension
8199 @file{.@var{ext}}.  When both @command{fpp} and @command{cpp} style
8200 preprocessing are provided, the former is preferred, as the latter may
8201 treat continuation lines, @code{//} tokens, and white space differently
8202 from what some Fortran dialects expect.  Conversely, if you do not want
8203 files to be preprocessed, use only lower-case characters in the file
8204 name extension.  Like with @code{AC_FC_SRCEXT(f90)}, any needed flags
8205 are stored in the @code{FCFLAGS_@var{ext}} variable.
8207 The @code{FCFLAGS_@var{ext}} flags can @emph{not} be simply absorbed
8208 into @code{FCFLAGS}, for two reasons based on the limitations of some
8209 compilers.  First, only one @code{FCFLAGS_@var{ext}} can be used at a
8210 time, so files with different extensions must be compiled separately.
8211 Second, @code{FCFLAGS_@var{ext}} must appear @emph{immediately} before
8212 the source-code file name when compiling.  So, continuing the example
8213 above, you might compile a @file{foo.f90} file in your makefile with the
8214 command:
8216 @example
8217 foo.o: foo.f90
8218        $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
8219 @end example
8221 If @code{AC_FC_SRCEXT} or @code{AC_FC_PP_SRCEXT} succeeds in compiling
8222 files with the @var{ext} extension, it calls @var{action-if-success}
8223 (defaults to nothing).  If it fails, and cannot find a way to make the
8224 @code{FC} compiler accept such files, it calls @var{action-if-failure}
8225 (defaults to exiting with an error message).
8227 The @code{AC_FC_SRCEXT} and @code{AC_FC_PP_SRCEXT} macros cache their
8228 results in @code{ac_cv_fc_srcext_@var{ext}} and
8229 @code{ac_cv_fc_pp_srcext_@var{ext}} variables, respectively.
8230 @end defmac
8232 @defmac AC_FC_PP_DEFINE (@ovar{action-if-success}, @
8233   @dvar{action-if-failure, AC_MSG_FAILURE})
8234 @acindex{FC_PP_DEFINE}
8235 @caindex fc_pp_define
8237 Find a flag to specify defines for preprocessed Fortran.  Not all
8238 Fortran compilers use @option{-D}.  Substitute @code{FC_DEFINE} with
8239 the result and call @var{action-if-success} (defaults to nothing) if
8240 successful, and @var{action-if-failure} (defaults to failing with an
8241 error message) if not.
8243 This macro calls @code{AC_FC_PP_SRCEXT([F])} in order to learn how to
8244 preprocess a @file{conftest.F} file, but restores a previously used
8245 Fortran source file extension afterwards again.
8247 The result of this test is cached in the @code{ac_cv_fc_pp_define}
8248 variable.
8249 @end defmac
8251 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @
8252   @dvar{action-if-failure, AC_MSG_FAILURE})
8253 @acindex{FC_FREEFORM}
8254 @caindex fc_freeform
8256 Try to ensure that the Fortran compiler (@code{$FC}) allows free-format
8257 source code (as opposed to the older fixed-format style from Fortran
8258 77).  If necessary, it may add some additional flags to @code{FCFLAGS}.
8260 This macro is most important if you are using the default @file{.f}
8261 extension, since many compilers interpret this extension as indicating
8262 fixed-format source unless an additional flag is supplied.  If you
8263 specify a different extension with @code{AC_FC_SRCEXT}, such as
8264 @file{.f90}, then @code{AC_FC_FREEFORM} ordinarily succeeds without
8265 modifying @code{FCFLAGS}.  For extensions which the compiler does not
8266 know about, the flag set by the @code{AC_FC_SRCEXT} macro might let
8267 the compiler assume Fortran 77 by default, however.
8269 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
8270 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8271 calls @var{action-if-failure} (defaults to exiting with an error
8272 message).
8274 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8275 the @code{ac_cv_fc_freeform} variable.
8276 @end defmac
8278 @defmac AC_FC_FIXEDFORM (@ovar{action-if-success}, @
8279   @dvar{action-if-failure, AC_MSG_FAILURE})
8280 @acindex{FC_FIXEDFORM}
8281 @caindex fc_fixedform
8283 Try to ensure that the Fortran compiler (@code{$FC}) allows the old
8284 fixed-format source code (as opposed to free-format style).  If
8285 necessary, it may add some additional flags to @code{FCFLAGS}.
8287 This macro is needed for some compilers alias names like @command{xlf95}
8288 which assume free-form source code by default, and in case you want to
8289 use fixed-form source with an extension like @file{.f90} which many
8290 compilers interpret as free-form by default.  If you specify a different
8291 extension with @code{AC_FC_SRCEXT}, such as @file{.f}, then
8292 @code{AC_FC_FIXEDFORM} ordinarily succeeds without modifying
8293 @code{FCFLAGS}.
8295 If @code{AC_FC_FIXEDFORM} succeeds in compiling fixed-form source, it
8296 calls @var{action-if-success} (defaults to nothing).  If it fails, it
8297 calls @var{action-if-failure} (defaults to exiting with an error
8298 message).
8300 The result of this test, or @samp{none} or @samp{unknown}, is cached in
8301 the @code{ac_cv_fc_fixedform} variable.
8302 @end defmac
8304 @defmac AC_FC_LINE_LENGTH (@ovar{length}, @ovar{action-if-success}, @
8305   @dvar{action-if-failure, AC_MSG_FAILURE})
8306 @acindex{FC_LINE_LENGTH}
8307 @caindex fc_line_length
8309 Try to ensure that the Fortran compiler (@code{$FC}) accepts long source
8310 code lines.  The @var{length} argument may be given as 80, 132, or
8311 unlimited, and defaults to 132.  Note that line lengths above 254
8312 columns are not portable, and some compilers do not accept more than 132
8313 columns at least for fixed format source.  If necessary, it may add some
8314 additional flags to @code{FCFLAGS}.
8316 If @code{AC_FC_LINE_LENGTH} 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_line_length} variable.
8323 @end defmac
8325 @defmac AC_FC_CHECK_BOUNDS (@ovar{action-if-success}, @
8326   @dvar{action-if-failure, AC_MSG_FAILURE})
8327 @acindex{FC_CHECK_BOUNDS}
8328 @caindex fc_check_bounds
8330 The @code{AC_FC_CHECK_BOUNDS} macro tries to enable array bounds checking
8331 in the Fortran compiler.  If successful, the @var{action-if-success}
8332 is called and any needed flags are added to @code{FCFLAGS}.  Otherwise,
8333 @var{action-if-failure} is called, which defaults to failing with an error
8334 message.  The macro currently requires Fortran 90 or a newer dialect.
8336 The result of the macro is cached in the @code{ac_cv_fc_check_bounds}
8337 variable.
8338 @end defmac
8340 @defmac AC_F77_IMPLICIT_NONE (@ovar{action-if-success}, @
8341   @dvar{action-if-failure, AC_MSG_FAILURE})
8342 @defmacx AC_FC_IMPLICIT_NONE (@ovar{action-if-success}, @
8343   @dvar{action-if-failure, AC_MSG_FAILURE})
8344 @acindex{F77_IMPLICIT_NONE}
8345 @acindex{FC_IMPLICIT_NONE}
8346 @caindex f77_implicit_none
8347 @caindex fc_implicit_none
8349 Try to disallow implicit declarations in the Fortran compiler.  If
8350 successful, @var{action-if-success} is called and any needed flags
8351 are added to @code{FFLAGS} or @code{FCFLAGS}, respectively.  Otherwise,
8352 @var{action-if-failure} is called, which defaults to failing with an error
8353 message.
8355 The result of these macros are cached in the
8356 @code{ac_cv_f77_implicit_none} and @code{ac_cv_fc_implicit_none}
8357 variables, respectively.
8358 @end defmac
8360 @defmac AC_FC_MODULE_EXTENSION
8361 @acindex{FC_MODULE_EXTENSION}
8362 @caindex fc_module_ext
8363 @ovindex FC_MODEXT
8365 Find the Fortran 90 module file name extension.  Most Fortran 90
8366 compilers store module information in files separate from the object
8367 files.  The module files are usually named after the name of the module
8368 rather than the source file name, with characters possibly turned to
8369 upper case, plus an extension, often @file{.mod}.
8371 Not all compilers use module files at all, or by default.  The Cray
8372 Fortran compiler requires @option{-e m} in order to store and search
8373 module information in @file{.mod} files rather than in object files.
8374 Likewise, the Fujitsu Fortran compilers uses the @option{-Am} option to
8375 indicate how module information is stored.
8377 The @code{AC_FC_MODULE_EXTENSION} macro computes the module extension
8378 without the leading dot, and stores that in the @code{FC_MODEXT}
8379 variable.  If the compiler does not produce module files, or the
8380 extension cannot be determined, @code{FC_MODEXT} is empty.  Typically,
8381 the result of this macro may be used in cleanup @command{make} rules as
8382 follows:
8384 @example
8385 clean-modules:
8386         -test -z "$(FC_MODEXT)" || rm -f *.$(FC_MODEXT)
8387 @end example
8389 The extension, or @samp{unknown}, is cached in the
8390 @code{ac_cv_fc_module_ext} variable.
8391 @end defmac
8393 @defmac AC_FC_MODULE_FLAG (@ovar{action-if-success}, @
8394   @dvar{action-if-failure, AC_MSG_FAILURE})
8395 @acindex{FC_MODULE_FLAG}
8396 @caindex fc_module_flag
8397 @ovindex FC_MODINC
8398 @ovindex ac_empty
8400 Find the compiler flag to include Fortran 90 module information from
8401 another directory, and store that in the @code{FC_MODINC} variable.
8402 Call @var{action-if-success} (defaults to nothing) if successful, and
8403 set @code{FC_MODINC} to empty and call @var{action-if-failure} (defaults
8404 to exiting with an error message) if not.
8406 Most Fortran 90 compilers provide a way to specify module directories.
8407 Some have separate flags for the directory to write module files to,
8408 and directories to search them in, whereas others only allow writing to
8409 the current directory or to the first directory specified in the include
8410 path.  Further, with some compilers, the module search path and the
8411 preprocessor search path can only be modified with the same flag.  Thus,
8412 for portability, write module files to the current directory only and
8413 list that as first directory in the search path.
8415 There may be no whitespace between @code{FC_MODINC} and the following
8416 directory name, but @code{FC_MODINC} may contain trailing white space.
8417 For example, if you use Automake and would like to search @file{../lib}
8418 for module files, you can use the following:
8420 @example
8421 AM_FCFLAGS = $(FC_MODINC). $(FC_MODINC)../lib
8422 @end example
8424 Inside @command{configure} tests, you can use:
8426 @example
8427 if test -n "$FC_MODINC"; then
8428   FCFLAGS="$FCFLAGS $FC_MODINC. $FC_MODINC../lib"
8430 @end example
8432 The flag is cached in the @code{ac_cv_fc_module_flag} variable.
8433 The substituted value of @code{FC_MODINC} may refer to the
8434 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8435 the significant trailing whitespace in a @file{Makefile}.
8436 @end defmac
8438 @defmac AC_FC_MODULE_OUTPUT_FLAG (@ovar{action-if-success}, @
8439   @dvar{action-if-failure, AC_MSG_FAILURE})
8440 @acindex{FC_MODULE_OUTPUT_FLAG}
8441 @caindex fc_module_output_flag
8442 @ovindex FC_MODOUT
8444 Find the compiler flag to write Fortran 90 module information to
8445 another directory, and store that in the @code{FC_MODOUT} variable.
8446 Call @var{action-if-success} (defaults to nothing) if successful, and
8447 set @code{FC_MODOUT} to empty and call @var{action-if-failure} (defaults
8448 to exiting with an error message) if not.
8450 Not all Fortran 90 compilers write module files, and of those that do,
8451 not all allow writing to a directory other than the current one, nor
8452 do all have separate flags for writing and reading; see the description
8453 of @code{AC_FC_MODULE_FLAG} above.  If you need to be able to write to
8454 another directory, for maximum portability use @code{FC_MODOUT} before
8455 any @code{FC_MODINC} and include both the current directory and the one
8456 you write to in the search path:
8458 @example
8459 AM_FCFLAGS = $(FC_MODOUT)../mod $(FC_MODINC)../mod $(FC_MODINC). @dots{}
8460 @end example
8462 The flag is cached in the @code{ac_cv_fc_module_output_flag} variable.
8463 The substituted value of @code{FC_MODOUT} may refer to the
8464 @code{ac_empty} dummy placeholder empty variable, to avoid losing
8465 the significant trailing whitespace in a @file{Makefile}.
8466 @end defmac
8469 @node Go Compiler
8470 @subsection Go Compiler Characteristics
8471 @cindex Go
8473 Autoconf provides basic support for the Go programming language when
8474 using the @code{gccgo} compiler (there is currently no support for the
8475 @code{6g} and @code{8g} compilers).
8477 @defmac AC_PROG_GO (@ovar{compiler-search-list})
8478 Find the Go compiler to use.  Check whether the environment variable
8479 @code{GOC} is set; if so, then set output variable @code{GOC} to its
8480 value.
8482 Otherwise, if the macro is invoked without an argument, then search for
8483 a Go compiler named @code{gccgo}.  If it is not found, then as a last
8484 resort set @code{GOC} to @code{gccgo}.
8486 This macro may be invoked with an optional first argument which, if
8487 specified, must be a blank-separated list of Go compilers to search for.
8489 If output variable @code{GOFLAGS} was not already set, set it to
8490 @option{-g -O2}.  If your package does not like this default,
8491 @code{GOFLAGS} may be set before @code{AC_PROG_GO}.
8492 @end defmac
8495 @node System Services
8496 @section System Services
8498 The following macros check for operating system services or capabilities.
8500 @anchor{AC_PATH_X}
8501 @defmac AC_PATH_X
8502 @acindex{PATH_X}
8503 @evindex XMKMF
8504 @cindex X Window System
8505 Try to locate the X Window System include files and libraries.  If the
8506 user gave the command line options @option{--x-includes=@var{dir}} and
8507 @option{--x-libraries=@var{dir}}, use those directories.
8509 If either or both were not given, get the missing values by running
8510 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
8511 environment variable) on a trivial @file{Imakefile} and examining the
8512 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
8513 disables this method.
8515 If this method fails to find the X Window System, @command{configure}
8516 looks for the files in several directories where they often reside.
8517 If either method is successful, set the shell variables
8518 @code{x_includes} and @code{x_libraries} to their locations, unless they
8519 are in directories the compiler searches by default.
8521 If both methods fail, or the user gave the command line option
8522 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
8523 otherwise set it to the empty string.
8524 @end defmac
8526 @anchor{AC_PATH_XTRA}
8527 @defmac AC_PATH_XTRA
8528 @acindex{PATH_XTRA}
8529 @ovindex X_CFLAGS
8530 @ovindex X_LIBS
8531 @ovindex X_EXTRA_LIBS
8532 @ovindex X_PRE_LIBS
8533 @cvindex X_DISPLAY_MISSING
8534 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
8535 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
8536 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
8537 available.
8539 This macro also checks for special libraries that some systems need in
8540 order to compile X programs.  It adds any that the system needs to
8541 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
8542 libraries that need to be linked with before @option{-lX11}, and adds
8543 any found to the output variable @code{X_PRE_LIBS}.
8545 @c This is an incomplete kludge.  Make a real way to do it.
8546 @c If you need to check for other X functions or libraries yourself, then
8547 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
8548 @c @code{LIBS} temporarily, like this: (FIXME - add example)
8549 @end defmac
8551 @anchor{AC_SYS_INTERPRETER}
8552 @defmac AC_SYS_INTERPRETER
8553 @acindex{SYS_INTERPRETER}
8554 Check whether the system supports starting scripts with a line of the
8555 form @samp{#!/bin/sh} to select the interpreter to use for the script.
8556 After running this macro, shell code in @file{configure.ac} can check
8557 the shell variable @code{interpval}; it is set to @samp{yes}
8558 if the system supports @samp{#!}, @samp{no} if not.
8559 @end defmac
8561 @defmac AC_SYS_LARGEFILE
8562 @acindex{SYS_LARGEFILE}
8563 @cvindex _FILE_OFFSET_BITS
8564 @cvindex _LARGE_FILES
8565 @ovindex CC
8566 @cindex Large file support
8567 @cindex LFS
8568 Arrange for 64-bit file offsets, known as
8569 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
8570 large-file support}.  On some hosts, one must use special compiler
8571 options to build programs that can access large files.  Append any such
8572 options to the output variable @code{CC}.  Define
8573 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
8575 Large-file support can be disabled by configuring with the
8576 @option{--disable-largefile} option.
8578 If you use this macro, check that your program works even when
8579 @code{off_t} is wider than @code{long int}, since this is common when
8580 large-file support is enabled.  For example, it is not correct to print
8581 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
8582 (long int) X)}.
8584 The LFS introduced the @code{fseeko} and @code{ftello} functions to
8585 replace their C counterparts @code{fseek} and @code{ftell} that do not
8586 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
8587 prototypes available when using them and large-file support is
8588 enabled.
8589 @end defmac
8591 @anchor{AC_SYS_LONG_FILE_NAMES}
8592 @defmac AC_SYS_LONG_FILE_NAMES
8593 @acindex{SYS_LONG_FILE_NAMES}
8594 @cvindex HAVE_LONG_FILE_NAMES
8595 If the system supports file names longer than 14 characters, define
8596 @code{HAVE_LONG_FILE_NAMES}.
8597 @end defmac
8599 @defmac AC_SYS_POSIX_TERMIOS
8600 @acindex{SYS_POSIX_TERMIOS}
8601 @cindex Posix termios headers
8602 @cindex termios Posix headers
8603 @caindex sys_posix_termios
8604 Check to see if the Posix termios headers and functions are available on the
8605 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
8606 @samp{yes}.  If not, set the variable to @samp{no}.
8607 @end defmac
8609 @node Posix Variants
8610 @section Posix Variants
8612 The following macro makes it possible to use features of Posix that are
8613 extensions to C, as well as platform extensions not defined by Posix.
8615 @anchor{AC_USE_SYSTEM_EXTENSIONS}
8616 @defmac AC_USE_SYSTEM_EXTENSIONS
8617 @acindex{USE_SYSTEM_EXTENSIONS}
8618 @cvindex _GNU_SOURCE
8619 @cvindex _ALL_SOURCE
8620 @cvindex _DARWIN_C_SOURCE
8621 @cvindex _MINIX
8622 @cvindex _NETBSD_SOURCE
8623 @cvindex _POSIX_1_SOURCE
8624 @cvindex _POSIX_PTHREAD_SEMANTICS
8625 @cvindex _POSIX_SOURCE
8626 @cvindex _TANDEM_SOURCE
8627 @cvindex _XOPEN_SOURCE
8628 @cvindex __EXTENSIONS__
8629 @cvindex __STDC_WANT_IEC_60559_BFP_EXT__
8630 @cvindex __STDC_WANT_IEC_60559_FUNCS_EXT__
8631 @cvindex __STDC_WANT_LIB_EXT2__
8632 If possible, enable
8633 extensions to C or Posix on hosts that normally disable the extensions,
8634 typically due to standards-conformance namespace issues.  This should be
8635 called before any macros that run the C compiler.  The following
8636 preprocessor macros are defined where appropriate:
8638 @table @code
8639 @item _GNU_SOURCE
8640 Enable extensions on GNU/Linux.
8641 @item _ALL_SOURCE
8642 Enable extensions for AIX 3, and for Interix.
8643 @item _DARWIN_C_SOURCE
8644 Enable extensions for macOS.
8645 @item _MINIX
8646 Identify Minix platform.  This particular preprocessor macro is
8647 obsolescent, and may be removed in a future release of Autoconf.
8648 @item _NETBSD_SOURCE
8649 Enable NetBSD-related extensions for Minix.
8650 @item _POSIX_1_SOURCE
8651 Enable additional Posix functions for Minix.
8652 @item _POSIX_PTHREAD_SEMANTICS
8653 Enable threading extensions on Solaris.
8654 @item _POSIX_SOURCE
8655 Enable Posix functions for Minix.
8656 @item _TANDEM_SOURCE
8657 Enable extensions for the HP NonStop platform.
8658 @item _XOPEN_SOURCE
8659 Enable X/Open extensions for HP-UX.
8660 @item __EXTENSIONS__
8661 Enable general extensions on Solaris.
8662 @item __STDC_WANT_IEC_60559_BFP_EXT__
8663 Enable extensions specified by ISO/IEC TS 18661-1:2014.
8664 @item __STDC_WANT_IEC_60559_FUNCS_EXT__
8665 Enable extensions specified by ISO/IEC TS 18661-4:2015.
8666 @item __STDC_WANT_LIB_EXT2__
8667 Enable extensions specified by ISO/IEC TR 24731-2:2010.
8668 @end table
8670 The macro @code{__STDC_WANT_LIB_EXT1__} is not defined, as C11 Annex K
8671 is problematic.  See: O'Donell C, Sebor M.
8672 @uref{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1967.htm, Field
8673 Experience With Annex K---Bounds Checking Interfaces}.
8675 This macro was introduced in Autoconf 2.60.
8676 @end defmac
8679 @node Erlang Libraries
8680 @section Erlang Libraries
8681 @cindex Erlang, Library, checking
8683 The following macros check for an installation of Erlang/OTP, and for the
8684 presence of certain Erlang libraries.  All those macros require the
8685 configuration of an Erlang interpreter and an Erlang compiler
8686 (@pxref{Erlang Compiler and Interpreter}).
8688 @defmac AC_ERLANG_SUBST_ERTS_VER
8689 @acindex{ERLANG_SUBST_ERTS_VER}
8690 @ovindex ERLANG_ERTS_VER
8691 Set the output variable @code{ERLANG_ERTS_VER} to the version of the
8692 Erlang runtime system (as returned by Erlang's
8693 @code{erlang:system_info(version)} function).  The result of this test
8694 is cached if caching is enabled when running @command{configure}.  The
8695 @code{ERLANG_ERTS_VER} variable is not intended to be used for testing
8696 for features of specific ERTS versions, but to be used for substituting
8697 the ERTS version in Erlang/OTP release resource files (@code{.rel}
8698 files), as shown below.
8699 @end defmac
8701 @defmac AC_ERLANG_SUBST_ROOT_DIR
8702 @acindex{ERLANG_SUBST_ROOT_DIR}
8703 @ovindex ERLANG_ROOT_DIR
8704 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
8705 directory in which Erlang/OTP is installed (as returned by Erlang's
8706 @code{code:root_dir/0} function).  The result of this test is cached if
8707 caching is enabled when running @command{configure}.
8708 @end defmac
8710 @defmac AC_ERLANG_SUBST_LIB_DIR
8711 @acindex{ERLANG_SUBST_LIB_DIR}
8712 @ovindex ERLANG_LIB_DIR
8713 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
8714 directory of Erlang/OTP (as returned by Erlang's
8715 @code{code:lib_dir/0} function), which subdirectories each contain an installed
8716 Erlang/OTP library.  The result of this test is cached if caching is enabled
8717 when running @command{configure}.
8718 @end defmac
8720 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
8721   @ovar{action-if-not-found})
8722 @acindex{ERLANG_CHECK_LIB}
8723 @ovindex ERLANG_LIB_DIR_@var{library}
8724 @ovindex ERLANG_LIB_VER_@var{library}
8725 Test whether the Erlang/OTP library @var{library} is installed by
8726 calling Erlang's @code{code:lib_dir/1} function.  The result of this
8727 test is cached if caching is enabled when running @command{configure}.
8728 @var{action-if-found} is a list of shell commands to run if the library
8729 is installed; @var{action-if-not-found} is a list of shell commands to
8730 run if it is not.  Additionally, if the library is installed, the output
8731 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
8732 library installation directory, and the output variable
8733 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
8734 part of the subdirectory name, if it is in the standard form
8735 (@code{@var{library}-@var{version}}).  If the directory name does not
8736 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
8737 empty string.  If the library is not installed,
8738 @samp{ERLANG_LIB_DIR_@var{library}} and
8739 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
8740 example, to check if library @code{stdlib} is installed:
8742 @example
8743 AC_ERLANG_CHECK_LIB([stdlib],
8744   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
8745    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
8746   [AC_MSG_ERROR([stdlib was not found!])])
8747 @end example
8749 The @samp{ERLANG_LIB_VER_@var{library}} variables (set by
8750 @code{AC_ERLANG_CHECK_LIB}) and the @code{ERLANG_ERTS_VER} variable (set
8751 by @code{AC_ERLANG_SUBST_ERTS_VER}) are not intended to be used for
8752 testing for features of specific versions of libraries or of the Erlang
8753 runtime system.  Those variables are intended to be substituted in
8754 Erlang release resource files (@code{.rel} files).  For instance, to
8755 generate a @file{example.rel} file for an application depending on the
8756 @code{stdlib} library, @file{configure.ac} could contain:
8758 @example
8759 AC_ERLANG_SUBST_ERTS_VER
8760 AC_ERLANG_CHECK_LIB([stdlib],
8761   [],
8762   [AC_MSG_ERROR([stdlib was not found!])])
8763 AC_CONFIG_FILES([example.rel])
8764 @end example
8766 @noindent
8767 The @file{example.rel.in} file used to generate @file{example.rel}
8768 should contain:
8770 @example
8771 @{release,
8772     @{"@@PACKAGE@@", "@@VERSION@@"@},
8773     @{erts, "@@ERLANG_ERTS_VER@@"@},
8774     [@{stdlib, "@@ERLANG_LIB_VER_stdlib@@"@},
8775      @{@@PACKAGE@@, "@@VERSION@@"@}]@}.
8776 @end example
8777 @end defmac
8779 In addition to the above macros, which test installed Erlang libraries, the
8780 following macros determine the paths to the directories into which newly built
8781 Erlang libraries are to be installed:
8783 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
8784 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
8785 @ovindex ERLANG_INSTALL_LIB_DIR
8787 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
8788 which every built Erlang library should be installed in a separate
8789 subdirectory.
8790 If this variable is not set in the environment when @command{configure} runs,
8791 its default value is @code{$@{libdir@}/erlang/lib}.
8792 @end defmac
8794 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
8795 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
8796 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
8798 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
8799 directory into which the built Erlang library @var{library} version
8800 @var{version} should be installed.  If this variable is not set in the
8801 environment when @command{configure} runs, its default value is
8802 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
8803 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
8804 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
8805 @end defmac
8811 @c ========================================================= Writing Tests
8813 @node Writing Tests
8814 @chapter Writing Tests
8816 If the existing feature tests don't do something you need, you have to
8817 write new ones.  These macros are the building blocks.  They provide
8818 ways for other macros to check whether various kinds of features are
8819 available and report the results.
8821 This chapter contains some suggestions and some of the reasons why the
8822 existing tests are written the way they are.  You can also learn a lot
8823 about how to write Autoconf tests by looking at the existing ones.  If
8824 something goes wrong in one or more of the Autoconf tests, this
8825 information can help you understand the assumptions behind them, which
8826 might help you figure out how to best solve the problem.
8828 These macros check the output of the compiler system of the current
8829 language (@pxref{Language Choice}).  They do not cache the results of
8830 their tests for future use (@pxref{Caching Results}), because they don't
8831 know enough about the information they are checking for to generate a
8832 cache variable name.  They also do not print any messages, for the same
8833 reason.  The checks for particular kinds of features call these macros
8834 and do cache their results and print messages about what they're
8835 checking for.
8837 When you write a feature test that could be applicable to more than one
8838 software package, the best thing to do is encapsulate it in a new macro.
8839 @xref{Writing Autoconf Macros}, for how to do that.
8841 @menu
8842 * Language Choice::             Selecting which language to use for testing
8843 * Writing Test Programs::       Forging source files for compilers
8844 * Running the Preprocessor::    Detecting preprocessor symbols
8845 * Running the Compiler::        Detecting language or header features
8846 * Running the Linker::          Detecting library features
8847 * Runtime::                     Testing for runtime features
8848 * Systemology::                 A zoology of operating systems
8849 * Multiple Cases::              Tests for several possible values
8850 @end menu
8852 @node Language Choice
8853 @section Language Choice
8854 @cindex Language
8856 Autoconf-generated @command{configure} scripts check for the C compiler and
8857 its features by default.  Packages that use other programming languages
8858 (maybe more than one, e.g., C and C++) need to test features of the
8859 compilers for the respective languages.  The following macros determine
8860 which programming language is used in the subsequent tests in
8861 @file{configure.ac}.
8863 @anchor{AC_LANG}
8864 @defmac AC_LANG (@var{language})
8865 @acindex{LANG}
8866 Do compilation tests using the compiler, preprocessor, and file
8867 extensions for the specified @var{language}.
8869 Supported languages are:
8871 @table @samp
8872 @item C
8873 Do compilation tests using @code{CC} and @code{CPP} and use extension
8874 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
8875 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
8877 @item C++
8878 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
8879 extension @file{.C} for test programs.  Use compilation flags:
8880 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
8881 @code{CXXFLAGS} with @code{CXX}.
8883 @item Fortran 77
8884 Do compilation tests using @code{F77} and use extension @file{.f} for
8885 test programs.  Use compilation flags: @code{FFLAGS}.
8887 @item Fortran
8888 Do compilation tests using @code{FC} and use extension @file{.f} (or
8889 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
8890 compilation flags: @code{FCFLAGS}.
8892 @item Erlang
8893 @ovindex ERLC
8894 @ovindex ERL
8895 @ovindex ERLCFLAGS
8896 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
8897 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
8899 @item Objective C
8900 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
8901 extension @file{.m} for test programs.  Use compilation flags:
8902 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
8903 @code{OBJCFLAGS} with @code{OBJC}.
8905 @item Objective C++
8906 Do compilation tests using @code{OBJCXX} and @code{OBJCXXCPP} and use
8907 extension @file{.mm} for test programs.  Use compilation flags:
8908 @code{CPPFLAGS} with @code{OBJCXXCPP}, and both @code{CPPFLAGS} and
8909 @code{OBJCXXFLAGS} with @code{OBJCXX}.
8911 @item Go
8912 Do compilation tests using @code{GOC} and use extension @file{.go} for
8913 test programs.  Use compilation flags @code{GOFLAGS}.
8914 @end table
8915 @end defmac
8917 @anchor{AC_LANG_PUSH}
8918 @defmac AC_LANG_PUSH (@var{language})
8919 @acindex{LANG_PUSH}
8920 Remember the current language (as set by @code{AC_LANG}) on a stack, and
8921 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
8922 in macros that need to temporarily switch to a particular language.
8923 @end defmac
8925 @defmac AC_LANG_POP (@ovar{language})
8926 @acindex{LANG_POP}
8927 Select the language that is saved on the top of the stack, as set by
8928 @code{AC_LANG_PUSH}, and remove it from the stack.
8930 If given, @var{language} specifies the language we just @emph{quit}.  It
8931 is a good idea to specify it when it's known (which should be the
8932 case@dots{}), since Autoconf detects inconsistencies.
8934 @example
8935 AC_LANG_PUSH([Fortran 77])
8936 # Perform some tests on Fortran 77.
8937 # @dots{}
8938 AC_LANG_POP([Fortran 77])
8939 @end example
8940 @end defmac
8942 @defmac AC_LANG_ASSERT (@var{language})
8943 @acindex{LANG_ASSERT}
8944 Check statically that the current language is @var{language}.
8945 You should use this in your language specific macros
8946 to avoid that they be called with an inappropriate language.
8948 This macro runs only at @command{autoconf} time, and incurs no cost at
8949 @command{configure} time.  Sadly enough and because Autoconf is a two
8950 layer language @footnote{Because M4 is not aware of Sh code,
8951 especially conditionals, some optimizations that look nice statically
8952 may produce incorrect results at runtime.}, the macros
8953 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
8954 therefore as much as possible you ought to avoid using them to wrap
8955 your code, rather, require from the user to run the macro with a
8956 correct current language, and check it with @code{AC_LANG_ASSERT}.
8957 And anyway, that may help the user understand she is running a Fortran
8958 macro while expecting a result about her Fortran 77 compiler@enddots{}
8959 @end defmac
8962 @defmac AC_REQUIRE_CPP
8963 @acindex{REQUIRE_CPP}
8964 Ensure that whichever preprocessor would currently be used for tests has
8965 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
8966 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
8967 depending on which language is current.
8968 @end defmac
8971 @node Writing Test Programs
8972 @section Writing Test Programs
8974 Autoconf tests follow a common scheme: feed some program with some
8975 input, and most of the time, feed a compiler with some source file.
8976 This section is dedicated to these source samples.
8978 @menu
8979 * Guidelines::                  General rules for writing test programs
8980 * Test Functions::              Avoiding pitfalls in test programs
8981 * Generating Sources::          Source program boilerplate
8982 @end menu
8984 @node Guidelines
8985 @subsection Guidelines for Test Programs
8987 The most important rule to follow when writing testing samples is:
8989 @center @emph{Look for realism.}
8991 This motto means that testing samples must be written with the same
8992 strictness as real programs are written.  In particular, you should
8993 avoid ``shortcuts'' and simplifications.
8995 Don't just play with the preprocessor if you want to prepare a
8996 compilation.  For instance, using @command{cpp} to check whether a header is
8997 functional might let your @command{configure} accept a header which
8998 causes some @emph{compiler} error.  Do not hesitate to check a header with
8999 other headers included before, especially required headers.
9001 Make sure the symbols you use are properly defined, i.e., refrain from
9002 simply declaring a function yourself instead of including the proper
9003 header.
9005 Test programs should not write to standard output.  They
9006 should exit with status 0 if the test succeeds, and with status 1
9007 otherwise, so that success
9008 can be distinguished easily from a core dump or other failure;
9009 segmentation violations and other failures produce a nonzero exit
9010 status.  Unless you arrange for @code{exit} to be declared, test
9011 programs should @code{return}, not @code{exit}, from @code{main},
9012 because on many systems @code{exit} is not declared by default.
9014 Test programs can use @code{#if} or @code{#ifdef} to check the values of
9015 preprocessor macros defined by tests that have already run.  For
9016 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
9017 @file{configure.ac} you can have a test program that includes
9018 @file{stdbool.h} conditionally:
9020 @example
9021 @group
9022 #ifdef HAVE_STDBOOL_H
9023 # include <stdbool.h>
9024 #endif
9025 @end group
9026 @end example
9028 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
9029 work with any standard C compiler.  Some developers prefer @code{#if}
9030 because it is easier to read, while others prefer @code{#ifdef} because
9031 it avoids diagnostics with picky compilers like GCC with the
9032 @option{-Wundef} option.
9034 If a test program needs to use or create a data file, give it a name
9035 that starts with @file{conftest}, such as @file{conftest.data}.  The
9036 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
9037 after running test programs and if the script is interrupted.
9039 @node Test Functions
9040 @subsection Test Functions
9042 These days it's safe to assume support for function prototypes
9043 (introduced in C89).
9045 Functions that test programs declare should also be conditionalized for
9046 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
9047 include any header files containing clashing prototypes.
9049 @example
9050 #ifdef __cplusplus
9051 extern "C"
9052 #endif
9053 void *valloc (size_t);
9054 @end example
9056 If a test program calls a function with invalid parameters (just to see
9057 whether it exists), organize the program to ensure that it never invokes
9058 that function.  You can do this by calling it in another function that is
9059 never invoked.  You can't do it by putting it after a call to
9060 @code{exit}, because GCC version 2 knows that @code{exit}
9061 never returns
9062 and optimizes out any code that follows it in the same block.
9064 If you include any header files, be sure to call the functions
9065 relevant to them with the correct number of arguments, even if they are
9066 just 0, to avoid compilation errors due to prototypes.  GCC
9067 version 2
9068 has internal prototypes for several functions that it automatically
9069 inlines; for example, @code{memcpy}.  To avoid errors when checking for
9070 them, either pass them the correct number of arguments or redeclare them
9071 with a different return type (such as @code{char}).
9074 @node Generating Sources
9075 @subsection Generating Sources
9077 Autoconf provides a set of macros that can be used to generate test
9078 source files.  They are written to be language generic, i.e., they
9079 actually depend on the current language (@pxref{Language Choice}) to
9080 ``format'' the output properly.
9083 @defmac AC_LANG_CONFTEST (@var{source})
9084 @acindex{LANG_CONFTEST}
9085 Save the @var{source} text in the current test source file:
9086 @file{conftest.@var{extension}} where the @var{extension} depends on the
9087 current language.  As of Autoconf 2.63b, the source file also contains
9088 the results of all of the @code{AC_DEFINE} performed so far.
9090 Note that the @var{source} is evaluated exactly once, like regular
9091 Autoconf macro arguments, and therefore (i) you may pass a macro
9092 invocation, (ii) if not, be sure to double quote if needed.
9094 This macro issues a warning during @command{autoconf} processing if
9095 @var{source} does not include an expansion of the macro
9096 @code{AC_LANG_DEFINES_PROVIDED} (note that both @code{AC_LANG_SOURCE} and
9097 @code{AC_LANG_PROGRAM} call this macro, and thus avoid the warning).
9099 This macro is seldom called directly, but is used under the hood by more
9100 common macros such as @code{AC_COMPILE_IFELSE} and @code{AC_RUN_IFELSE}.
9101 @end defmac
9103 @defmac AC_LANG_DEFINES_PROVIDED
9104 @acindex{LANG_DEFINES_PROVIDED}
9105 This macro is called as a witness that the file
9106 @file{conftest.@var{extension}} appropriate for the current language is
9107 complete, including all previously determined results from
9108 @code{AC_DEFINE}.  This macro is seldom called directly, but exists if
9109 you have a compelling reason to write a conftest file without using
9110 @code{AC_LANG_SOURCE}, yet still want to avoid a syntax warning from
9111 @code{AC_LANG_CONFTEST}.
9112 @end defmac
9114 @defmac AC_LANG_SOURCE (@var{source})
9115 @acindex{LANG_SOURCE}
9116 Expands into the @var{source}, with the definition of
9117 all the @code{AC_DEFINE} performed so far.  This macro includes an
9118 expansion of @code{AC_LANG_DEFINES_PROVIDED}.
9120 In many cases, you may find it more convenient to use the wrapper
9121 @code{AC_LANG_PROGRAM}.
9122 @end defmac
9124 For instance, executing (observe the double quotation!):
9126 @example
9127 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9128 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9129         [http://www.example.org/])
9130 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9131   [Greetings string.])
9132 AC_LANG([C])
9133 AC_LANG_CONFTEST(
9134    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
9135 gcc -E -dD conftest.c
9136 @end example
9138 @noindent
9139 on a system with @command{gcc} installed, results in:
9141 @example
9142 @c If you change this example, adjust tests/compile.at:AC_LANG_SOURCE example.
9143 @dots{}
9144 @asis{#} 1 "conftest.c"
9146 #define PACKAGE_NAME "Hello"
9147 #define PACKAGE_TARNAME "hello"
9148 #define PACKAGE_VERSION "1.0"
9149 #define PACKAGE_STRING "Hello 1.0"
9150 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9151 #define PACKAGE_URL "http://www.example.org/"
9152 #define HELLO_WORLD "Hello, World\n"
9154 const char hw[] = "Hello, World\n";
9155 @end example
9157 When the test language is Fortran, Erlang, or Go, the @code{AC_DEFINE}
9158 definitions are not automatically translated into constants in the
9159 source code by this macro.
9161 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
9162 @acindex{LANG_PROGRAM}
9163 Expands into a source file which consists of the @var{prologue}, and
9164 then @var{body} as body of the main function (e.g., @code{main} in
9165 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
9166 available.
9167 @end defmac
9169 For instance:
9171 @example
9172 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9173 AC_INIT([Hello], [1.0], [bug-hello@@example.org], [],
9174         [http://www.example.org/])
9175 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9176   [Greetings string.])
9177 AC_LANG_CONFTEST(
9178 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9179                  [[fputs (hw, stdout);]])])
9180 gcc -E -dD conftest.c
9181 @end example
9183 @noindent
9184 on a system with @command{gcc} installed, results in:
9186 @example
9187 @c If you change this example, adjust tests/compile.at:AC_LANG_PROGRAM example.
9188 @dots{}
9189 @asis{#} 1 "conftest.c"
9191 #define PACKAGE_NAME "Hello"
9192 #define PACKAGE_TARNAME "hello"
9193 #define PACKAGE_VERSION "1.0"
9194 #define PACKAGE_STRING "Hello 1.0"
9195 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
9196 #define PACKAGE_URL "http://www.example.org/"
9197 #define HELLO_WORLD "Hello, World\n"
9199 const char hw[] = "Hello, World\n";
9201 main (void)
9203 fputs (hw, stdout);
9204   ;
9205   return 0;
9207 @end example
9209 In Erlang tests, the created source file is that of an Erlang module called
9210 @code{conftest} (@file{conftest.erl}).  This module defines and exports
9211 at least
9212 one @code{start/0} function, which is called to perform the test.  The
9213 @var{prologue} is optional code that is inserted between the module header and
9214 the @code{start/0} function definition.  @var{body} is the body of the
9215 @code{start/0} function without the final period (@pxref{Runtime}, about
9216 constraints on this function's behavior).
9218 For instance:
9220 @example
9221 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9222 AC_LANG(Erlang)
9223 AC_LANG_CONFTEST(
9224 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
9225                  [[io:format("~s~n", [?HELLO_WORLD])]])])
9226 cat conftest.erl
9227 @end example
9229 @noindent
9230 results in:
9232 @example
9233 -module(conftest).
9234 -export([start/0]).
9235 -define(HELLO_WORLD, "Hello, world!").
9236 start() ->
9237 io:format("~s~n", [?HELLO_WORLD])
9239 @end example
9241 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
9242 @acindex{LANG_CALL}
9243 Expands into a source file which consists of the @var{prologue}, and
9244 then a call to the @var{function} as body of the main function (e.g.,
9245 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
9246 of the latter are available.
9248 This function will probably be replaced in the future by a version
9249 which would enable specifying the arguments.  The use of this macro is
9250 not encouraged, as it violates strongly the typing system.
9252 This macro cannot be used for Erlang tests.
9253 @end defmac
9255 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
9256 @acindex{LANG_FUNC_LINK_TRY}
9257 Expands into a source file which uses the @var{function} in the body of
9258 the main function (e.g., @code{main} in C).  Since it uses
9259 @code{AC_LANG_PROGRAM}, the features of the latter are available.
9261 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
9262 It is considered to be severely broken, and in the future will be
9263 removed in favor of actual function calls (with properly typed
9264 arguments).
9266 This macro cannot be used for Erlang tests.
9267 @end defmac
9269 @node Running the Preprocessor
9270 @section Running the Preprocessor
9272 Sometimes one might need to run the preprocessor on some source file.
9273 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
9274 your project, not merely run the preprocessor on it; therefore you
9275 certainly want to run the compiler, not the preprocessor.  Resist the
9276 temptation of following the easiest path.
9278 Nevertheless, if you need to run the preprocessor, then use
9279 @code{AC_PREPROC_IFELSE}.
9281 The macros described in this section cannot be used for tests in Erlang,
9282 Fortran, or Go, since those languages require no preprocessor.
9284 @anchor{AC_PREPROC_IFELSE}
9285 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
9286   @ovar{action-if-false})
9287 @acindex{PREPROC_IFELSE}
9288 Run the preprocessor of the current language (@pxref{Language Choice})
9289 on the @var{input}, run the shell commands @var{action-if-true} on
9290 success, @var{action-if-false} otherwise.  The @var{input} can be made
9291 by @code{AC_LANG_PROGRAM} and friends.
9293 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
9294 @option{-g}, @option{-O}, etc.@: are not valid options to many C
9295 preprocessors.
9297 It is customary to report unexpected failures with
9298 @code{AC_MSG_FAILURE}.  If needed, @var{action-if-true} can further access
9299 the preprocessed output in the file @file{conftest.i}.
9300 @end defmac
9302 For instance:
9304 @example
9305 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
9306 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
9307   [Greetings string.])
9308 AC_PREPROC_IFELSE(
9309    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
9310                     [[fputs (hw, stdout);]])],
9311    [AC_MSG_RESULT([OK])],
9312    [AC_MSG_FAILURE([unexpected preprocessor failure])])
9313 @end example
9315 @noindent
9316 might result in:
9318 @example
9319 checking for gcc... gcc
9320 checking whether the C compiler works... yes
9321 checking for C compiler default output file name... a.out
9322 checking for suffix of executables...
9323 checking whether we are cross compiling... no
9324 checking for suffix of object files... o
9325 checking whether the compiler supports GNU C... yes
9326 checking whether gcc accepts -g... yes
9327 checking for gcc option to enable C11 features... -std=gnu11
9328 checking how to run the C preprocessor... gcc -std=gnu11 -E
9330 @end example
9332 @sp 1
9334 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
9335 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
9336 it impossible to use it to elaborate sources.  You are encouraged to
9337 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
9338 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
9339 to run the @emph{preprocessor} and not the compiler?
9341 @anchor{AC_EGREP_HEADER}
9342 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
9343   @var{action-if-found}, @ovar{action-if-not-found})
9344 @acindex{EGREP_HEADER}
9345 If the output of running the preprocessor on the system header file
9346 @var{header-file} matches the extended regular expression
9347 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
9348 execute @var{action-if-not-found}.
9349 @end defmac
9351 @anchor{AC_EGREP_CPP}
9352 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
9353   @ovar{action-if-found}, @ovar{action-if-not-found})
9354 @acindex{EGREP_CPP}
9355 @var{program} is the text of a C or C++ program, on which shell
9356 variable, back quote, and backslash substitutions are performed.  If the
9357 output of running the preprocessor on @var{program} matches the
9358 extended regular expression @var{pattern}, execute shell commands
9359 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
9360 @end defmac
9364 @node Running the Compiler
9365 @section Running the Compiler
9367 To check for a syntax feature of the current language's (@pxref{Language
9368 Choice}) compiler, such as whether it recognizes a certain keyword, or
9369 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
9370 to compile a small program that uses that feature.
9372 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
9373   @ovar{action-if-false})
9374 @acindex{COMPILE_IFELSE}
9375 Run the compiler and compilation flags of the current language
9376 (@pxref{Language Choice}) on the @var{input}, run the shell commands
9377 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
9378 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9380 It is customary to report unexpected failures with
9381 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
9382 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
9383 Linker}).  If needed, @var{action-if-true} can further access the
9384 just-compiled object file @file{conftest.$OBJEXT}.
9386 This macro uses @code{AC_REQUIRE} for the compiler associated with the
9387 current language, which means that if the compiler has not yet been
9388 determined, the compiler determination will be made prior to the body of
9389 the outermost @code{AC_DEFUN} macro that triggered this macro to
9390 expand (@pxref{Expanded Before Required}).
9391 @end defmac
9393 @ovindex ERL
9394 For tests in Erlang, the @var{input} must be the source code of a module named
9395 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
9396 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
9397 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
9398 to ensure that the Erlang module has the right name.
9400 @node Running the Linker
9401 @section Running the Linker
9403 To check for a library, a function, or a global variable, Autoconf
9404 @command{configure} scripts try to compile and link a small program that
9405 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
9406 @code{ar} on the C library to try to figure out which functions are
9407 available.  Trying to link with the function is usually a more reliable
9408 approach because it avoids dealing with the variations in the options
9409 and output formats of @code{nm} and @code{ar} and in the location of the
9410 standard libraries.  It also allows configuring for cross-compilation or
9411 checking a function's runtime behavior if needed.  On the other hand,
9412 it can be slower than scanning the libraries once, but accuracy is more
9413 important than speed.
9415 @code{AC_LINK_IFELSE} is used to compile test programs to test for
9416 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
9417 to check for libraries (@pxref{Libraries}), by adding the library being
9418 checked for to @code{LIBS} temporarily and trying to link a small
9419 program.
9421 @anchor{AC_LINK_IFELSE}
9422 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
9423   @ovar{action-if-false})
9424 @acindex{LINK_IFELSE}
9425 Run the compiler (and compilation flags) and the linker of the current
9426 language (@pxref{Language Choice}) on the @var{input}, run the shell
9427 commands @var{action-if-true} on success, @var{action-if-false}
9428 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
9429 friends.  If needed, @var{action-if-true} can further access the
9430 just-linked program file @file{conftest$EXEEXT}.
9432 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9433 current compilation flags.
9435 It is customary to report unexpected failures with
9436 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
9437 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
9438 @end defmac
9440 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
9441 programs are interpreted and do not require linking.
9445 @node Runtime
9446 @section Checking Runtime Behavior
9448 Sometimes you need to find out how a system performs at runtime, such
9449 as whether a given function has a certain capability or bug.  If you
9450 can, make such checks when your program runs instead of when it is
9451 configured.  You can check for things like the machine's endianness when
9452 your program initializes itself.
9454 If you really need to test for a runtime behavior while configuring,
9455 you can write a test program to determine the result, and compile and
9456 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
9457 possible, because this prevents people from configuring your package for
9458 cross-compiling.
9460 @anchor{AC_RUN_IFELSE}
9461 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
9462   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
9463 @acindex{RUN_IFELSE}
9464 Run the compiler (and compilation flags) and the linker of the current
9465 language (@pxref{Language Choice}) on the @var{input}, then execute the
9466 resulting program.  If the program returns an exit
9467 status of 0 when executed, run shell commands @var{action-if-true}.
9468 Otherwise, run shell commands @var{action-if-false}.
9470 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
9471 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
9472 compilation flags of the current language (@pxref{Language Choice}).
9473 Additionally, @var{action-if-true} can run @command{./conftest$EXEEXT}
9474 for further testing.
9476 In the @var{action-if-false} section, the failing exit status is
9477 available in the shell variable @samp{$?}.  This exit status might be
9478 that of a failed compilation, or it might be that of a failed program
9479 execution.
9481 If cross-compilation mode is enabled (this is the case if either the
9482 compiler being used does not produce executables that run on the system
9483 where @command{configure} is being run, or if the options @code{--build}
9484 and @code{--host} were both specified and their values are different),
9485 then the test program is
9486 not run.  If the optional shell commands @var{action-if-cross-compiling}
9487 are given, those commands are run instead; typically these commands
9488 provide pessimistic defaults that allow cross-compilation to work even
9489 if the guess was wrong.  If the fourth argument is empty or omitted, but
9490 cross-compilation is detected, then @command{configure} prints an error
9491 message and exits.  If you want your package to be useful in a
9492 cross-compilation scenario, you @emph{should} provide a non-empty
9493 @var{action-if-cross-compiling} clause, as well as wrap the
9494 @code{AC_RUN_IFELSE} compilation inside an @code{AC_CACHE_CHECK}
9495 (@pxref{Caching Results}) which allows the user to override the
9496 pessimistic default if needed.
9498 It is customary to report unexpected failures with
9499 @code{AC_MSG_FAILURE}.
9500 @end defmac
9502 @command{autoconf} prints a warning message when creating
9503 @command{configure} each time it encounters a call to
9504 @code{AC_RUN_IFELSE} with no @var{action-if-cross-compiling} argument
9505 given.  If you are not concerned about users configuring your package
9506 for cross-compilation, you may ignore the warning.  A few of the macros
9507 distributed with Autoconf produce this warning message; but if this is a
9508 problem for you, please report it as a bug, along with an appropriate
9509 pessimistic guess to use instead.
9511 To configure for cross-compiling you can also choose a value for those
9512 parameters based on the canonical system name (@pxref{Manual
9513 Configuration}).  Alternatively, set up a test results cache file with
9514 the correct values for the host system (@pxref{Caching Results}).
9516 @ovindex cross_compiling
9517 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
9518 in other macros, including a few of the ones that come with Autoconf,
9519 you can test whether the shell variable @code{cross_compiling} is set to
9520 @samp{yes}, and then use an alternate method to get the results instead
9521 of calling the macros.
9523 It is also permissible to temporarily assign to @code{cross_compiling}
9524 in order to force tests to behave as though they are in a
9525 cross-compilation environment, particularly since this provides a way to
9526 test your @var{action-if-cross-compiling} even when you are not using a
9527 cross-compiler.
9529 @example
9530 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
9531 # to use the slow link-only method
9532 save_cross_compiling=$cross_compiling
9533 cross_compiling=yes
9534 AC_COMPUTE_INT([@dots{}])
9535 cross_compiling=$save_cross_compiling
9536 @end example
9538 A C or C++ runtime test should be portable.
9539 @xref{Portable C and C++}.
9541 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
9542 function: the given status code is used to determine the success of the test
9543 (status is @code{0}) or its failure (status is different than @code{0}), as
9544 explained above.  It must be noted that data output through the standard output
9545 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
9546 Therefore, if a test must output configuration information, it is recommended
9547 to create and to output data into the temporary file named @file{conftest.out},
9548 using the functions of module @code{file}.  The @code{conftest.out} file is
9549 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
9550 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
9551 macro is:
9553 @example
9554 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
9555 AC_ERLANG_NEED_ERL
9556 AC_LANG(Erlang)
9557 AC_RUN_IFELSE(
9558   [AC_LANG_PROGRAM([], [dnl
9559     file:write_file("conftest.out", code:lib_dir()),
9560     halt(0)])],
9561   [echo "code:lib_dir() returned: `cat conftest.out`"],
9562   [AC_MSG_FAILURE([test Erlang program execution failed])])
9563 @end example
9566 @node Systemology
9567 @section Systemology
9568 @cindex Systemology
9570 This section aims at presenting some systems and pointers to
9571 documentation.  It may help you addressing particular problems reported
9572 by users.
9574 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
9575 derived from the
9576 @uref{http://@/www.bell-labs.com/@/usr/@/dmr/@/www/@/hist.html, Unix
9577 operating system}.
9579 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
9580 contains a table correlating the features of various Posix-conforming
9581 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
9582 simplified diagram of how many Unix systems were derived from each
9583 other.
9585 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
9586 provides some variants of traditional implementations of Unix utilities.
9588 @table @asis
9589 @item Darwin
9590 @cindex Darwin
9591 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
9592 case-preserving, but case insensitive.  This can cause nasty problems,
9593 since for instance the installation attempt for a package having an
9594 @file{INSTALL} file can result in @samp{make install} report that
9595 nothing was to be done!
9597 That's all dependent on whether the file system is a UFS (case
9598 sensitive) or HFS+ (case preserving).  By default Apple wants you to
9599 install the OS on HFS+.  Unfortunately, there are some pieces of
9600 software which really need to be built on UFS@.  We may want to rebuild
9601 Darwin to have both UFS and HFS+ available (and put the /local/build
9602 tree on the UFS).
9604 @item QNX 4.25
9605 @cindex QNX 4.25
9606 @c FIXME: Please, if you feel like writing something more precise,
9607 @c it'd be great.  In particular, I can't understand the difference with
9608 @c QNX Neutrino.
9609 QNX is a realtime operating system running on Intel architecture
9610 meant to be scalable from the small embedded systems to the hundred
9611 processor super-computer.  It claims to be Posix certified.  More
9612 information is available on the
9613 @uref{http://@/www.qnx.com/, QNX home page}.
9615 @item Tru64
9616 @cindex Tru64
9617 @uref{http://@/h30097.www3.hp.com/@/docs/,
9618 Documentation of several versions of Tru64} is available in different
9619 formats.
9621 @item Unix version 7
9622 @cindex Unix version 7
9623 @cindex V7
9624 Officially this was called the ``Seventh Edition'' of ``the UNIX
9625 time-sharing system'' but we use the more-common name ``Unix version 7''.
9626 Documentation is available in the
9627 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
9628 Previous versions of Unix are called ``Unix version 6'', etc., but
9629 they were not as widely used.
9630 @end table
9633 @node Multiple Cases
9634 @section Multiple Cases
9636 Some operations are accomplished in several possible ways, depending on
9637 the OS variant.  Checking for them essentially requires a ``case
9638 statement''.  Autoconf does not directly provide one; however, it is
9639 easy to simulate by using a shell variable to keep track of whether a
9640 way to perform the operation has been found yet.
9642 Here is an example that uses the shell variable @code{fstype} to keep
9643 track of whether the remaining cases need to be checked.  Note that
9644 since the value of @code{fstype} is under our control, we don't have to
9645 use the longer @samp{test "x$fstype" = xno}.
9647 @example
9648 @group
9649 AC_MSG_CHECKING([how to get file system type])
9650 fstype=no
9651 # The order of these tests is important.
9652 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
9653 #include <sys/fstyp.h>]])],
9654                   [AC_DEFINE([FSTYPE_STATVFS], [1],
9655                      [Define if statvfs exists.])
9656                    fstype=SVR4])
9657 if test $fstype = no; then
9658   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9659 #include <sys/fstyp.h>]])],
9660                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
9661                      [Define if USG statfs.])
9662                    fstype=SVR3])
9664 if test $fstype = no; then
9665   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
9666 #include <sys/vmount.h>]])]),
9667                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
9668                      [Define if AIX statfs.])
9669                    fstype=AIX])
9671 # (more cases omitted here)
9672 AC_MSG_RESULT([$fstype])
9673 @end group
9674 @end example
9676 @c ====================================================== Results of Tests.
9678 @node Results
9679 @chapter Results of Tests
9681 Once @command{configure} has determined whether a feature exists, what can
9682 it do to record that information?  There are four sorts of things it can
9683 do: define a C preprocessor symbol, set a variable in the output files,
9684 save the result in a cache file for future @command{configure} runs, and
9685 print a message letting the user know the result of the test.
9687 @menu
9688 * Defining Symbols::            Defining C preprocessor symbols
9689 * Setting Output Variables::    Replacing variables in output files
9690 * Special Chars in Variables::  Characters to beware of in variables
9691 * Caching Results::             Speeding up subsequent @command{configure} runs
9692 * Printing Messages::           Notifying @command{configure} users
9693 @end menu
9695 @node Defining Symbols
9696 @section Defining C Preprocessor Symbols
9698 A common action to take in response to a feature test is to define a C
9699 preprocessor symbol indicating the results of the test.  That is done by
9700 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
9702 By default, @code{AC_OUTPUT} places the symbols defined by these macros
9703 into the output variable @code{DEFS}, which contains an option
9704 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
9705 Autoconf version 1, there is no variable @code{DEFS} defined while
9706 @command{configure} is running.  To check whether Autoconf macros have
9707 already defined a certain C preprocessor symbol, test the value of the
9708 appropriate cache variable, as in this example:
9710 @example
9711 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
9712                           [Define if vprintf exists.])])
9713 if test "x$ac_cv_func_vprintf" != xyes; then
9714   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
9715                             [Define if _doprnt exists.])])
9717 @end example
9719 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
9720 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
9721 correct values into @code{#define} statements in a template file.
9722 @xref{Configuration Headers}, for more information about this kind of
9723 output.
9725 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
9726 @defmacx AC_DEFINE (@var{variable})
9727 @cvindex @var{variable}
9728 @acindex{DEFINE}
9729 Define @var{variable} to @var{value} (verbatim), by defining a C
9730 preprocessor macro for @var{variable}.  @var{variable} should be a C
9731 identifier, optionally suffixed by a parenthesized argument list to
9732 define a C preprocessor macro with arguments.  The macro argument list,
9733 if present, should be a comma-separated list of C identifiers, possibly
9734 terminated by an ellipsis @samp{...} if C99-or-later syntax is employed.
9735 @var{variable} should not contain comments, white space, trigraphs,
9736 backslash-newlines, universal character names, or non-ASCII
9737 characters.
9739 @var{value} may contain backslash-escaped newlines, which will be
9740 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
9741 via @code{@@DEFS@@} (with no effect on the compilation, since the
9742 preprocessor sees only one line in the first place).  @var{value} should
9743 not contain raw newlines.  If you are not using
9744 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
9745 characters, as @command{make} tends to eat them.  To use a shell
9746 variable, use @code{AC_DEFINE_UNQUOTED} instead.
9748 @var{description} is only useful if you are using
9749 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
9750 the generated @file{config.h.in} as the comment before the macro define.
9751 The following example defines the C preprocessor variable
9752 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
9754 @example
9755 AC_DEFINE([EQUATION], ["$a > $b"],
9756   [Equation string.])
9757 @end example
9759 If neither @var{value} nor @var{description} are given, then
9760 @var{value} defaults to 1 instead of to the empty string.  This is for
9761 backwards compatibility with older versions of Autoconf, but this usage
9762 is obsolescent and may be withdrawn in future versions of Autoconf.
9764 If the @var{variable} is a literal string, it is passed to
9765 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
9767 If multiple @code{AC_DEFINE} statements are executed for the same
9768 @var{variable} name (not counting any parenthesized argument list),
9769 the last one wins.
9770 @end defmac
9772 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
9773 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
9774 @acindex{DEFINE_UNQUOTED}
9775 @cvindex @var{variable}
9776 Like @code{AC_DEFINE}, but three shell expansions are
9777 performed---once---on @var{variable} and @var{value}: variable expansion
9778 (@samp{$}), command substitution (@samp{`}), and backslash escaping
9779 (@samp{\}), as if in an unquoted here-document.  Single and double quote
9780 characters in the value have no
9781 special meaning.  Use this macro instead of @code{AC_DEFINE} when
9782 @var{variable} or @var{value} is a shell variable.  Examples:
9784 @example
9785 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
9786   [Configuration machine file.])
9787 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
9788   [getgroups return type.])
9789 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
9790   [Translated header name.])
9791 @end example
9792 @end defmac
9794 Due to a syntactical bizarreness of the Bourne shell, do not use
9795 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
9796 calls from other macro calls or shell code; that can cause syntax errors
9797 in the resulting @command{configure} script.  Use either blanks or
9798 newlines.  That is, do this:
9800 @example
9801 AC_CHECK_HEADER([elf.h],
9802   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
9803 @end example
9805 @noindent
9806 or this:
9808 @example
9809 AC_CHECK_HEADER([elf.h],
9810   [AC_DEFINE([SVR4], [1], [System V Release 4])
9811    LIBS="-lelf $LIBS"])
9812 @end example
9814 @noindent
9815 instead of this:
9817 @example
9818 AC_CHECK_HEADER([elf.h],
9819   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
9820 @end example
9822 @node Setting Output Variables
9823 @section Setting Output Variables
9824 @cindex Output variables
9826 Another way to record the results of tests is to set @dfn{output
9827 variables}, which are shell variables whose values are substituted into
9828 files that @command{configure} outputs.  The two macros below create new
9829 output variables.  @xref{Preset Output Variables}, for a list of output
9830 variables that are always available.
9832 @defmac AC_SUBST (@var{variable}, @ovar{value})
9833 @acindex{SUBST}
9834 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
9835 substitute the variable @var{variable} into output files (typically one
9836 or more makefiles).  This means that @code{AC_OUTPUT}
9837 replaces instances of @samp{@@@var{variable}@@} in input files with the
9838 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
9839 is called.  The value can contain any non-@code{NUL} character, including
9840 newline.  If you are using Automake 1.11 or newer, for newlines in values
9841 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
9842 @command{automake} from adding a line @code{@var{variable} =
9843 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
9844 Automake, automake, Other things Automake recognizes}).
9846 Variable occurrences should not overlap: e.g., an input file should
9847 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
9848 are variable names.
9849 The substituted value is not rescanned for more output variables;
9850 occurrences of @samp{@@@var{variable}@@} in the value are inserted
9851 literally into the output file.  (The algorithm uses the special marker
9852 @code{|#_!!_#|} internally, so neither the substituted value nor the
9853 output file may contain @code{|#_!!_#|}.)
9855 If @var{value} is given, in addition assign it to @var{variable}.
9857 The string @var{variable} is passed to @code{m4_pattern_allow}
9858 (@pxref{Forbidden Patterns}).  @var{variable} is not further expanded,
9859 even if there is another macro by the same name.
9860 @end defmac
9862 @defmac AC_SUBST_FILE (@var{variable})
9863 @acindex{SUBST_FILE}
9864 Another way to create an output variable from a shell variable.  Make
9865 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
9866 named by shell variable @var{variable} into output files.  This means
9867 that @code{AC_OUTPUT} replaces instances of
9868 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
9869 with the contents of the file that the shell variable @var{variable}
9870 names when @code{AC_OUTPUT} is called.  Set the variable to
9871 @file{/dev/null} for cases that do not have a file to insert.
9872 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
9873 line by itself, optionally surrounded by spaces and tabs.  The
9874 substitution replaces the whole line, including the spaces, tabs, and
9875 the terminating newline.
9877 This macro is useful for inserting makefile fragments containing
9878 special dependencies or other @command{make} directives for particular host
9879 or target types into makefiles.  For example, @file{configure.ac}
9880 could contain:
9882 @example
9883 AC_SUBST_FILE([host_frag])
9884 host_frag=$srcdir/conf/sun4.mh
9885 @end example
9887 @noindent
9888 and then a @file{Makefile.in} could contain:
9890 @example
9891 @@host_frag@@
9892 @end example
9894 The string @var{variable} is passed to @code{m4_pattern_allow}
9895 (@pxref{Forbidden Patterns}).
9896 @end defmac
9898 @cindex Precious Variable
9899 @cindex Variable, Precious
9900 Running @command{configure} in varying environments can be extremely
9901 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
9902 ./configure}, then the cache, @file{config.h}, and many other output
9903 files depend upon @command{bizarre-cc} being the C compiler.  If
9904 for some reason the user runs @command{./configure} again, or if it is
9905 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
9906 and @pxref{config.status Invocation}), then the configuration can be
9907 inconsistent, composed of results depending upon two different
9908 compilers.
9910 Environment variables that affect this situation, such as @samp{CC}
9911 above, are called @dfn{precious variables}, and can be declared as such
9912 by @code{AC_ARG_VAR}.
9914 @defmac AC_ARG_VAR (@var{variable}, @var{description})
9915 @acindex{ARG_VAR}
9916 Declare @var{variable} is a precious variable, and include its
9917 @var{description} in the variable section of @samp{./configure --help}.
9919 Being precious means that
9920 @itemize @minus
9921 @item
9922 @var{variable} is substituted via @code{AC_SUBST}.
9924 @item
9925 The value of @var{variable} when @command{configure} was launched is
9926 saved in the cache, including if it was not specified on the command
9927 line but via the environment.  Indeed, while @command{configure} can
9928 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
9929 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
9930 which, unfortunately, is what most users do.
9932 We emphasize that it is the @emph{initial} value of @var{variable} which
9933 is saved, not that found during the execution of @command{configure}.
9934 Indeed, specifying @samp{./configure FOO=foo} and letting
9935 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
9936 different things.
9938 @item
9939 @var{variable} is checked for consistency between two
9940 @command{configure} runs.  For instance:
9942 @example
9943 $ @kbd{./configure --silent --config-cache}
9944 $ @kbd{CC=cc ./configure --silent --config-cache}
9945 configure: error: 'CC' was not set in the previous run
9946 configure: error: changes in the environment can compromise \
9947 the build
9948 configure: error: run 'make distclean' and/or \
9949 'rm config.cache' and start over
9950 @end example
9952 @noindent
9953 and similarly if the variable is unset, or if its content is changed.
9954 If the content has white space changes only, then the error is degraded
9955 to a warning only, but the old value is reused.
9957 @item
9958 @var{variable} is kept during automatic reconfiguration
9959 (@pxref{config.status Invocation}) as if it had been passed as a command
9960 line argument, including when no cache is used:
9962 @example
9963 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
9964 $ @kbd{./config.status --recheck}
9965 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
9966   CC=/usr/bin/cc  --no-create --no-recursion
9967 @end example
9968 @end itemize
9969 @end defmac
9971 @node Special Chars in Variables
9972 @section Special Characters in Output Variables
9973 @cindex Output variables, special characters in
9975 Many output variables are intended to be evaluated both by
9976 @command{make} and by the shell.  Some characters are expanded
9977 differently in these two contexts, so to avoid confusion these
9978 variables' values should not contain any of the following characters:
9980 @example
9981 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
9982 @end example
9984 Also, these variables' values should neither contain newlines, nor start
9985 with @samp{~}, nor contain white space or @samp{:} immediately followed
9986 by @samp{~}.  The values can contain nonempty sequences of white space
9987 characters like tabs and spaces, but each such sequence might
9988 arbitrarily be replaced by a single space during substitution.
9990 These restrictions apply both to the values that @command{configure}
9991 computes, and to the values set directly by the user.  For example, the
9992 following invocations of @command{configure} are problematic, since they
9993 attempt to use special characters within @code{CPPFLAGS} and white space
9994 within @code{$(srcdir)}:
9996 @example
9997 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
9999 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
10000 @end example
10002 @node Caching Results
10003 @section Caching Results
10004 @cindex Cache
10006 To avoid checking for the same features repeatedly in various
10007 @command{configure} scripts (or in repeated runs of one script),
10008 @command{configure} can optionally save the results of many checks in a
10009 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
10010 runs with caching enabled and finds a cache file, it reads the results
10011 of previous runs from the cache and avoids rerunning those checks.  As a
10012 result, @command{configure} can then run much faster than if it had to
10013 perform all of the checks every time.
10015 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
10016 @acindex{CACHE_VAL}
10017 Ensure that the results of the check identified by @var{cache-id} are
10018 available.  If the results of the check were in the cache file that was
10019 read, and @command{configure} was not given the @option{--quiet} or
10020 @option{--silent} option, print a message saying that the result was
10021 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
10022 the shell commands are run to determine the value, the value is
10023 saved in the cache file just before @command{configure} creates its output
10024 files.  @xref{Cache Variable Names}, for how to choose the name of the
10025 @var{cache-id} variable.
10027 The @var{commands-to-set-it} @emph{must have no side effects} except for
10028 setting the variable @var{cache-id}, see below.
10029 @end defmac
10031 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
10032   @var{commands-to-set-it})
10033 @acindex{CACHE_CHECK}
10034 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
10035 messages.  This macro provides a convenient shorthand for the most
10036 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
10037 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
10038 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
10040 The @var{commands-to-set-it} @emph{must have no side effects} except for
10041 setting the variable @var{cache-id}, see below.
10042 @end defmac
10044 It is common to find buggy macros using @code{AC_CACHE_VAL} or
10045 @code{AC_CACHE_CHECK}, because people are tempted to call
10046 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
10047 @emph{follows} the call to @code{AC_CACHE_VAL} should call
10048 @code{AC_DEFINE}, by examining the value of the cache variable.  For
10049 instance, the following macro is broken:
10051 @example
10052 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10053 @group
10054 AC_DEFUN([AC_SHELL_TRUE],
10055 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10056                 [my_cv_shell_true_works=no
10057                  (true) 2>/dev/null && my_cv_shell_true_works=yes
10058                  if test "x$my_cv_shell_true_works" = xyes; then
10059                    AC_DEFINE([TRUE_WORKS], [1],
10060                              [Define if 'true(1)' works properly.])
10061                  fi])
10063 @end group
10064 @end example
10066 @noindent
10067 This fails if the cache is enabled: the second time this macro is run,
10068 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
10071 @example
10072 @c If you change this example, adjust tests/base.at:AC_CACHE_CHECK.
10073 @group
10074 AC_DEFUN([AC_SHELL_TRUE],
10075 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
10076                 [my_cv_shell_true_works=no
10077                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
10078  if test "x$my_cv_shell_true_works" = xyes; then
10079    AC_DEFINE([TRUE_WORKS], [1],
10080              [Define if 'true(1)' works properly.])
10081  fi
10083 @end group
10084 @end example
10086 Also, @var{commands-to-set-it} should not print any messages, for
10087 example with @code{AC_MSG_CHECKING}; do that before calling
10088 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
10089 the results of the check are retrieved from the cache or determined by
10090 running the shell commands.
10092 @menu
10093 * Cache Variable Names::        Shell variables used in caches
10094 * Cache Files::                 Files @command{configure} uses for caching
10095 * Cache Checkpointing::         Loading and saving the cache file
10096 @end menu
10098 @node Cache Variable Names
10099 @subsection Cache Variable Names
10100 @cindex Cache variable
10102 The names of cache variables should have the following format:
10104 @example
10105 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
10106 @end example
10108 @noindent
10109 for example, @samp{ac_cv_header_stat_broken} or
10110 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
10112 @table @asis
10113 @item @var{package-prefix}
10114 An abbreviation for your package or organization; the same prefix you
10115 begin local Autoconf macros with, except lowercase by convention.
10116 For cache values used by the distributed Autoconf macros, this value is
10117 @samp{ac}.
10119 @item @code{_cv_}
10120 Indicates that this shell variable is a cache value.  This string
10121 @emph{must} be present in the variable name, including the leading
10122 underscore.
10124 @item @var{value-type}
10125 A convention for classifying cache values, to produce a rational naming
10126 system.  The values used in Autoconf are listed in @ref{Macro Names}.
10128 @item @var{specific-value}
10129 Which member of the class of cache values this test applies to.
10130 For example, which function (@samp{alloca}), program (@samp{gcc}), or
10131 output variable (@samp{INSTALL}).
10133 @item @var{additional-options}
10134 Any particular behavior of the specific member that this test applies to.
10135 For example, @samp{broken} or @samp{set}.  This part of the name may
10136 be omitted if it does not apply.
10137 @end table
10139 The values assigned to cache variables may not contain newlines.
10140 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
10141 names of files or functions; so this is not an important restriction.
10142 @ref{Cache Variable Index} for an index of cache variables with
10143 documented semantics.
10146 @node Cache Files
10147 @subsection Cache Files
10149 A cache file is a shell script that caches the results of configure
10150 tests run on one system so they can be shared between configure scripts
10151 and configure runs.  It is not useful on other systems.  If its contents
10152 are invalid for some reason, the user may delete or edit it, or override
10153 documented cache variables on the @command{configure} command line.
10155 By default, @command{configure} uses no cache file,
10156 to avoid problems caused by accidental
10157 use of stale cache files.
10159 To enable caching, @command{configure} accepts @option{--config-cache} (or
10160 @option{-C}) to cache results in the file @file{config.cache}.
10161 Alternatively, @option{--cache-file=@var{file}} specifies that
10162 @var{file} be the cache file.  The cache file is created if it does not
10163 exist already.  When @command{configure} calls @command{configure} scripts in
10164 subdirectories, it uses the @option{--cache-file} argument so that they
10165 share the same cache.  @xref{Subdirectories}, for information on
10166 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
10168 @file{config.status} only pays attention to the cache file if it is
10169 given the @option{--recheck} option, which makes it rerun
10170 @command{configure}.
10172 It is wrong to try to distribute cache files for particular system types.
10173 There is too much room for error in doing that, and too much
10174 administrative overhead in maintaining them.  For any features that
10175 can't be guessed automatically, use the standard method of the canonical
10176 system type and linking files (@pxref{Manual Configuration}).
10178 The site initialization script can specify a site-wide cache file to
10179 use, instead of the usual per-program cache.  In this case, the cache
10180 file gradually accumulates information whenever someone runs a new
10181 @command{configure} script.  (Running @command{configure} merges the new cache
10182 results with the existing cache file.)  This may cause problems,
10183 however, if the system configuration (e.g., the installed libraries or
10184 compilers) changes and the stale cache file is not deleted.
10186 If @command{configure} is interrupted at the right time when it updates
10187 a cache file outside of the build directory where the @command{configure}
10188 script is run, it may leave behind a temporary file named after the
10189 cache file with digits following it.  You may safely delete such a file.
10192 @node Cache Checkpointing
10193 @subsection Cache Checkpointing
10195 If your configure script, or a macro called from @file{configure.ac}, happens
10196 to abort the configure process, it may be useful to checkpoint the cache
10197 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
10198 reduces the amount of time it takes to rerun the configure script with
10199 (hopefully) the error that caused the previous abort corrected.
10201 @c FIXME: Do we really want to document this guy?
10202 @defmac AC_CACHE_LOAD
10203 @acindex{CACHE_LOAD}
10204 Loads values from existing cache file, or creates a new cache file if a
10205 cache file is not found.  Called automatically from @code{AC_INIT}.
10206 @end defmac
10208 @defmac AC_CACHE_SAVE
10209 @acindex{CACHE_SAVE}
10210 Flushes all cached values to the cache file.  Called automatically from
10211 @code{AC_OUTPUT}, but it can be quite useful to call
10212 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
10213 @end defmac
10215 For instance:
10217 @example
10218 @r{ @dots{} AC_INIT, etc. @dots{}}
10219 @group
10220 # Checks for programs.
10221 AC_PROG_CC
10222 AC_PROG_AWK
10223 @r{ @dots{} more program checks @dots{}}
10224 AC_CACHE_SAVE
10225 @end group
10227 @group
10228 # Checks for libraries.
10229 AC_CHECK_LIB([nsl], [gethostbyname])
10230 AC_CHECK_LIB([socket], [connect])
10231 @r{ @dots{} more lib checks @dots{}}
10232 AC_CACHE_SAVE
10233 @end group
10235 @group
10236 # Might abort@dots{}
10237 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
10238 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
10239 @end group
10240 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
10241 @end example
10243 @node Printing Messages
10244 @section Printing Messages
10245 @cindex Messages, from @command{configure}
10247 @command{configure} scripts need to give users running them several kinds
10248 of information.  The following macros print messages in ways appropriate
10249 for each kind.  The arguments to all of them get enclosed in shell
10250 double quotes, so the shell performs variable and back-quote
10251 substitution on them.
10253 These macros are all wrappers around the @command{echo} shell command.
10254 They direct output to the appropriate file descriptor (@pxref{File
10255 Descriptor Macros}).
10256 @command{configure} scripts should rarely need to run @command{echo} directly
10257 to print messages for the user.  Using these macros makes it easy to
10258 change how and when each kind of message is printed; such changes need
10259 only be made to the macro definitions and all the callers change
10260 automatically.
10262 To diagnose static issues, i.e., when @command{autoconf} is run, see
10263 @ref{Diagnostic Macros}.
10265 @defmac AC_MSG_CHECKING (@var{feature-description})
10266 @acindex{MSG_CHECKING}
10267 Notify the user that @command{configure} is checking for a particular
10268 feature.  This macro prints a message that starts with @samp{checking }
10269 and ends with @samp{...} and no newline.  It must be followed by a call
10270 to @code{AC_MSG_RESULT} to print the result of the check and the
10271 newline.  The @var{feature-description} should be something like
10272 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
10273 _Alignof}.
10275 This macro prints nothing if @command{configure} is run with the
10276 @option{--quiet} or @option{--silent} option.
10277 @end defmac
10279 @anchor{AC_MSG_RESULT}
10280 @defmac AC_MSG_RESULT (@var{result-description})
10281 @acindex{MSG_RESULT}
10282 Notify the user of the results of a check.  @var{result-description} is
10283 almost always the value of the cache variable for the check, typically
10284 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
10285 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
10286 the completion of the message printed by the call to
10287 @code{AC_MSG_CHECKING}.
10289 This macro prints nothing if @command{configure} is run with the
10290 @option{--quiet} or @option{--silent} option.
10291 @end defmac
10293 @anchor{AC_MSG_NOTICE}
10294 @defmac AC_MSG_NOTICE (@var{message})
10295 @acindex{MSG_NOTICE}
10296 Deliver the @var{message} to the user.  It is useful mainly to print a
10297 general description of the overall purpose of a group of feature checks,
10298 e.g.,
10300 @example
10301 AC_MSG_NOTICE([checking if stack overflow is detectable])
10302 @end example
10304 This macro prints nothing if @command{configure} is run with the
10305 @option{--quiet} or @option{--silent} option.
10306 @end defmac
10308 @anchor{AC_MSG_ERROR}
10309 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
10310 @acindex{MSG_ERROR}
10311 Notify the user of an error that prevents @command{configure} from
10312 completing.  This macro prints an error message to the standard error
10313 output and exits @command{configure} with @var{exit-status} (@samp{$?}
10314 by default, except that @samp{0} is converted to @samp{1}).
10315 @var{error-description} should be something like @samp{invalid value
10316 $HOME for \$HOME}.
10318 The @var{error-description} should start with a lower-case letter, and
10319 ``cannot'' is preferred to ``can't''.
10320 @end defmac
10322 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
10323 @acindex{MSG_FAILURE}
10324 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
10325 prevents @command{configure} from completing @emph{and} that additional
10326 details are provided in @file{config.log}.  This is typically used when
10327 abnormal results are found during a compilation.
10328 @end defmac
10330 @anchor{AC_MSG_WARN}
10331 @defmac AC_MSG_WARN (@var{problem-description})
10332 @acindex{MSG_WARN}
10333 Notify the @command{configure} user of a possible problem.  This macro
10334 prints the message to the standard error output; @command{configure}
10335 continues running afterward, so macros that call @code{AC_MSG_WARN} should
10336 provide a default (back-up) behavior for the situations they warn about.
10337 @var{problem-description} should be something like @samp{ln -s seems to
10338 make hard links}.
10339 @end defmac
10343 @c ====================================================== Programming in M4.
10345 @node Programming in M4
10346 @chapter Programming in M4
10347 @cindex M4
10349 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
10350 convenient macros for pure M4 programming, and @dfn{M4sh}, which
10351 provides macros dedicated to shell script generation.
10353 As of this version of Autoconf, these two layers still contain
10354 experimental macros, whose interface might change in the future.  As a
10355 matter of fact, @emph{anything that is not documented must not be used}.
10357 @menu
10358 * M4 Quotation::                Protecting macros from unwanted expansion
10359 * Using autom4te::              The Autoconf executables backbone
10360 * Programming in M4sugar::      Convenient pure M4 macros
10361 * Debugging via autom4te::      Figuring out what M4 was doing
10362 @end menu
10364 @node M4 Quotation
10365 @section M4 Quotation
10366 @cindex M4 quotation
10367 @cindex quotation
10369 The most common problem with existing macros is an improper quotation.
10370 This section, which users of Autoconf can skip, but which macro writers
10371 @emph{must} read, first justifies the quotation scheme that was chosen
10372 for Autoconf and then ends with a rule of thumb.  Understanding the
10373 former helps one to follow the latter.
10375 @menu
10376 * Active Characters::           Characters that change the behavior of M4
10377 * One Macro Call::              Quotation and one macro call
10378 * Quoting and Parameters::      M4 vs. shell parameters
10379 * Quotation and Nested Macros::  Macros calling macros
10380 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
10381 * Quadrigraphs::                Another way to escape special characters
10382 * Balancing Parentheses::       Dealing with unbalanced parentheses
10383 * Quotation Rule Of Thumb::     One parenthesis, one quote
10384 @end menu
10386 @node Active Characters
10387 @subsection Active Characters
10389 To fully understand where proper quotation is important, you first need
10390 to know what the special characters are in Autoconf: @samp{#} introduces
10391 a comment inside which no macro expansion is performed, @samp{,}
10392 separates arguments, @samp{[} and @samp{]} are the quotes
10393 themselves@footnote{By itself, M4 uses @samp{`} and @samp{'}; it is the
10394 M4sugar layer that sets up the preferred quotes of @samp{[} and @samp{]}.},
10395 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
10396 @samp{$} inside a macro definition.
10398 In order to understand the delicate case of macro calls, we first have
10399 to present some obvious failures.  Below they are ``obvious-ified'',
10400 but when you find them in real life, they are usually in disguise.
10402 Comments, introduced by a hash and running up to the newline, are opaque
10403 tokens to the top level: active characters are turned off, and there is
10404 no macro expansion:
10406 @example
10407 # define([def], ine)
10408 @result{}# define([def], ine)
10409 @end example
10411 Each time there can be a macro expansion, there is a quotation
10412 expansion, i.e., one level of quotes is stripped:
10414 @example
10415 int tab[10];
10416 @result{}int tab10;
10417 [int tab[10];]
10418 @result{}int tab[10];
10419 @end example
10421 Without this in mind, the reader might try hopelessly to use her macro
10422 @code{array}:
10424 @example
10425 define([array], [int tab[10];])
10426 array
10427 @result{}int tab10;
10428 [array]
10429 @result{}array
10430 @end example
10432 @noindent
10433 How can you correctly output the intended results@footnote{Using
10434 @code{defn}.}?
10437 @node One Macro Call
10438 @subsection One Macro Call
10440 Let's proceed on the interaction between active characters and macros
10441 with this small macro, which just returns its first argument:
10443 @example
10444 define([car], [$1])
10445 @end example
10447 @noindent
10448 The two pairs of quotes above are not part of the arguments of
10449 @code{define}; rather, they are understood by the top level when it
10450 tries to find the arguments of @code{define}.  Therefore, assuming
10451 @code{car} is not already defined, it is equivalent to write:
10453 @example
10454 define(car, $1)
10455 @end example
10457 @noindent
10458 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
10459 quotes, it is bad practice for Autoconf macros which must both be more
10460 robust and also advocate perfect style.
10462 At the top level, there are only two possibilities: either you
10463 quote or you don't:
10465 @example
10466 car(foo, bar, baz)
10467 @result{}foo
10468 [car(foo, bar, baz)]
10469 @result{}car(foo, bar, baz)
10470 @end example
10472 Let's pay attention to the special characters:
10474 @example
10475 car(#)
10476 @error{}EOF in argument list
10477 @end example
10479 The closing parenthesis is hidden in the comment; with a hypothetical
10480 quoting, the top level understood it this way:
10482 @example
10483 car([#)]
10484 @end example
10486 @noindent
10487 Proper quotation, of course, fixes the problem:
10489 @example
10490 car([#])
10491 @result{}#
10492 @end example
10494 Here are more examples:
10496 @example
10497 car(foo, bar)
10498 @result{}foo
10499 car([foo, bar])
10500 @result{}foo, bar
10501 car((foo, bar))
10502 @result{}(foo, bar)
10503 car([(foo], [bar)])
10504 @result{}(foo
10505 define([a], [b])
10506 @result{}
10507 car(a)
10508 @result{}b
10509 car([a])
10510 @result{}b
10511 car([[a]])
10512 @result{}a
10513 car([[[a]]])
10514 @result{}[a]
10515 @end example
10517 @node Quoting and Parameters
10518 @subsection Quoting and Parameters
10520 When M4 encounters @samp{$} within a macro definition, followed
10521 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
10522 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
10523 expansion.  This happens regardless of how many layers of quotes the
10524 parameter expansion is nested within, or even if it occurs in text that
10525 will be rescanned as a comment.
10527 @example
10528 define([none], [$1])
10529 @result{}
10530 define([one], [[$1]])
10531 @result{}
10532 define([two], [[[$1]]])
10533 @result{}
10534 define([comment], [# $1])
10535 @result{}
10536 define([active], [ACTIVE])
10537 @result{}
10538 none([active])
10539 @result{}ACTIVE
10540 one([active])
10541 @result{}active
10542 two([active])
10543 @result{}[active]
10544 comment([active])
10545 @result{}# active
10546 @end example
10548 On the other hand, since autoconf generates shell code, you often want
10549 to output shell variable expansion, rather than performing M4 parameter
10550 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
10551 from the next character in the definition of your macro.  If the macro
10552 definition occurs in single-quoted text, then insert another level of
10553 quoting; if the usage is already inside a double-quoted string, then
10554 split it into concatenated strings.
10556 @example
10557 define([single], [a single-quoted $[]1 definition])
10558 @result{}
10559 define([double], [[a double-quoted $][1 definition]])
10560 @result{}
10561 single
10562 @result{}a single-quoted $1 definition
10563 double
10564 @result{}a double-quoted $1 definition
10565 @end example
10567 Posix states that M4 implementations are free to provide implementation
10568 extensions when @samp{$@{} is encountered in a macro definition.
10569 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
10570 extensions that will be available in the future GNU M4 2.0,
10571 but guarantees that all other instances of @samp{$@{} will be output
10572 literally.  Therefore, this idiom can also be used to output shell code
10573 parameter references:
10575 @example
10576 define([first], [$@{1@}])first
10577 @result{}$@{1@}
10578 @end example
10580 Posix also states that @samp{$11} should expand to the first parameter
10581 concatenated with a literal @samp{1}, although some versions of
10582 GNU M4 expand the eleventh parameter instead.  For
10583 portability, you should only use single-digit M4 parameter expansion.
10585 With this in mind, we can explore the cases where macros invoke
10586 macros@enddots{}
10588 @node Quotation and Nested Macros
10589 @subsection Quotation and Nested Macros
10591 The examples below use the following macros:
10593 @example
10594 define([car], [$1])
10595 define([active], [ACT, IVE])
10596 define([array], [int tab[10]])
10597 @end example
10599 Each additional embedded macro call introduces other possible
10600 interesting quotations:
10602 @example
10603 car(active)
10604 @result{}ACT
10605 car([active])
10606 @result{}ACT, IVE
10607 car([[active]])
10608 @result{}active
10609 @end example
10611 In the first case, the top level looks for the arguments of @code{car},
10612 and finds @samp{active}.  Because M4 evaluates its arguments
10613 before applying the macro, @samp{active} is expanded, which results in:
10615 @example
10616 car(ACT, IVE)
10617 @result{}ACT
10618 @end example
10620 @noindent
10621 In the second case, the top level gives @samp{active} as first and only
10622 argument of @code{car}, which results in:
10624 @example
10625 active
10626 @result{}ACT, IVE
10627 @end example
10629 @noindent
10630 i.e., the argument is evaluated @emph{after} the macro that invokes it.
10631 In the third case, @code{car} receives @samp{[active]}, which results in:
10633 @example
10634 [active]
10635 @result{}active
10636 @end example
10638 @noindent
10639 exactly as we already saw above.
10641 The example above, applied to a more realistic example, gives:
10643 @example
10644 car(int tab[10];)
10645 @result{}int tab10;
10646 car([int tab[10];])
10647 @result{}int tab10;
10648 car([[int tab[10];]])
10649 @result{}int tab[10];
10650 @end example
10652 @noindent
10653 Huh?  The first case is easily understood, but why is the second wrong,
10654 and the third right?  To understand that, you must know that after
10655 M4 expands a macro, the resulting text is immediately subjected
10656 to macro expansion and quote removal.  This means that the quote removal
10657 occurs twice---first before the argument is passed to the @code{car}
10658 macro, and second after the @code{car} macro expands to the first
10659 argument.
10661 As the author of the Autoconf macro @code{car}, you then consider it to
10662 be incorrect that your users have to double-quote the arguments of
10663 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
10664 quoted car:
10666 @example
10667 define([qar], [[$1]])
10668 @end example
10670 @noindent
10671 and check that @code{qar} is properly fixed:
10673 @example
10674 qar([int tab[10];])
10675 @result{}int tab[10];
10676 @end example
10678 @noindent
10679 Ahhh!  That's much better.
10681 But note what you've done: now that the result of @code{qar} is always
10682 a literal string, the only time a user can use nested macros is if she
10683 relies on an @emph{unquoted} macro call:
10685 @example
10686 qar(active)
10687 @result{}ACT
10688 qar([active])
10689 @result{}active
10690 @end example
10692 @noindent
10693 leaving no way for her to reproduce what she used to do with @code{car}:
10695 @example
10696 car([active])
10697 @result{}ACT, IVE
10698 @end example
10700 @noindent
10701 Worse yet: she wants to use a macro that produces a set of @code{cpp}
10702 macros:
10704 @example
10705 define([my_includes], [#include <stdio.h>])
10706 car([my_includes])
10707 @result{}#include <stdio.h>
10708 qar(my_includes)
10709 @error{}EOF in argument list
10710 @end example
10712 This macro, @code{qar}, because it double quotes its arguments, forces
10713 its users to leave their macro calls unquoted, which is dangerous.
10714 Commas and other active symbols are interpreted by M4 before
10715 they are given to the macro, often not in the way the users expect.
10716 Also, because @code{qar} behaves differently from the other macros,
10717 it's an exception that should be avoided in Autoconf.
10719 @node Changequote is Evil
10720 @subsection @code{changequote} is Evil
10721 @cindex @code{changequote}
10723 The temptation is often high to bypass proper quotation, in particular
10724 when it's late at night.  Then, many experienced Autoconf hackers
10725 finally surrender to the dark side of the force and use the ultimate
10726 weapon: @code{changequote}.
10728 The M4 builtin @code{changequote} belongs to a set of primitives that
10729 allow one to adjust the syntax of the language to adjust it to one's
10730 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
10731 quotes, but in the context of shell programming (and actually of most
10732 programming languages), that's about the worst choice one can make:
10733 because of strings and back-quoted expressions in shell code (such as
10734 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
10735 programming languages (as in @samp{'0'}), there are many unbalanced
10736 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
10737 not impossible.  In order to make M4 useful in such a context, its
10738 designers have equipped it with @code{changequote}, which makes it
10739 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
10740 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
10741 because they are unlikely characters, but @emph{because they are
10742 characters unlikely to be unbalanced}.
10744 There are other magic primitives, such as @code{changecom} to specify
10745 what syntactic forms are comments (it is common to see
10746 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
10747 @code{changeword} and @code{changesyntax} to change other syntactic
10748 details (such as the character to denote the @var{n}th argument, @samp{$} by
10749 default, the parentheses around arguments, etc.).
10751 These primitives are really meant to make M4 more useful for specific
10752 domains: they should be considered like command line options:
10753 @option{--quotes}, @option{--comments}, @option{--words}, and
10754 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
10755 it makes M4 libraries self contained (no need for additional options).
10757 There lies the problem@enddots{}
10759 @sp 1
10761 The problem is that it is then tempting to use them in the middle of an
10762 M4 script, as opposed to its initialization.  This, if not carefully
10763 thought out, can lead to disastrous effects: @emph{you are changing the
10764 language in the middle of the execution}.  Changing and restoring the
10765 syntax is often not enough: if you happened to invoke macros in between,
10766 these macros are lost, as the current syntax is probably not
10767 the one they were implemented with.
10769 @c FIXME: I've been looking for a short, real case example, but I
10770 @c lost them all :(
10773 @node Quadrigraphs
10774 @subsection Quadrigraphs
10775 @cindex quadrigraphs
10776 @cindex @samp{@@S|@@}
10777 @cindex @samp{@@&t@@}
10778 @c Info cannot handle ':' in index entries.
10779 @ifnotinfo
10780 @cindex @samp{@@<:@@}
10781 @cindex @samp{@@:>@@}
10782 @cindex @samp{@@%:@@}
10783 @cindex @samp{@@@{:@@}
10784 @cindex @samp{@@:@}@@}
10785 @end ifnotinfo
10787 When writing an Autoconf macro you may occasionally need to generate
10788 special characters that are difficult to express with the standard
10789 Autoconf quoting rules.  For example, you may need to output the regular
10790 expression @samp{[^[]}, which matches any character other than @samp{[}.
10791 This expression contains unbalanced brackets so it cannot be put easily
10792 into an M4 macro.
10794 Additionally, there are a few m4sugar macros (such as @code{m4_split}
10795 and @code{m4_expand}) which internally use special markers in addition
10796 to the regular quoting characters.  If the arguments to these macros
10797 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
10798 might behave incorrectly.
10800 You can work around these problems by using one of the following
10801 @dfn{quadrigraphs}:
10803 @table @samp
10804 @item @@<:@@
10805 @samp{[}
10806 @item @@:>@@
10807 @samp{]}
10808 @item @@S|@@
10809 @samp{$}
10810 @item @@%:@@
10811 @samp{#}
10812 @item @@@{:@@
10813 @samp{(}
10814 @item @@:@}@@
10815 @samp{)}
10816 @item @@&t@@
10817 Expands to nothing.
10818 @end table
10820 Quadrigraphs are replaced at a late stage of the translation process,
10821 after @command{m4} is run, so they do not get in the way of M4 quoting.
10822 For example, the string @samp{^@@<:@@}, independently of its quotation,
10823 appears as @samp{^[} in the output.
10825 The empty quadrigraph can be used:
10827 @itemize @minus
10828 @item to mark trailing spaces explicitly
10830 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
10832 @item to produce quadrigraphs and other strings reserved by m4sugar
10834 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
10835 contrived example:
10837 @example
10838 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
10839 m4_split([a )@}>=- b -=<@{( c])
10840 @result{}[a], [], [B], [], [c]
10841 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
10842 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
10843 @end example
10845 @item to escape @emph{occurrences} of forbidden patterns
10847 For instance you might want to mention @code{AC_FOO} in a comment, while
10848 still being sure that @command{autom4te} still catches unexpanded
10849 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
10850 @end itemize
10852 The name @samp{@@&t@@} was suggested by Paul Eggert:
10854 @quotation
10855 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
10856 own invention, but the @samp{t} came from the source code of the
10857 ALGOL68C compiler, written by Steve Bourne (of Bourne shell fame),
10858 and which used @samp{mt} to denote the empty string.  In C, it would
10859 have looked like something like:
10861 @example
10862 char const mt[] = "";
10863 @end example
10865 @noindent
10866 but of course the source code was written in Algol 68.
10868 I don't know where he got @samp{mt} from: it could have been his own
10869 invention, and I suppose it could have been a common pun around the
10870 Cambridge University computer lab at the time.
10871 @end quotation
10874 @node Balancing Parentheses
10875 @subsection Dealing with unbalanced parentheses
10876 @cindex balancing parentheses
10877 @cindex parentheses, balancing
10878 @cindex unbalanced parentheses, managing
10880 One of the pitfalls of portable shell programming is that @command{case}
10881 statements require unbalanced parentheses (@pxref{case, , Limitations of
10882 Shell Builtins}).  With syntax highlighting
10883 editors, the presence of unbalanced @samp{)} can interfere with editors
10884 that perform syntax highlighting of macro contents based on finding the
10885 matching @samp{(}.  Another concern is how much editing must be done
10886 when transferring code snippets between shell scripts and macro
10887 definitions.  But most importantly, the presence of unbalanced
10888 parentheses can introduce expansion bugs.
10890 For an example, here is an underquoted attempt to use the macro
10891 @code{my_case}, which happens to expand to a portable @command{case}
10892 statement:
10894 @example
10895 AC_DEFUN([my_case],
10896 [case $file_name in
10897   *.c) echo "C source code";;
10898 esac])
10899 AS_IF(:, my_case)
10900 @end example
10902 @noindent
10903 In the above example, the @code{AS_IF} call underquotes its arguments.
10904 As a result, the unbalanced @samp{)} generated by the premature
10905 expansion of @code{my_case} results in expanding @code{AS_IF} with a
10906 truncated parameter, and the expansion is syntactically invalid:
10908 @example
10909 if :; then
10910   case $file_name in
10911   *.c
10912 fi echo "C source code";;
10913 esac)
10914 @end example
10916 If nothing else, this should emphasize the importance of the quoting
10917 arguments to macro calls.  On the other hand, there are several
10918 variations for defining @code{my_case} to be more robust, even when used
10919 without proper quoting, each with some benefits and some drawbacks.
10921 @itemize @w{}
10922 @item Creative literal shell comment
10923 @example
10924 AC_DEFUN([my_case],
10925 [case $file_name in #(
10926   *.c) echo "C source code";;
10927 esac])
10928 @end example
10929 @noindent
10930 This version provides balanced parentheses to several editors, and can
10931 be copied and pasted into a terminal as is.  Unfortunately, it is still
10932 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
10933 that masks the normal properties of @samp{(}.
10935 @item Quadrigraph shell comment
10936 @example
10937 AC_DEFUN([my_case],
10938 [case $file_name in @@%:@@(
10939   *.c) echo "C source code";;
10940 esac])
10941 @end example
10942 @noindent
10943 This version provides balanced parentheses to even more editors, and can
10944 be used as a balanced Autoconf argument.  Unfortunately, it requires
10945 some editing before it can be copied and pasted into a terminal, and the
10946 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
10948 @item Quoting just the parenthesis
10949 @example
10950 AC_DEFUN([my_case],
10951 [case $file_name in
10952   *.c[)] echo "C source code";;
10953 esac])
10954 @end example
10955 @noindent
10956 This version quotes the @samp{)}, so that it can be used as a balanced
10957 Autoconf argument.  As written, this is not balanced to an editor, but
10958 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
10959 still requires some edits before it can be copied and pasted into a
10960 terminal.
10962 @item Double-quoting the entire statement
10963 @example
10964 AC_DEFUN([my_case],
10965 [[case $file_name in #(
10966   *.c) echo "C source code";;
10967 esac]])
10968 @end example
10969 @noindent
10970 Since the entire macro is double-quoted, there is no problem with using
10971 this as an Autoconf argument; and since the double-quoting is over the
10972 entire statement, this code can be easily copied and pasted into a
10973 terminal.  However, the double quoting prevents the expansion of any
10974 macros inside the case statement, which may cause its own set of
10975 problems.
10977 @item Using @code{AS_CASE}
10978 @example
10979 AC_DEFUN([my_case],
10980 [AS_CASE([$file_name],
10981   [*.c], [echo "C source code"])])
10982 @end example
10983 @noindent
10984 This version avoids the balancing issue altogether, by relying on
10985 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
10986 expansion of @code{AC_REQUIRE} to occur prior to the entire case
10987 statement, rather than within a branch of the case statement that might
10988 not be taken.  However, the abstraction comes with a penalty that it is
10989 no longer a quick copy, paste, and edit to get back to shell code.
10990 @end itemize
10993 @node Quotation Rule Of Thumb
10994 @subsection Quotation Rule Of Thumb
10996 To conclude, the quotation rule of thumb is:
10998 @center @emph{One pair of quotes per pair of parentheses.}
11000 Never over-quote, never under-quote, in particular in the definition of
11001 macros.  In the few places where the macros need to use brackets
11002 (usually in C program text or regular expressions), properly quote
11003 @emph{the arguments}!
11005 It is common to read Autoconf programs with snippets like:
11007 @example
11008 AC_TRY_LINK(
11009 changequote(<<, >>)dnl
11010 <<#include <time.h>
11011 #ifndef tzname /* For SGI.  */
11012 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11013 #endif>>,
11014 changequote([, ])dnl
11015 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
11016 @end example
11018 @noindent
11019 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
11020 double quoting, so you just need:
11022 @example
11023 AC_TRY_LINK(
11024 [#include <time.h>
11025 #ifndef tzname /* For SGI.  */
11026 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11027 #endif],
11028             [atoi (*tzname);],
11029             [ac_cv_var_tzname=yes],
11030             [ac_cv_var_tzname=no])
11031 @end example
11033 @noindent
11034 The M4-fluent reader might note that these two examples are rigorously
11035 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
11036 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
11037 quotes are not part of the arguments!
11039 Simplified, the example above is just doing this:
11041 @example
11042 changequote(<<, >>)dnl
11043 <<[]>>
11044 changequote([, ])dnl
11045 @end example
11047 @noindent
11048 instead of simply:
11050 @example
11051 [[]]
11052 @end example
11054 With macros that do not double quote their arguments (which is the
11055 rule), double-quote the (risky) literals:
11057 @example
11058 AC_LINK_IFELSE([AC_LANG_PROGRAM(
11059 [[#include <time.h>
11060 #ifndef tzname /* For SGI.  */
11061 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
11062 #endif]],
11063                                 [atoi (*tzname);])],
11064                [ac_cv_var_tzname=yes],
11065                [ac_cv_var_tzname=no])
11066 @end example
11068 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
11069 should be using @code{AC_LINK_IFELSE} instead.
11071 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
11072 where quoting does not suffice.
11074 When you create a @command{configure} script using newly written macros,
11075 examine it carefully to check whether you need to add more quotes in
11076 your macros.  If one or more words have disappeared in the M4
11077 output, you need more quotes.  When in doubt, quote.
11079 However, it's also possible to put on too many layers of quotes.  If
11080 this happens, the resulting @command{configure} script may contain
11081 unexpanded macros.  The @command{autoconf} program checks for this problem
11082 by looking for the string @samp{AC_} in @file{configure}.  However, this
11083 heuristic does not work in general: for example, it does not catch
11084 overquoting in @code{AC_DEFINE} descriptions.
11087 @c ---------------------------------------- Using autom4te
11089 @node Using autom4te
11090 @section Using @command{autom4te}
11092 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
11093 to Autoconf per se, heavily rely on M4.  All these different uses
11094 revealed common needs factored into a layer over M4:
11095 @command{autom4te}@footnote{
11097 Yet another great name from Lars J. Aas.
11101 @command{autom4te} is a preprocessor that is like @command{m4}.
11102 It supports M4 extensions designed for use in tools like Autoconf.
11104 @menu
11105 * autom4te Invocation::         A GNU M4 wrapper
11106 * Customizing autom4te::        Customizing the Autoconf package
11107 @end menu
11109 @node autom4te Invocation
11110 @subsection Invoking @command{autom4te}
11112 The command line arguments are modeled after M4's:
11114 @example
11115 autom4te @var{options} @var{files}
11116 @end example
11118 @noindent
11119 @evindex M4
11120 where the @var{files} are directly passed to @command{m4}.  By default,
11121 GNU M4 is found during configuration, but the environment
11122 variable
11123 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
11124 to the regular expansion, it handles the replacement of the quadrigraphs
11125 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
11126 output.  It supports an extended syntax for the @var{files}:
11128 @table @file
11129 @item @var{file}.m4f
11130 This file is an M4 frozen file.  Note that @emph{all the previous files
11131 are ignored}.  See the option @option{--melt} for the rationale.
11133 @item @var{file}?
11134 If found in the library path, the @var{file} is included for expansion,
11135 otherwise it is ignored instead of triggering a failure.
11136 @end table
11138 @sp 1
11140 Of course, it supports the Autoconf common subset of options:
11142 @table @option
11143 @item --help
11144 @itemx -h
11145 Print a summary of the command line options and exit.
11147 @item --version
11148 @itemx -V
11149 Print the version number of Autoconf and exit.
11151 @item --verbose
11152 @itemx -v
11153 Report processing steps.
11155 @item --debug
11156 @itemx -d
11157 Don't remove the temporary files and be even more verbose.
11159 @item --include=@var{dir}
11160 @itemx -I @var{dir}
11161 Also look for input files in @var{dir}.  Multiple invocations
11162 accumulate.
11164 @item --output=@var{file}
11165 @itemx -o @var{file}
11166 Save output (script or trace) to @var{file}.  The file @option{-} stands
11167 for the standard output.
11168 @end table
11170 @sp 1
11172 As an extension of @command{m4}, it includes the following options:
11174 @table @option
11175 @item --warnings=@var{category}
11176 @itemx -W @var{category}
11177 @evindex WARNINGS
11178 @c FIXME: Point to the M4sugar macros, not Autoconf's.
11179 Report the warnings related to @var{category} (which can actually be a
11180 comma separated list).  @xref{Reporting Messages}, macro
11181 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
11182 values include:
11184 @table @samp
11185 @item all
11186 report all the warnings
11188 @item none
11189 report none
11191 @item error
11192 treats warnings as errors
11194 @item no-@var{category}
11195 disable warnings falling into @var{category}
11196 @end table
11198 Warnings about @samp{syntax} are enabled by default, and the environment
11199 variable @env{WARNINGS}, a comma separated list of categories, is
11200 honored.  @samp{autom4te -W @var{category}} actually
11201 behaves as if you had run:
11203 @example
11204 autom4te --warnings=syntax,$WARNINGS,@var{category}
11205 @end example
11207 @noindent
11208 For example, if you want to disable defaults and @env{WARNINGS}
11209 of @command{autom4te}, but enable the warnings about obsolete
11210 constructs, you would use @option{-W none,obsolete}.
11212 @cindex Back trace
11213 @cindex Macro invocation stack
11214 @command{autom4te} displays a back trace for errors, but not for
11215 warnings; if you want them, just pass @option{-W error}.
11217 @item --melt
11218 @itemx -M
11219 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
11220 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
11221 are executed only when the files are frozen, typically
11222 @code{m4_define}.  For instance, running:
11224 @example
11225 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
11226 @end example
11228 @noindent
11229 is roughly equivalent to running:
11231 @example
11232 m4 1.m4 2.m4 3.m4 4.m4 input.m4
11233 @end example
11235 @noindent
11236 while
11238 @example
11239 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
11240 @end example
11242 @noindent
11243 is equivalent to:
11245 @example
11246 m4 --reload-state=4.m4f input.m4
11247 @end example
11249 @item --freeze
11250 @itemx -F
11251 Produce a frozen state file.  @command{autom4te} freezing is stricter
11252 than M4's: it must produce no warnings, and no output other than empty
11253 lines (a line with white space is @emph{not} empty) and comments
11254 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
11255 this option takes no argument:
11257 @example
11258 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
11259 @end example
11261 @noindent
11262 corresponds to
11264 @example
11265 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
11266 @end example
11268 @item --mode=@var{octal-mode}
11269 @itemx -m @var{octal-mode}
11270 Set the mode of the non-traces output to @var{octal-mode}; by default
11271 @samp{0666}.
11272 @end table
11274 @sp 1
11276 @cindex @file{autom4te.cache}
11277 As another additional feature over @command{m4}, @command{autom4te}
11278 caches its results.  GNU M4 is able to produce a regular
11279 output and traces at the same time.  Traces are heavily used in the
11280 GNU Build System: @command{autoheader} uses them to build
11281 @file{config.h.in}, @command{autoreconf} to determine what
11282 GNU Build System components are used, @command{automake} to
11283 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
11284 traces are cached while performing regular expansion,
11285 and conversely.  This cache is (actually, the caches are) stored in
11286 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
11287 at any moment (especially if for some reason @command{autom4te}
11288 considers it trashed).
11290 @table @option
11291 @item --cache=@var{directory}
11292 @itemx -C @var{directory}
11293 Specify the name of the directory where the result should be cached.
11294 Passing an empty value disables caching.  Be sure to pass a relative
11295 file name, as for the time being, global caches are not supported.
11297 @item --no-cache
11298 Don't cache the results.
11300 @item --force
11301 @itemx -f
11302 If a cache is used, consider it obsolete (but update it anyway).
11303 @end table
11305 @sp 1
11307 Because traces are so important to the GNU Build System,
11308 @command{autom4te} provides high level tracing features as compared to
11309 M4, and helps exploiting the cache:
11311 @table @option
11312 @item --trace=@var{macro}[:@var{format}]
11313 @itemx -t @var{macro}[:@var{format}]
11314 Trace the invocations of @var{macro} according to the @var{format}.
11315 Multiple @option{--trace} arguments can be used to list several macros.
11316 Multiple @option{--trace} arguments for a single macro are not
11317 cumulative; instead, you should just make @var{format} as long as
11318 needed.
11320 The @var{format} is a regular string, with newlines if desired, and
11321 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
11322 use the following special escapes:
11324 @table @samp
11325 @item $$
11326 @c $$ restore font-lock
11327 The character @samp{$}.
11329 @item $f
11330 The file name from which @var{macro} is called.
11332 @item $l
11333 The line number from which @var{macro} is called.
11335 @item $d
11336 The depth of the @var{macro} call.  This is an M4 technical detail that
11337 you probably don't want to know about.
11339 @item $n
11340 The name of the @var{macro}.
11342 @item $@var{num}
11343 The @var{num}th argument of the call to @var{macro}.
11345 @item $@@
11346 @itemx $@var{sep}@@
11347 @itemx $@{@var{separator}@}@@
11348 All the arguments passed to @var{macro}, separated by the character
11349 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
11350 argument is quoted, i.e., enclosed in a pair of square brackets.
11352 @item $*
11353 @itemx $@var{sep}*
11354 @itemx $@{@var{separator}@}*
11355 As above, but the arguments are not quoted.
11357 @item $%
11358 @itemx $@var{sep}%
11359 @itemx $@{@var{separator}@}%
11360 As above, but the arguments are not quoted, all new line characters in
11361 the arguments are smashed, and the default separator is @samp{:}.
11363 The escape @samp{$%} produces single-line trace outputs (unless you put
11364 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
11365 not.
11366 @end table
11368 @xref{autoconf Invocation}, for examples of trace uses.
11370 @item --preselect=@var{macro}
11371 @itemx -p @var{macro}
11372 Cache the traces of @var{macro}, but do not enable traces.  This is
11373 especially important to save CPU cycles in the future.  For instance,
11374 when invoked, @command{autoconf} preselects all the macros that
11375 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
11376 trace, so that running @command{m4} is not needed to trace them: the
11377 cache suffices.  This results in a huge speed-up.
11378 @end table
11380 @sp 1
11382 @cindex Autom4te Library
11383 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
11384 libraries}.  They consists in a powerful yet extremely simple feature:
11385 sets of combined command line arguments:
11387 @table @option
11388 @item --language=@var{language}
11389 @itemx -l @var{language}
11390 Use the @var{language} Autom4te library.  Current languages include:
11392 @table @code
11393 @item M4sugar
11394 create M4sugar output.
11396 @item M4sh
11397 create M4sh executable shell scripts.
11399 @item Autotest
11400 create Autotest executable test suites.
11402 @item Autoconf-without-aclocal-m4
11403 create Autoconf executable configure scripts without
11404 reading @file{aclocal.m4}.
11406 @item Autoconf
11407 create Autoconf executable configure scripts.  This language inherits
11408 all the characteristics of @code{Autoconf-without-aclocal-m4} and
11409 additionally reads @file{aclocal.m4}.
11410 @end table
11412 @item --prepend-include=@var{dir}
11413 @itemx -B @var{dir}
11414 Prepend directory @var{dir} to the search path.  This is used to include
11415 the language-specific files before any third-party macros.
11417 @end table
11419 @cindex @file{autom4te.cfg}
11420 As an example, if Autoconf is installed in its default location,
11421 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
11422 strictly equivalent to the command:
11424 @example
11425 autom4te --prepend-include /usr/local/share/autoconf \
11426   m4sugar/m4sugar.m4f --warnings syntax foo.m4
11427 @end example
11429 @noindent
11430 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
11431 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
11432 foo.m4}, i.e.:
11434 @example
11435 autom4te --prepend-include /usr/local/share/autoconf \
11436   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
11437 @end example
11439 @noindent
11440 The definition of the languages is stored in @file{autom4te.cfg}.
11442 @node Customizing autom4te
11443 @subsection Customizing @command{autom4te}
11445 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
11446 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
11447 as found in the directory from which @command{autom4te} is run).  The
11448 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
11449 then @file{./.autom4te.cfg}, and finally the command line arguments.
11451 In these text files, comments are introduced with @code{#}, and empty
11452 lines are ignored.  Customization is performed on a per-language basis,
11453 wrapped in between a @samp{begin-language: "@var{language}"},
11454 @samp{end-language: "@var{language}"} pair.
11456 Customizing a language stands for appending options (@pxref{autom4te
11457 Invocation}) to the current definition of the language.  Options, and
11458 more generally arguments, are introduced by @samp{args:
11459 @var{arguments}}.  You may use the traditional shell syntax to quote the
11460 @var{arguments}.
11462 As an example, to disable Autoconf caches (@file{autom4te.cache})
11463 globally, include the following lines in @file{~/.autom4te.cfg}:
11465 @verbatim
11466 ## ------------------ ##
11467 ## User Preferences.  ##
11468 ## ------------------ ##
11470 begin-language: "Autoconf-without-aclocal-m4"
11471 args: --no-cache
11472 end-language: "Autoconf-without-aclocal-m4"
11473 @end verbatim
11476 @node Programming in M4sugar
11477 @section Programming in M4sugar
11479 @cindex M4sugar
11480 M4 by itself provides only a small, but sufficient, set of all-purpose
11481 macros.  M4sugar introduces additional generic macros.  Its name was
11482 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
11483 M4sugar''.
11485 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
11486 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
11487 define your own macros into these namespaces.
11489 @menu
11490 * Redefined M4 Macros::         M4 builtins changed in M4sugar
11491 * Diagnostic Macros::           Diagnostic messages from M4sugar
11492 * Diversion support::           Diversions in M4sugar
11493 * Conditional constructs::      Conditions in M4
11494 * Looping constructs::          Iteration in M4
11495 * Evaluation Macros::           More quotation and evaluation control
11496 * Text processing Macros::      String manipulation in M4
11497 * Number processing Macros::    Arithmetic computation in M4
11498 * Set manipulation Macros::     Set manipulation in M4
11499 * Forbidden Patterns::          Catching unexpanded macros
11500 @end menu
11502 @node Redefined M4 Macros
11503 @subsection Redefined M4 Macros
11505 @msindex{builtin}
11506 @msindex{changecom}
11507 @msindex{changequote}
11508 @msindex{debugfile}
11509 @msindex{debugmode}
11510 @msindex{decr}
11511 @msindex{define}
11512 @msindex{divnum}
11513 @msindex{errprint}
11514 @msindex{esyscmd}
11515 @msindex{eval}
11516 @msindex{format}
11517 @msindex{ifdef}
11518 @msindex{incr}
11519 @msindex{index}
11520 @msindex{indir}
11521 @msindex{len}
11522 @msindex{pushdef}
11523 @msindex{shift}
11524 @msindex{substr}
11525 @msindex{syscmd}
11526 @msindex{sysval}
11527 @msindex{traceoff}
11528 @msindex{traceon}
11529 @msindex{translit}
11530 With a few exceptions, all the M4 native macros are moved in the
11531 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
11532 @code{m4_define} etc.
11534 The list of macros unchanged from M4, except for their name, is:
11535 @itemize @minus
11536 @item m4_builtin
11537 @item m4_changecom
11538 @item m4_changequote
11539 @item m4_debugfile
11540 @item m4_debugmode
11541 @item m4_decr
11542 @item m4_define
11543 @item m4_divnum
11544 @item m4_errprint
11545 @item m4_esyscmd
11546 @item m4_eval
11547 @item m4_format
11548 @item m4_ifdef
11549 @item m4_incr
11550 @item m4_index
11551 @item m4_indir
11552 @item m4_len
11553 @item m4_pushdef
11554 @item m4_shift
11555 @item m4_substr
11556 @item m4_syscmd
11557 @item m4_sysval
11558 @item m4_traceoff
11559 @item m4_traceon
11560 @item m4_translit
11561 @end itemize
11563 Some M4 macros are redefined, and are slightly incompatible with their
11564 native equivalent.
11566 @defmac __file__
11567 @defmacx __line__
11568 @MSindex __file__
11569 @MSindex __line__
11570 All M4 macros starting with @samp{__} retain their original name: for
11571 example, no @code{m4__file__} is defined.
11572 @end defmac
11574 @defmac __oline__
11575 @MSindex __oline__
11576 This is not technically a macro, but a feature of Autom4te.  The
11577 sequence @code{__oline__} can be used similarly to the other m4sugar
11578 location macros, but rather than expanding to the location of the input
11579 file, it is translated to the line number where it appears in the output
11580 file after all other M4 expansions.
11581 @end defmac
11583 @defmac dnl
11584 @MSindex dnl
11585 This macro kept its original name: no @code{m4_dnl} is defined.
11586 @end defmac
11588 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
11589 @msindex{bpatsubst}
11590 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
11591 is kept for future versions of M4sugar, once GNU M4 2.0 is
11592 released and supports extended regular expression syntax.
11593 @end defmac
11595 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
11596 @msindex{bregexp}
11597 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
11598 is kept for future versions of M4sugar, once GNU M4 2.0 is
11599 released and supports extended regular expression syntax.
11600 @end defmac
11602 @defmac m4_copy (@var{source}, @var{dest})
11603 @defmacx m4_copy_force (@var{source}, @var{dest})
11604 @defmacx m4_rename (@var{source}, @var{dest})
11605 @defmacx m4_rename_force (@var{source}, @var{dest})
11606 @msindex{copy}
11607 @msindex{copy_force}
11608 @msindex{rename}
11609 @msindex{rename_force}
11610 These macros aren't directly builtins, but are closely related to
11611 @code{m4_pushdef} and @code{m4_defn}.  @code{m4_copy} and
11612 @code{m4_rename} ensure that @var{dest} is undefined, while
11613 @code{m4_copy_force} and @code{m4_rename_force} overwrite any existing
11614 definition.  All four macros then proceed to copy the entire pushdef
11615 stack of definitions of @var{source} over to @var{dest}.  @code{m4_copy}
11616 and @code{m4_copy_force} preserve the source (including in the special
11617 case where @var{source} is undefined), while @code{m4_rename} and
11618 @code{m4_rename_force} undefine the original macro name (making it an
11619 error to rename an undefined @var{source}).
11621 Note that attempting to invoke a renamed macro might not work, since the
11622 macro may have a dependence on helper macros accessed via composition of
11623 @samp{$0} but that were not also renamed; likewise, other macros may
11624 have a hard-coded dependence on @var{source} and could break if
11625 @var{source} has been deleted.  On the other hand, it is always safe to
11626 rename a macro to temporarily move it out of the way, then rename it
11627 back later to restore original semantics.
11628 @end defmac
11630 @defmac m4_defn (@var{macro}@dots{})
11631 @msindex{defn}
11632 This macro fails if @var{macro} is not defined, even when using older
11633 versions of M4 that did not warn.  See @code{m4_undefine}.
11634 Unfortunately, in order to support these older versions of M4, there are
11635 some situations involving unbalanced quotes where concatenating multiple
11636 macros together will work in newer M4 but not in m4sugar; use
11637 quadrigraphs to work around this.
11638 @end defmac
11640 @defmac m4_divert (@var{diversion})
11641 @msindex{divert}
11642 M4sugar relies heavily on diversions, so rather than behaving as a
11643 primitive, @code{m4_divert} behaves like:
11644 @example
11645 m4_divert_pop()m4_divert_push([@var{diversion}])
11646 @end example
11647 @noindent
11648 @xref{Diversion support}, for more details about the use of the
11649 diversion stack.  In particular, this implies that @var{diversion}
11650 should be a named diversion rather than a raw number.  But be aware that
11651 it is seldom necessary to explicitly change the diversion stack, and
11652 that when done incorrectly, it can lead to syntactically invalid
11653 scripts.
11654 @end defmac
11656 @defmac m4_dumpdef (@var{name}@dots{})
11657 @defmacx m4_dumpdefs (@var{name}@dots{})
11658 @msindex{dumpdef}
11659 @msindex{dumpdefs}
11660 @code{m4_dumpdef} is like the M4 builtin, except that this version
11661 requires at least one argument, output always goes to standard error
11662 rather than the current debug file, no sorting is done on multiple
11663 arguments, and an error is issued if any
11664 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
11665 calls @code{m4_dumpdef} for all of the
11666 @code{m4_pushdef} stack of definitions, starting with the current, and
11667 silently does nothing if @var{name} is undefined.
11669 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
11670 builtin is output as the empty string.  This behavior is rectified by
11671 using M4 1.6 or newer.  However, this behavior difference means that
11672 @code{m4_dumpdef} should only be used while developing m4sugar macros,
11673 and never in the final published form of a macro.
11674 @end defmac
11676 @defmac m4_esyscmd_s (@var{command})
11677 @msindex{esyscmd_s}
11678 Like @code{m4_esyscmd}, this macro expands to the result of running
11679 @var{command} in a shell.  The difference is that any trailing newlines
11680 are removed, so that the output behaves more like shell command
11681 substitution.
11682 @end defmac
11684 @defmac m4_exit (@var{exit-status})
11685 @msindex{exit}
11686 This macro corresponds to @code{m4exit}.
11687 @end defmac
11689 @defmac m4_if (@var{comment})
11690 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
11691 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal-1}, @
11692   @var{string-3}, @var{string-4}, @var{equal-2}, @dots{}, @ovar{not-equal})
11693 @msindex{if}
11694 This macro corresponds to @code{ifelse}.  @var{string-1} and
11695 @var{string-2} are compared literally, so usually one of the two
11696 arguments is passed unquoted.  @xref{Conditional constructs}, for more
11697 conditional idioms.
11698 @end defmac
11700 @defmac m4_include (@var{file})
11701 @defmacx m4_sinclude (@var{file})
11702 @msindex{include}
11703 @msindex{sinclude}
11704 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
11705 @end defmac
11707 @defmac m4_mkstemp (@var{template})
11708 @defmacx m4_maketemp (@var{template})
11709 @msindex{maketemp}
11710 @msindex{mkstemp}
11711 Posix requires @code{maketemp} to replace the trailing @samp{X}
11712 characters in @var{template} with the process id, without regards to the
11713 existence of a file by that name, but this a security hole.  When this
11714 was pointed out to the Posix folks, they agreed to invent a new macro
11715 @code{mkstemp} that always creates a uniquely named file, but not all
11716 versions of GNU M4 support the new macro.  In M4sugar,
11717 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
11718 and both have the secure semantics regardless of which macro the
11719 underlying M4 provides.
11720 @end defmac
11722 @defmac m4_popdef (@var{macro}@dots{})
11723 @msindex{popdef}
11724 This macro fails if @var{macro} is not defined, even when using older
11725 versions of M4 that did not warn.  See @code{m4_undefine}.
11726 @end defmac
11728 @defmac m4_undefine (@var{macro}@dots{})
11729 @msindex{undefine}
11730 This macro fails if @var{macro} is not defined, even when using older
11731 versions of M4 that did not warn.  Use
11733 @example
11734 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
11735 @end example
11737 @noindent
11738 if you are not sure whether @var{macro} is defined.
11739 @end defmac
11741 @defmac m4_undivert (@var{diversion}@dots{})
11742 @msindex{undivert}
11743 Unlike the M4 builtin, at least one @var{diversion} must be specified.
11744 Also, since the M4sugar diversion stack prefers named
11745 diversions, the use of @code{m4_undivert} to include files is risky.
11746 @xref{Diversion support}, for more details about the use of the
11747 diversion stack.  But be aware that it is seldom necessary to explicitly
11748 change the diversion stack, and that when done incorrectly, it can lead
11749 to syntactically invalid scripts.
11750 @end defmac
11752 @defmac m4_wrap (@var{text})
11753 @defmacx m4_wrap_lifo (@var{text})
11754 @msindex{wrap}
11755 @msindex{wrap_lifo}
11756 These macros correspond to @code{m4wrap}.  Posix requires arguments of
11757 multiple wrap calls to be reprocessed at EOF in the same order
11758 as the original calls (first-in, first-out).  GNU M4 versions
11759 through 1.4.10, however, reprocess them in reverse order (last-in,
11760 first-out).  Both orders are useful, therefore, you can rely on
11761 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
11762 LIFO semantics, regardless of the underlying GNU M4 version.
11764 Unlike the GNU M4 builtin, these macros only recognize one
11765 argument, and avoid token pasting between consecutive invocations.  On
11766 the other hand, nested calls to @code{m4_wrap} from within wrapped text
11767 work just as in the builtin.
11768 @end defmac
11771 @node Diagnostic Macros
11772 @subsection Diagnostic messages from M4sugar
11773 @cindex Messages, from @command{M4sugar}
11775 When macros statically diagnose abnormal situations, benign or fatal,
11776 they should report them using these macros.  For issuing dynamic issues,
11777 i.e., when @command{configure} is run, see @ref{Printing Messages}.
11779 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
11780 @msindex{assert}
11781 Assert that the arithmetic @var{expression} evaluates to non-zero.
11782 Otherwise, issue a fatal error, and exit @command{autom4te} with
11783 @var{exit-status}.
11784 @end defmac
11786 @defmac m4_errprintn (@var{message})
11787 @msindex{errprintn}
11788 Similar to the builtin @code{m4_errprint}, except that a newline is
11789 guaranteed after @var{message}.
11790 @end defmac
11792 @anchor{m4_fatal}
11793 @defmac m4_fatal (@var{message})
11794 @msindex{fatal}
11795 Report a severe error @var{message} prefixed with the current location,
11796 and have @command{autom4te} die.
11797 @end defmac
11799 @defmac m4_location
11800 @msindex{location}
11801 Useful as a prefix in a message line.  Short for:
11802 @example
11803 __file__:__line__
11804 @end example
11805 @end defmac
11807 @anchor{m4_warn}
11808 @defmac m4_warn (@var{category}, @var{message})
11809 @msindex{warn}
11810 Report @var{message} as a warning (or as an error if requested by the
11811 user) if warnings of the @var{category} are turned on.  If the message
11812 is emitted, it is prefixed with the current location, and followed by a
11813 call trace of all macros defined via @code{AC_DEFUN} used to get to the
11814 current expansion.  You are encouraged to use standard categories, which
11815 currently include:
11817 @table @samp
11818 @item all
11819 messages that don't fall into one of the following categories.  Use of an
11820 empty @var{category} is equivalent.
11822 @item cross
11823 related to cross compilation issues.
11825 @item obsolete
11826 use of an obsolete construct.
11828 @item syntax
11829 dubious syntactic constructs, incorrectly ordered macro calls.
11830 @end table
11831 @end defmac
11834 @node Diversion support
11835 @subsection Diversion support
11837 M4sugar makes heavy use of diversions under the hood, because it is
11838 often the case that
11839 text that must appear early in the output is not discovered until late
11840 in the input.  Additionally, some of the topological sorting algorithms
11841 used in resolving macro dependencies use diversions.  However, most
11842 macros should not need to change diversions directly, but rather rely on
11843 higher-level M4sugar macros to manage diversions transparently.  If you
11844 change diversions improperly, you risk generating a syntactically
11845 invalid script, because an incorrect diversion will violate assumptions
11846 made by many macros about whether prerequisite text has been previously
11847 output.  In short, if you manually change the diversion, you should not
11848 expect any macros provided by the Autoconf package to work until you
11849 have restored the diversion stack back to its original state.
11851 In the rare case that it is necessary to write a macro that explicitly
11852 outputs text to a different diversion, it is important to be aware of an
11853 M4 limitation regarding diversions: text only goes to a diversion if it
11854 is not part of argument collection.  Therefore, any macro that changes
11855 the current diversion cannot be used as an unquoted argument to another
11856 macro, but must be expanded at the top level.  The macro
11857 @code{m4_expand} will diagnose any attempt to change diversions, since
11858 it is generally useful only as an argument to another macro.  The
11859 following example shows what happens when diversion manipulation is
11860 attempted within macro arguments:
11862 @example
11863 m4_do([normal text]
11864 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
11865 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
11866 @result{}normal text
11867 @result{}unwanted
11868 @end example
11870 @noindent
11871 Notice that the unquoted text @code{unwanted} is output, even though it
11872 was processed while the current diversion was @code{KILL}, because it
11873 was collected as part of the argument to @code{m4_do}.  However, the
11874 text @code{discarded} disappeared as desired, because the diversion
11875 changes were single-quoted, and were not expanded until the top-level
11876 rescan of the output of @code{m4_do}.
11878 To make diversion management easier, M4sugar uses the concept of named
11879 diversions.  Rather than using diversion numbers directly, it is nicer
11880 to associate a name with each diversion.  The diversion number associated
11881 with a particular diversion name is an implementation detail, and a
11882 syntax warning is issued if a diversion number is used instead of a
11883 name.  In general, you should not output text
11884 to a named diversion until after calling the appropriate initialization
11885 routine for your language (@code{m4_init}, @code{AS_INIT},
11886 @code{AT_INIT}, @dots{}), although there are some exceptions documented
11887 below.
11889 M4sugar defines two named diversions.
11890 @table @code
11891 @item KILL
11892 Text written to this diversion is discarded.  This is the default
11893 diversion once M4sugar is initialized.
11894 @item GROW
11895 This diversion is used behind the scenes by topological sorting macros,
11896 such as @code{AC_REQUIRE}.
11897 @end table
11899 M4sh adds several more named diversions.
11900 @table @code
11901 @item BINSH
11902 This diversion is reserved for the @samp{#!} interpreter line.
11903 @item HEADER-REVISION
11904 This diversion holds text from @code{AC_REVISION}.
11905 @item HEADER-COMMENT
11906 This diversion holds comments about the purpose of a file.
11907 @item HEADER-COPYRIGHT
11908 This diversion is managed by @code{AC_COPYRIGHT}.
11909 @item M4SH-SANITIZE
11910 This diversion contains M4sh sanitization code, used to ensure M4sh is
11911 executing in a reasonable shell environment.
11912 @item M4SH-INIT
11913 This diversion contains M4sh initialization code, initializing variables
11914 that are required by other M4sh macros.
11915 @item BODY
11916 This diversion contains the body of the shell code, and is the default
11917 diversion once M4sh is initialized.
11918 @end table
11920 Autotest inherits diversions from M4sh, and changes the default
11921 diversion from @code{BODY} back to @code{KILL}.  It also adds several
11922 more named diversions, with the following subset designed for developer
11923 use.
11924 @table @code
11925 @item PREPARE_TESTS
11926 This diversion contains initialization sequences which are executed
11927 after @file{atconfig} and @file{atlocal}, and after all command line
11928 arguments have been parsed, but prior to running any tests.  It can be
11929 used to set up state that is required across all tests.  This diversion
11930 will work even before @code{AT_INIT}.
11931 @end table
11933 Autoconf inherits diversions from M4sh, and adds the following named
11934 diversions which developers can utilize.
11935 @table @code
11936 @item DEFAULTS
11937 This diversion contains shell variable assignments to set defaults that
11938 must be in place before arguments are parsed.  This diversion is placed
11939 early enough in @file{configure} that it is unsafe to expand any
11940 autoconf macros into this diversion.
11941 @item HELP_ENABLE
11942 If @code{AC_PRESERVE_HELP_ORDER} was used, then text placed in this
11943 diversion will be included as part of a quoted here-doc providing all of
11944 the @option{--help} output of @file{configure} related to options
11945 created by @code{AC_ARG_WITH} and @code{AC_ARG_ENABLE}.
11946 @item INIT_PREPARE
11947 This diversion occurs after all command line options have been parsed,
11948 but prior to the main body of the @file{configure} script.  This
11949 diversion is the last chance to insert shell code such as variable
11950 assignments or shell function declarations that will used by the
11951 expansion of other macros.
11952 @end table
11954 For now, the remaining named diversions of Autoconf, Autoheader, and
11955 Autotest are not documented.  In other words,
11956 intentionally outputting text into an undocumented diversion is subject
11957 to breakage in a future release of Autoconf.
11959 @defmac m4_cleardivert (@var{diversion}@dots{})
11960 @msindex{cleardivert}
11961 Permanently discard any text that has been diverted into
11962 @var{diversion}.
11963 @end defmac
11965 @defmac m4_divert_once (@var{diversion}, @ovar{content})
11966 @msindex{divert_once}
11967 Similar to @code{m4_divert_text}, except that @var{content} is only
11968 output to @var{diversion} if this is the first time that
11969 @code{m4_divert_once} has been called with its particular arguments.
11970 @end defmac
11972 @defmac m4_divert_pop (@ovar{diversion})
11973 @msindex{divert_pop}
11974 If provided, check that the current diversion is indeed @var{diversion}.
11975 Then change to the diversion located earlier on the stack, giving an
11976 error if an attempt is made to pop beyond the initial m4sugar diversion
11977 of @code{KILL}.
11978 @end defmac
11980 @defmac m4_divert_push (@var{diversion})
11981 @msindex{divert_push}
11982 Remember the former diversion on the diversion stack, and output
11983 subsequent text into @var{diversion}.  M4sugar maintains a diversion
11984 stack, and issues an error if there is not a matching pop for every
11985 push.
11986 @end defmac
11988 @anchor{m4_divert_text}
11989 @defmac m4_divert_text (@var{diversion}, @ovar{content})
11990 @msindex{divert_text}
11991 Output @var{content} and a newline into @var{diversion}, without
11992 affecting the current diversion.  Shorthand for:
11993 @example
11994 m4_divert_push([@var{diversion}])@var{content}
11995 m4_divert_pop([@var{diversion}])dnl
11996 @end example
11998 One use of @code{m4_divert_text} is to develop two related macros, where
11999 macro @samp{MY_A} does the work, but adjusts what work is performed
12000 based on whether the optional macro @samp{MY_B} has also been expanded.
12001 Of course, it is possible to use @code{AC_BEFORE} within @code{MY_A} to
12002 require that @samp{MY_B} occurs first, if it occurs at all.  But this
12003 imposes an ordering restriction on the user; it would be nicer if macros
12004 @samp{MY_A} and @samp{MY_B} can be invoked in either order.  The trick
12005 is to let @samp{MY_B} leave a breadcrumb in an early diversion, which
12006 @samp{MY_A} can then use to determine whether @samp{MY_B} has been
12007 expanded.
12009 @example
12010 AC_DEFUN([MY_A],
12011 [# various actions
12012 if test -n "$b_was_used"; then
12013   # extra action
12014 fi])
12015 AC_DEFUN([MY_B],
12016 [AC_REQUIRE([MY_A])dnl
12017 m4_divert_text([INIT_PREPARE], [b_was_used=true])])
12018 @end example
12020 @end defmac
12022 @defmac m4_init
12023 @msindex{init}
12024 Initialize the M4sugar environment, setting up the default named
12025 diversion to be @code{KILL}.
12026 @end defmac
12028 @node Conditional constructs
12029 @subsection Conditional constructs
12031 The following macros provide additional conditional constructs as
12032 convenience wrappers around @code{m4_if}.
12034 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
12035   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
12036 @msindex{bmatch}
12037 The string @var{string} is repeatedly compared against a series of
12038 @var{regex} arguments; if a match is found, the expansion is the
12039 corresponding @var{value}, otherwise, the macro moves on to the next
12040 @var{regex}.  If no @var{regex} match, then the result is the optional
12041 @var{default}, or nothing.
12042 @end defmac
12044 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
12045   @ovar{regex-2}, @ovar{subst-2}, @dots{})
12046 @msindex{bpatsubsts}
12047 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
12048 as if by:
12049 @example
12050 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
12051 @end example
12053 @noindent
12054 The result of the substitution is then passed through the next set of
12055 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
12056 deletion of any matched portions in the current string.  Note that this
12057 macro over-quotes @var{string}; this behavior is intentional, so that
12058 the result of each step of the recursion remains as a quoted string.
12059 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
12060 will line up with the extra quotations, and not the characters of the
12061 original string.  The overquoting is removed after the final
12062 substitution.
12063 @end defmac
12065 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
12066   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12067 @msindex{case}
12068 Test @var{string} against multiple @var{value} possibilities, resulting
12069 in the first @var{if-value} for a match, or in the optional
12070 @var{default}.  This is shorthand for:
12071 @example
12072 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
12073       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
12074       [@var{default}])
12075 @end example
12076 @end defmac
12078 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
12079   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
12080 @msindex{cond}
12081 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
12082 except that each @var{test} is expanded only when it is encountered.
12083 This is useful for short-circuiting expensive tests; while @code{m4_if}
12084 requires all its strings to be expanded up front before doing
12085 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
12086 tests have failed.
12088 For an example, these two sequences give the same result, but in the
12089 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
12090 version only expands @code{m4_index} once, instead of five times, for
12091 faster computation if this is a common case for @samp{$1}.  Notice that
12092 every third argument is unquoted for @code{m4_if}, and quoted for
12093 @code{m4_cond}:
12095 @example
12096 m4_if(m4_index([$1], [\]), [-1], [$2],
12097       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
12098       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
12099       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
12100       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
12101       [$2])
12102 m4_cond([m4_index([$1], [\])], [-1], [$2],
12103         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
12104         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
12105         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
12106         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
12107         [$2])
12108 @end example
12109 @end defmac
12111 @defmac m4_default (@var{expr-1}, @var{expr-2})
12112 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
12113 @defmacx m4_default_nblank (@var{expr-1}, @ovar{expr-2})
12114 @defmacx m4_default_nblank_quoted (@var{expr-1}, @ovar{expr-2})
12115 @msindex{default}
12116 @msindex{default_quoted}
12117 @msindex{default_nblank}
12118 @msindex{default_nblank_quoted}
12119 If @var{expr-1} contains text, use it.  Otherwise, select @var{expr-2}.
12120 @code{m4_default} expands the result, while @code{m4_default_quoted}
12121 does not.  Useful for providing a fixed default if the expression that
12122 results in @var{expr-1} would otherwise be empty.  The difference
12123 between @code{m4_default} and @code{m4_default_nblank} is whether an
12124 argument consisting of just blanks (space, tab, newline) is
12125 significant.  When using the expanding versions, note that an argument
12126 may contain text but still expand to an empty string.
12128 @example
12129 m4_define([active], [ACTIVE])dnl
12130 m4_define([empty], [])dnl
12131 m4_define([demo1], [m4_default([$1], [$2])])dnl
12132 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
12133 m4_define([demo3], [m4_default_nblank([$1], [$2])])dnl
12134 m4_define([demo4], [m4_default_nblank_quoted([$1], [$2])])dnl
12135 demo1([active], [default])
12136 @result{}ACTIVE
12137 demo1([], [active])
12138 @result{}ACTIVE
12139 demo1([empty], [text])
12140 @result{}
12141 -demo1([ ], [active])-
12142 @result{}- -
12143 demo2([active], [default])
12144 @result{}active
12145 demo2([], [active])
12146 @result{}active
12147 demo2([empty], [text])
12148 @result{}empty
12149 -demo2([ ], [active])-
12150 @result{}- -
12151 demo3([active], [default])
12152 @result{}ACTIVE
12153 demo3([], [active])
12154 @result{}ACTIVE
12155 demo3([empty], [text])
12156 @result{}
12157 -demo3([ ], [active])-
12158 @result{}-ACTIVE-
12159 demo4([active], [default])
12160 @result{}active
12161 demo4([], [active])
12162 @result{}active
12163 demo4([empty], [text])
12164 @result{}empty
12165 -demo4([ ], [active])-
12166 @result{}-active-
12167 @end example
12168 @end defmac
12170 @defmac m4_define_default (@var{macro}, @ovar{default-definition})
12171 @msindex{define_default}
12172 If @var{macro} does not already have a definition, then define it to
12173 @var{default-definition}.
12174 @end defmac
12176 @defmac m4_ifblank (@var{cond}, @ovar{if-blank}, @ovar{if-text})
12177 @defmacx m4_ifnblank (@var{cond}, @ovar{if-text}, @ovar{if-blank})
12178 @msindex{ifblank}
12179 @msindex{ifnblank}
12180 If @var{cond} is empty or consists only of blanks (space, tab, newline),
12181 then expand @var{if-blank}; otherwise, expand @var{if-text}.  Two
12182 variants exist, in order to make it easier to select the correct logical
12183 sense when using only two parameters.  Note that this is more efficient
12184 than the equivalent behavior of:
12185 @example
12186 m4_ifval(m4_normalize([@var{cond}]), @var{if-text}, @var{if-blank})
12187 @end example
12188 @end defmac
12190 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
12191 @msindex{ifndef}
12192 This is shorthand for:
12193 @example
12194 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
12195 @end example
12196 @end defmac
12198 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
12199 @msindex{ifset}
12200 If @var{macro} is undefined, or is defined as the empty string, expand
12201 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
12202 @example
12203 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
12204 @end example
12205 @noindent
12206 except that it is not an error if @var{macro} is undefined.
12207 @end defmac
12209 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
12210 @msindex{ifval}
12211 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
12212 @var{if-false}.  This is shorthand for:
12213 @example
12214 m4_if([@var{cond}], [], [@var{if-false}], [@var{if-true}])
12215 @end example
12216 @end defmac
12218 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
12219 @msindex{ifvaln}
12220 Similar to @code{m4_ifval}, except guarantee that a newline is present
12221 after any non-empty expansion.  Often followed by @code{dnl}.
12222 @end defmac
12224 @defmac m4_n (@var{text})
12225 @msindex{n}
12226 Expand to @var{text}, and add a newline if @var{text} is not empty.
12227 Often followed by @code{dnl}.
12228 @end defmac
12231 @node Looping constructs
12232 @subsection Looping constructs
12234 The following macros are useful in implementing recursive algorithms in
12235 M4, including loop operations.  An M4 list is formed by quoting a list
12236 of quoted elements; generally the lists are comma-separated, although
12237 @code{m4_foreach_w} is whitespace-separated.  For example, the list
12238 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
12239 It is common to see lists with unquoted elements when those elements are
12240 not likely to be macro names, as in @samp{[fputc_unlocked,
12241 fgetc_unlocked]}.
12243 Although not generally recommended, it is possible for quoted lists to
12244 have side effects; all side effects are expanded only once, and prior to
12245 visiting any list element.  On the other hand, the fact that unquoted
12246 macros are expanded exactly once means that macros without side effects
12247 can be used to generate lists.  For example,
12249 @example
12250 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
12251 @error{}hi
12252 @result{}123
12253 m4_define([list], [[1], [2], [3]])
12254 @result{}
12255 m4_foreach([i], [list], [i])
12256 @result{}123
12257 @end example
12259 @defmac m4_argn (@var{n}, @ovar{arg}@dots{})
12260 @msindex{argn}
12261 Extracts argument @var{n} (larger than 0) from the remaining arguments.
12262 If there are too few arguments, the empty string is used.  For any
12263 @var{n} besides 1, this is more efficient than the similar
12264 @samp{m4_car(m4_shiftn([@var{n}], [], [@var{arg}@dots{}]))}.
12265 @end defmac
12267 @defmac m4_car (@var{arg}@dots{})
12268 @msindex{car}
12269 Expands to the quoted first @var{arg}.  Can be used with @code{m4_cdr}
12270 to recursively iterate
12271 through a list.  Generally, when using quoted lists of quoted elements,
12272 @code{m4_car} should be called without any extra quotes.
12273 @end defmac
12275 @defmac m4_cdr (@var{arg}@dots{})
12276 @msindex{cdr}
12277 Expands to a quoted list of all but the first @var{arg}, or the empty
12278 string if there was only one argument.  Generally, when using quoted
12279 lists of quoted elements, @code{m4_cdr} should be called without any
12280 extra quotes.
12282 For example, this is a simple implementation of @code{m4_map}; note how
12283 each iteration checks for the end of recursion, then merely applies the
12284 first argument to the first element of the list, then repeats with the
12285 rest of the list.  (The actual implementation in M4sugar is a bit more
12286 involved, to gain some speed and share code with @code{m4_map_sep}, and
12287 also to avoid expanding side effects in @samp{$2} twice).
12288 @example
12289 m4_define([m4_map], [m4_ifval([$2],
12290   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
12291 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
12292 @result{} 1 2 a
12293 @end example
12294 @end defmac
12296 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
12297   @var{expression})
12298 @msindex{for}
12299 Loop over the numeric values between @var{first} and @var{last}
12300 including bounds by increments of @var{step}.  For each iteration,
12301 expand @var{expression} with the numeric value assigned to @var{var}.
12302 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
12303 on the order of the limits.  If given, @var{step} has to match this
12304 order.  The number of iterations is determined independently from
12305 definition of @var{var}; iteration cannot be short-circuited or
12306 lengthened by modifying @var{var} from within @var{expression}.
12307 @end defmac
12309 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
12310 @msindex{foreach}
12311 Loop over the comma-separated M4 list @var{list}, assigning each value
12312 to @var{var}, and expand @var{expression}.  The following example
12313 outputs two lines:
12315 @example
12316 m4_foreach([myvar], [[foo], [bar, baz]],
12317            [echo myvar
12318 ])dnl
12319 @result{}echo foo
12320 @result{}echo bar, baz
12321 @end example
12323 Note that for some forms of @var{expression}, it may be faster to use
12324 @code{m4_map_args}.
12325 @end defmac
12327 @anchor{m4_foreach_w}
12328 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
12329 @msindex{foreach_w}
12330 Loop over the white-space-separated list @var{list}, assigning each value
12331 to @var{var}, and expand @var{expression}.  If @var{var} is only
12332 referenced once in @var{expression}, it is more efficient to use
12333 @code{m4_map_args_w}.
12335 The deprecated macro @code{AC_FOREACH} is an alias of
12336 @code{m4_foreach_w}.
12337 @end defmac
12339 @defmac m4_map (@var{macro}, @var{list})
12340 @defmacx m4_mapall (@var{macro}, @var{list})
12341 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
12342 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
12343 @msindex{map}
12344 @msindex{mapall}
12345 @msindex{map_sep}
12346 @msindex{mapall_sep}
12347 Loop over the comma separated quoted list of argument descriptions in
12348 @var{list}, and invoke @var{macro} with the arguments.  An argument
12349 description is in turn a comma-separated quoted list of quoted elements,
12350 suitable for @code{m4_apply}.  The macros @code{m4_map} and
12351 @code{m4_map_sep} ignore empty argument descriptions, while
12352 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
12353 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
12354 additionally expand @var{separator} between invocations of @var{macro}.
12356 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
12357 separating output with commas, this means that the map result can be
12358 used as a series of arguments, by using a single-quoted comma as
12359 @var{separator}, or as a single string, by using a double-quoted comma.
12361 @example
12362 m4_map([m4_count], [])
12363 @result{}
12364 m4_map([ m4_count], [[],
12365                      [[1]],
12366                      [[1], [2]]])
12367 @result{} 1 2
12368 m4_mapall([ m4_count], [[],
12369                         [[1]],
12370                         [[1], [2]]])
12371 @result{} 0 1 2
12372 m4_map_sep([m4_eval], [,], [[[1+2]],
12373                             [[10], [16]]])
12374 @result{}3,a
12375 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
12376 @result{}a,b
12377 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
12378 @result{}2
12379 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
12380 @result{}a,b
12381 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
12382 @result{}1
12383 @end example
12384 @end defmac
12386 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
12387 @msindex{map_args}
12388 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
12389 argument.  In the following example, three solutions are presented with
12390 the same expansion; the solution using @code{m4_map_args} is the most
12391 efficient.
12392 @example
12393 m4_define([active], [ACTIVE])dnl
12394 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
12395 @result{} plain active
12396 m4_map([ m4_echo], [[[plain]], [[active]]])
12397 @result{} plain active
12398 m4_map_args([ m4_echo], [plain], [active])
12399 @result{} plain active
12400 @end example
12402 In cases where it is useful to operate on additional parameters besides
12403 the list elements, the macro @code{m4_curry} can be used in @var{macro}
12404 to supply the argument currying necessary to generate the desired
12405 argument list.  In the following example, @code{list_add_n} is more
12406 efficient than @code{list_add_x}.  On the other hand, using
12407 @code{m4_map_args_sep} can be even more efficient.
12409 @example
12410 m4_define([list], [[1], [2], [3]])dnl
12411 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
12412 dnl list_add_n(N, ARG...)
12413 dnl Output a list consisting of each ARG added to N
12414 m4_define([list_add_n],
12415 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
12416 list_add_n([1], list)
12417 @result{}2,3,4
12418 list_add_n([2], list)
12419 @result{}3,4,5
12420 m4_define([list_add_x],
12421 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
12422   [,add([$1],m4_defn([var]))]))])dnl
12423 list_add_x([1], list)
12424 @result{}2,3,4
12425 @end example
12426 @end defmac
12428 @defmac m4_map_args_pair (@var{macro}, @dvarv{macro-end, macro}, @
12429   @var{arg}@dots{})
12430 @msindex{map_args_pair}
12431 For every pair of arguments @var{arg}, invoke @var{macro} with two
12432 arguments.  If there is an odd number of arguments, invoke
12433 @var{macro-end}, which defaults to @var{macro}, with the remaining
12434 argument.
12436 @example
12437 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
12438 @result{}, 2, 1, 3
12439 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
12440 @result{}, 2, 1, [3]
12441 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
12442 @result{}, 2, 1, 4, 3
12443 @end example
12444 @end defmac
12446 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
12447 @msindex{map_args_sep}
12448 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
12449 argument, additionally expanding @var{sep} between arguments.  One
12450 common use of this macro is constructing a macro call, where the opening
12451 and closing parentheses are split between @var{pre} and @var{post}; in
12452 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
12453 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
12454 macro provides the most efficient means for iterating over an arbitrary
12455 list of arguments, particularly when repeatedly constructing a macro
12456 call with more arguments than @var{arg}.
12457 @end defmac
12459 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
12460 @msindex{map_args_w}
12461 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
12462 the whitespace-separated @var{string}, additionally expanding @var{sep}
12463 between words.  This macro provides the most efficient means for
12464 iterating over a whitespace-separated string.  In particular,
12465 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
12466 efficient than @code{m4_foreach_w([var], [@var{string}],
12467 [@var{action}(m4_defn([var]))])}.
12468 @end defmac
12470 @defmac m4_shiftn (@var{count}, @dots{})
12471 @defmacx m4_shift2 (@dots{})
12472 @defmacx m4_shift3 (@dots{})
12473 @msindex{shift2}
12474 @msindex{shift3}
12475 @msindex{shiftn}
12476 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
12477 along with validation that enough arguments were passed in to match the
12478 shift count, and that the count is positive.  @code{m4_shift2} and
12479 @code{m4_shift3} are specializations
12480 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
12481 for two and three shifts, respectively.
12482 @end defmac
12484 @defmac m4_stack_foreach (@var{macro}, @var{action})
12485 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
12486 @msindex{stack_foreach}
12487 @msindex{stack_foreach_lifo}
12488 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
12489 @var{action} with the single argument of a definition of @var{macro}.
12490 @code{m4_stack_foreach} starts with the oldest definition, while
12491 @code{m4_stack_foreach_lifo} starts with the current definition.
12492 @var{action} should not push or pop definitions of @var{macro}, nor is
12493 there any guarantee that the current definition of @var{macro} matches
12494 the argument that was passed to @var{action}.  The macro @code{m4_curry}
12495 can be used if @var{action} needs more than one argument, although in
12496 that case it is more efficient to use @var{m4_stack_foreach_sep}.
12498 Due to technical limitations, there are a few low-level m4sugar
12499 functions, such as @code{m4_pushdef}, that cannot be used as the
12500 @var{macro} argument.
12502 @example
12503 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
12504 m4_stack_foreach([a], [ m4_incr])
12505 @result{} 2 3
12506 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
12507 @result{} cd bcd
12508 @end example
12509 @end defmac
12511 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
12512 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
12513   @ovar{sep})
12514 @msindex{stack_foreach_sep}
12515 @msindex{stack_foreach_sep_lifo}
12516 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
12517 @code{m4_pushdef} definition of @var{macro}, additionally expanding
12518 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
12519 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
12520 the current definition first.  This macro provides the most efficient
12521 means for iterating over a pushdef stack.  In particular,
12522 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
12523 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
12524 @end defmac
12526 @node Evaluation Macros
12527 @subsection Evaluation Macros
12529 The following macros give some control over the order of the evaluation
12530 by adding or removing levels of quotes.
12532 @defmac m4_apply (@var{macro}, @var{list})
12533 @msindex{apply}
12534 Apply the elements of the quoted, comma-separated @var{list} as the
12535 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
12536 without arguments.  Note the difference between @code{m4_indir}, which
12537 expects its first argument to be a macro name but can use names that are
12538 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
12539 other text, but must end in a valid macro name.
12540 @example
12541 m4_apply([m4_count], [])
12542 @result{}0
12543 m4_apply([m4_count], [[]])
12544 @result{}1
12545 m4_apply([m4_count], [[1], [2]])
12546 @result{}2
12547 m4_apply([m4_join], [[|], [1], [2]])
12548 @result{}1|2
12549 @end example
12550 @end defmac
12552 @defmac m4_count (@var{arg}, @dots{})
12553 @msindex{count}
12554 This macro returns the decimal count of the number of arguments it was
12555 passed.
12556 @end defmac
12558 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
12559 @msindex{curry}
12560 This macro performs argument currying.  The expansion of this macro is
12561 another macro name that expects exactly one argument; that argument is
12562 then appended to the @var{arg} list, and then @var{macro} is expanded
12563 with the resulting argument list.
12565 @example
12566 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
12567 @result{}3, 2, 1
12568 @end example
12570 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
12571 pass the definition of a builtin macro as the argument to the output of
12572 @code{m4_curry}; the empty string is used instead of the builtin token.
12573 This behavior is rectified by using M4 1.6 or newer.
12574 @end defmac
12576 @defmac m4_do (@var{arg}, @dots{})
12577 @msindex{do}
12578 This macro loops over its arguments and expands each @var{arg} in
12579 sequence.  Its main use is for readability; it allows the use of
12580 indentation and fewer @code{dnl} to result in the same expansion.  This
12581 macro guarantees that no expansion will be concatenated with subsequent
12582 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
12583 @var{arg@dots{}}))}.
12585 @example
12586 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
12587 m4_do([a],[b])c
12588 @result{}abc
12589 m4_unquote(m4_join([],[a],[b]))c
12590 @result{}3
12591 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
12592 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
12593 m4_do([a],[b])c
12594 @result{}ABC
12595 m4_unquote(m4_join([],[a],[b]))c
12596 @result{}3
12597 @end example
12598 @end defmac
12600 @defmac m4_dquote (@var{arg}, @dots{})
12601 @msindex{dquote}
12602 Return the arguments as a quoted list of quoted arguments.
12603 Conveniently, if there is just one @var{arg}, this effectively adds a
12604 level of quoting.
12605 @end defmac
12607 @defmac m4_dquote_elt (@var{arg}, @dots{})
12608 @msindex{dquote_elt}
12609 Return the arguments as a series of double-quoted arguments.  Whereas
12610 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
12611 as many arguments as it was passed.
12612 @end defmac
12614 @defmac m4_echo (@var{arg}, @dots{})
12615 @msindex{echo}
12616 Return the arguments, with the same level of quoting.  Other than
12617 discarding whitespace after unquoted commas, this macro is a no-op.
12618 @end defmac
12620 @defmac m4_expand (@var{arg})
12621 @msindex{expand}
12622 Return the expansion of @var{arg} as a quoted string.  Whereas
12623 @code{m4_quote} is designed to collect expanded text into a single
12624 argument, @code{m4_expand} is designed to perform one level of expansion
12625 on quoted text.  One distinction is in the treatment of whitespace
12626 following a comma in the original @var{arg}.  Any time multiple
12627 arguments are collected into one with @code{m4_quote}, the M4 argument
12628 collection rules discard the whitespace.  However, with @code{m4_expand},
12629 whitespace is preserved, even after the expansion of macros contained in
12630 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
12631 would involve an unterminated comment, whereas expanding that same text
12632 as the argument to @code{m4_quote} runs into difficulty in finding the
12633 end of the argument.  Since manipulating diversions during argument
12634 collection is inherently unsafe, @code{m4_expand} issues an error if
12635 @var{arg} attempts to change the current diversion (@pxref{Diversion
12636 support}).
12638 @example
12639 m4_define([active], [ACT, IVE])dnl
12640 m4_define([active2], [[ACT, IVE]])dnl
12641 m4_quote(active, active)
12642 @result{}ACT,IVE,ACT,IVE
12643 m4_expand([active, active])
12644 @result{}ACT, IVE, ACT, IVE
12645 m4_quote(active2, active2)
12646 @result{}ACT, IVE,ACT, IVE
12647 m4_expand([active2, active2])
12648 @result{}ACT, IVE, ACT, IVE
12649 m4_expand([# m4_echo])
12650 @result{}# m4_echo
12651 m4_quote(# m4_echo)
12653 @result{}# m4_echo)
12654 @result{}
12655 @end example
12657 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
12658 literal unbalanced quotes, but that quadrigraphs can be used when
12659 unbalanced output is necessary.  Likewise, unbalanced parentheses should
12660 be supplied with double quoting or a quadrigraph.
12662 @example
12663 m4_define([pattern], [[!@@<:@@]])dnl
12664 m4_define([bar], [BAR])dnl
12665 m4_expand([case $foo in
12666   m4_defn([pattern])@@:@}@@ bar ;;
12667   *[)] blah ;;
12668 esac])
12669 @result{}case $foo in
12670 @result{}  [![]) BAR ;;
12671 @result{}  *) blah ;;
12672 @result{}esac
12673 @end example
12674 @end defmac
12676 @defmac m4_ignore (@dots{})
12677 @msindex{ignore}
12678 This macro was introduced in Autoconf 2.62.  Expands to nothing,
12679 ignoring all of its arguments.  By itself, this isn't very useful.
12680 However, it can be used to conditionally ignore an arbitrary number of
12681 arguments, by deciding which macro name to apply to a list of arguments.
12682 @example
12683 dnl foo outputs a message only if [debug] is defined.
12684 m4_define([foo],
12685 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
12686 @end example
12688 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
12689 serve the same purpose, although it is less readable.
12690 @end defmac
12692 @defmac m4_make_list (@var{arg}, @dots{})
12693 @msindex{make_list}
12694 This macro exists to aid debugging of M4sugar algorithms.  Its net
12695 effect is similar to @code{m4_dquote}---it produces a quoted list of
12696 quoted arguments, for each @var{arg}.  The difference is that this
12697 version uses a comma-newline separator instead of just comma, to improve
12698 readability of the list; with the result that it is less efficient than
12699 @code{m4_dquote}.
12700 @example
12701 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
12702 m4_dquote(zero, [one], [[two]])
12703 @result{}[0],[one],[[two]]
12704 m4_make_list(zero, [one], [[two]])
12705 @result{}[0],
12706 @result{}[one],
12707 @result{}[[two]]
12708 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
12709 @result{} 0 1 two
12710 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
12711 @result{} 0 1 two
12712 @end example
12713 @end defmac
12715 @c m4_noquote is too dangerous to document - it invokes macros that
12716 @c probably rely on @samp{[]} nested quoting for proper operation.  The
12717 @c user should generally prefer m4_unquote instead.
12719 @defmac m4_quote (@var{arg}, @dots{})
12720 @msindex{quote}
12721 Return the arguments as a single entity, i.e., wrap them into a pair of
12722 quotes.  This effectively collapses multiple arguments into one,
12723 although it loses whitespace after unquoted commas in the process.
12724 @end defmac
12726 @defmac m4_reverse (@var{arg}, @dots{})
12727 @msindex{reverse}
12728 Outputs each argument with the same level of quoting, but in reverse
12729 order, and with space following each comma for readability.
12731 @example
12732 m4_define([active], [ACT,IVE])
12733 @result{}
12734 m4_reverse(active, [active])
12735 @result{}active, IVE, ACT
12736 @end example
12737 @end defmac
12739 @defmac m4_unquote (@var{arg}, @dots{})
12740 @msindex{unquote}
12741 This macro was introduced in Autoconf 2.62.  Expand each argument,
12742 separated by commas.  For a single @var{arg}, this effectively removes a
12743 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
12744 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
12745 this results in an unquoted list of expansions.  This is commonly used
12746 with @code{m4_split}, in order to convert a single quoted list into a
12747 series of quoted elements.
12748 @end defmac
12750 The following example aims at emphasizing the difference between several
12751 scenarios: not using these macros, using @code{m4_defn}, using
12752 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
12754 @example
12755 $ @kbd{cat example.m4}
12756 dnl Overquote, so that quotes are visible.
12757 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
12758 m4_define([a], [A])
12759 m4_define([mkargs], [1, 2[,] 3])
12760 m4_define([arg1], [[$1]])
12761 m4_divert([0])dnl
12762 show(a, b)
12763 show([a, b])
12764 show(m4_quote(a, b))
12765 show(m4_dquote(a, b))
12766 show(m4_expand([a, b]))
12768 arg1(mkargs)
12769 arg1([mkargs])
12770 arg1(m4_defn([mkargs]))
12771 arg1(m4_quote(mkargs))
12772 arg1(m4_dquote(mkargs))
12773 arg1(m4_expand([mkargs]))
12774 $ @kbd{autom4te -l m4sugar example.m4}
12775 $1 = A, $@@ = [A],[b]
12776 $1 = a, b, $@@ = [a, b]
12777 $1 = A,b, $@@ = [A,b]
12778 $1 = [A],[b], $@@ = [[A],[b]]
12779 $1 = A, b, $@@ = [A, b]
12782 mkargs
12783 1, 2[,] 3
12784 1,2, 3
12785 [1],[2, 3]
12786 1, 2, 3
12787 @end example
12790 @node Text processing Macros
12791 @subsection String manipulation in M4
12793 The following macros may be used to manipulate strings in M4.  Many of
12794 the macros in this section intentionally result in quoted strings as
12795 output, rather than subjecting the arguments to further expansions.  As
12796 a result, if you are manipulating text that contains active M4
12797 characters, the arguments are passed with single quoting rather than
12798 double.
12800 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
12801 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
12802   @ovar{if-uniq}, @ovar{if-duplicate})
12803 @msindex{append}
12804 @msindex{append_uniq}
12805 Redefine @var{macro-name} to its former contents with @var{separator}
12806 and @var{string} added at the end.  If @var{macro-name} was undefined
12807 before (but not if it was defined but empty), then no @var{separator} is
12808 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
12809 are expanded during this macro; instead, they are expanded when
12810 @var{macro-name} is invoked.
12812 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
12813 to grow strings without duplicating substrings.  Additionally,
12814 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
12815 @var{if-uniq} is expanded if @var{string} was appended, and
12816 @var{if-duplicate} is expanded if @var{string} was already present.
12817 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
12818 occurs within @var{string}, since that can lead to duplicates.
12820 Note that @code{m4_append} can scale linearly in the length of the final
12821 string, depending on the quality of the underlying M4 implementation,
12822 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
12823 If an algorithm can tolerate duplicates in the final string, use the
12824 former for speed.  If duplicates must be avoided, consider using
12825 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
12827 @example
12828 m4_define([active], [ACTIVE])dnl
12829 m4_append([sentence], [This is an])dnl
12830 m4_append([sentence], [ active ])dnl
12831 m4_append([sentence], [symbol.])dnl
12832 sentence
12833 @result{}This is an ACTIVE symbol.
12834 m4_undefine([active])dnl
12835 @result{}This is an active symbol.
12836 m4_append_uniq([list], [one], [, ], [new], [existing])
12837 @result{}new
12838 m4_append_uniq([list], [one], [, ], [new], [existing])
12839 @result{}existing
12840 m4_append_uniq([list], [two], [, ], [new], [existing])
12841 @result{}new
12842 m4_append_uniq([list], [three], [, ], [new], [existing])
12843 @result{}new
12844 m4_append_uniq([list], [two], [, ], [new], [existing])
12845 @result{}existing
12846 list
12847 @result{}one, two, three
12848 m4_dquote(list)
12849 @result{}[one],[two],[three]
12850 m4_append([list2], [one], [[, ]])dnl
12851 m4_append_uniq([list2], [two], [[, ]])dnl
12852 m4_append([list2], [three], [[, ]])dnl
12853 list2
12854 @result{}one, two, three
12855 m4_dquote(list2)
12856 @result{}[one, two, three]
12857 @end example
12858 @end defmac
12860 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
12861 @msindex{append_uniq_w}
12862 This macro was introduced in Autoconf 2.62.  It is similar to
12863 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
12864 separated list of words to append, and only appends unique words.
12865 @var{macro-name} is updated with a single space between new words.
12866 @example
12867 m4_append_uniq_w([numbers], [1 1 2])dnl
12868 m4_append_uniq_w([numbers], [ 2 3 ])dnl
12869 numbers
12870 @result{}1 2 3
12871 @end example
12872 @end defmac
12874 @defmac m4_chomp (@var{string})
12875 @defmacx m4_chomp_all (@var{string})
12876 @msindex{chomp}
12877 @msindex{chomp_all}
12878 Output @var{string} in quotes, but without a trailing newline.  The
12879 macro @code{m4_chomp} is slightly faster, and removes at most one
12880 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
12881 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
12882 and backslash does not influence the result.
12883 @end defmac
12885 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
12886   @var{suffix-1}, @ovar{suffix-2}, @dots{})
12887 @msindex{combine}
12888 This macro produces a quoted string containing the pairwise combination
12889 of every element of the quoted, comma-separated @var{prefix-list}, and
12890 every element from the @var{suffix} arguments.  Each pairwise
12891 combination is joined with @var{infix} in the middle, and successive
12892 pairs are joined by @var{separator}.  No expansion occurs on any of the
12893 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
12894 list is empty, but the lists can contain empty elements.
12895 @example
12896 m4_define([a], [oops])dnl
12897 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
12898 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
12899 m4_combine([, ], [[a], [b]], [-])
12900 @result{}
12901 m4_combine([, ], [[a], [b]], [-], [])
12902 @result{}a-, b-
12903 m4_combine([, ], [], [-], [1], [2])
12904 @result{}
12905 m4_combine([, ], [[]], [-], [1], [2])
12906 @result{}-1, -2
12907 @end example
12908 @end defmac
12910 @defmac m4_escape (@var{string})
12911 @msindex{escape}
12912 Convert all instances of @samp{[}, @samp{]}, @samp{#}, and @samp{$}
12913 within @var{string} into their respective quadrigraphs.  The result is
12914 still a quoted string.
12915 @end defmac
12917 @defmac m4_flatten (@var{string})
12918 @msindex{flatten}
12919 Flatten @var{string} into a single line.  Delete all backslash-newline
12920 pairs, and replace all remaining newlines with a space.  The result is
12921 still a quoted string.
12922 @end defmac
12924 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
12925 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
12926 @msindex{join}
12927 @msindex{joinall}
12928 Concatenate each @var{arg}, separated by @var{separator}.
12929 @code{joinall} uses every argument, while @code{join} omits empty
12930 arguments so that there are no back-to-back separators in the output.
12931 The result is a quoted string.
12932 @example
12933 m4_define([active], [ACTIVE])dnl
12934 m4_join([|], [one], [], [active], [two])
12935 @result{}one|active|two
12936 m4_joinall([|], [one], [], [active], [two])
12937 @result{}one||active|two
12938 @end example
12940 Note that if all you intend to do is join @var{args} with commas between
12941 them, to form a quoted list suitable for @code{m4_foreach}, it is more
12942 efficient to use @code{m4_dquote}.
12943 @end defmac
12945 @defmac m4_newline (@ovar{text})
12946 @msindex{newline}
12947 This macro was introduced in Autoconf 2.62, and expands to a newline,
12948 followed by any @var{text}.
12949 It is primarily useful for maintaining macro formatting, and ensuring
12950 that M4 does not discard leading whitespace during argument collection.
12951 @end defmac
12953 @defmac m4_normalize (@var{string})
12954 @msindex{normalize}
12955 Remove leading and trailing spaces and tabs, sequences of
12956 backslash-then-newline, and replace multiple spaces, tabs, and newlines
12957 with a single space.  This is a combination of @code{m4_flatten} and
12958 @code{m4_strip}.  To determine if @var{string} consists only of bytes
12959 that would be removed by @code{m4_normalize}, you can use
12960 @code{m4_ifblank}.
12961 @end defmac
12963 @defmac m4_re_escape (@var{string})
12964 @msindex{re_escape}
12965 Backslash-escape all characters in @var{string} that are active in
12966 regexps.
12967 @end defmac
12969 @c We cannot use @dvar because the macro expansion mistreats backslashes.
12970 @defmac m4_split (@var{string}, @r{[}@var{regexp} = @samp{[\t ]+}@r{]})
12971 @msindex{split}
12972 Split @var{string} into an M4 list of elements quoted by @samp{[} and
12973 @samp{]}, while keeping white space at the beginning and at the end.
12974 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
12975 If @var{string} is empty, the result is an empty list.
12976 @end defmac
12978 @defmac m4_strip (@var{string})
12979 @msindex{strip}
12980 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
12981 reduced to a single space, then leading and trailing spaces are removed.
12982 The result is still a quoted string.  Note that this does not interfere
12983 with newlines; if you want newlines stripped as well, consider
12984 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.  To
12985 quickly test if @var{string} has only whitespace, use @code{m4_ifblank}.
12986 @end defmac
12988 @defmac m4_text_box (@var{message}, @dvar{frame, -})
12989 @msindex{text_box}
12990 Add a text box around @var{message}, using @var{frame} as the border
12991 character above and below the message.  The @var{frame} argument must be
12992 a single byte, and does not support quadrigraphs.
12993 The frame correctly accounts for
12994 the subsequent expansion of @var{message}.  For example:
12995 @example
12996 m4_define([macro], [abc])dnl
12997 m4_text_box([macro])
12998 @result{}## --- ##
12999 @result{}## abc ##
13000 @result{}## --- ##
13001 @end example
13003 The @var{message} must contain balanced quotes and parentheses, although
13004 quadrigraphs can be used to work around this.
13005 @end defmac
13007 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
13008   @dvarv{prefix1, prefix}, @dvar{width, 79})
13009 @msindex{text_wrap}
13010 Break @var{string} into a series of whitespace-separated words, then
13011 output those words separated by spaces, and wrapping lines any time the
13012 output would exceed @var{width} columns.  If given, @var{prefix1} begins
13013 the first line, and @var{prefix} begins all wrapped lines.  If
13014 @var{prefix1} is longer than @var{prefix}, then the first line consists
13015 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
13016 padding is inserted so that the first word of @var{string} begins at the
13017 same indentation as all wrapped lines.  Note that using literal tab
13018 characters in any of the arguments will interfere with the calculation
13019 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
13020 words of @var{string}, although quadrigraphs are recognized.
13022 For some examples:
13023 @example
13024 m4_text_wrap([Short string */], [   ], [/* ], [20])
13025 @result{}/* Short string */
13026 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
13027 @result{}/* Much longer
13028 @result{}   string */
13029 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
13030 @result{}  --short Short doc.
13031 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
13032 @result{}  --too-wide
13033 @result{}          Short doc.
13034 m4_text_wrap([Super long documentation.], [     ],
13035              [  --too-wide ], 30)
13036 @result{}  --too-wide
13037 @result{}     Super long
13038 @result{}     documentation.
13039 @end example
13040 @end defmac
13042 @defmac m4_tolower (@var{string})
13043 @defmacx m4_toupper (@var{string})
13044 @msindex{tolower}
13045 @msindex{toupper}
13046 Return @var{string} with letters converted to upper or lower case,
13047 respectively.
13048 @end defmac
13050 @node Number processing Macros
13051 @subsection Arithmetic computation in M4
13053 The following macros facilitate integer arithmetic operations.
13054 Where a parameter is documented as taking an arithmetic expression, you
13055 can use anything that can be parsed by @code{m4_eval}.
13057 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
13058 @msindex{cmp}
13059 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
13060 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
13061 equal, and @samp{1} if @var{expr-1} is larger.
13062 @end defmac
13064 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
13065 @msindex{list_cmp}
13066 Compare the two M4 lists consisting of comma-separated arithmetic
13067 expressions, left to right.  Expand to @samp{-1} for the first element
13068 pairing where the value from @var{list-1} is smaller, @samp{1} where the
13069 value from @var{list-2} is smaller, or @samp{0} if both lists have the
13070 same values.  If one list is shorter than the other, the remaining
13071 elements of the longer list are compared against zero.
13072 @example
13073 m4_list_cmp([1, 0],       [1])
13074 @result{}0
13075 m4_list_cmp([1, [1 * 0]], [1, 0])
13076 @result{}0
13077 m4_list_cmp([1, 2],       [1, 0])
13078 @result{}1
13079 m4_list_cmp([1, [1+1], 3],[1, 2])
13080 @result{}1
13081 m4_list_cmp([1, 2, -3],   [1, 2])
13082 @result{}-1
13083 m4_list_cmp([1, 0],       [1, 2])
13084 @result{}-1
13085 m4_list_cmp([1],          [1, 2])
13086 @result{}-1
13087 @end example
13088 @end defmac
13090 @defmac m4_max (@var{arg}, @dots{})
13091 @msindex{max}
13092 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13093 of the maximum arithmetic expression among all the arguments.
13094 @end defmac
13096 @defmac m4_min (@var{arg}, @dots{})
13097 @msindex{min}
13098 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
13099 of the minimum arithmetic expression among all the arguments.
13100 @end defmac
13102 @defmac m4_sign (@var{expr})
13103 @msindex{sign}
13104 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
13105 @samp{1} if it is positive, and @samp{0} if it is zero.
13106 @end defmac
13108 @anchor{m4_version_compare}
13109 @defmac m4_version_compare (@var{version-1}, @var{version-2})
13110 @msindex{version_compare}
13111 This macro was introduced in Autoconf 2.53, but had a number of
13112 usability limitations that were not lifted until Autoconf 2.62.  Compare
13113 the version strings @var{version-1} and @var{version-2}, and expand to
13114 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
13115 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
13116 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
13117 element is a number along with optional case-insensitive letters
13118 designating beta releases.  The comparison stops at the leftmost element
13119 that contains a difference, although a 0 element compares equal to a
13120 missing element.
13122 It is permissible to include commit identifiers in @var{version}, such
13123 as an abbreviated SHA1 of the commit, provided there is still a
13124 monotonically increasing prefix to allow for accurate version-based
13125 comparisons.  For example, this paragraph was written when the
13126 development snapshot of autoconf claimed to be at version
13127 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
13128 abbreviated commit identification of @samp{dc51}.
13130 @example
13131 m4_version_compare([1.1], [2.0])
13132 @result{}-1
13133 m4_version_compare([2.0b], [2.0a])
13134 @result{}1
13135 m4_version_compare([1.1.1], [1.1.1a])
13136 @result{}-1
13137 m4_version_compare([1.2], [1.1.1a])
13138 @result{}1
13139 m4_version_compare([1.0], [1])
13140 @result{}0
13141 m4_version_compare([1.1pre], [1.1PRE])
13142 @result{}0
13143 m4_version_compare([1.1a], [1,10])
13144 @result{}-1
13145 m4_version_compare([2.61a], [2.61a-248-dc51])
13146 @result{}-1
13147 m4_version_compare([2.61b], [2.61a-248-dc51])
13148 @result{}1
13149 @end example
13150 @end defmac
13152 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
13153   @dvar{if-old, m4_fatal})
13154 @msindex{version_prereq}
13155 Compares @var{version} against the version of Autoconf currently
13156 running.  If the running version is at @var{version} or newer, expand
13157 @var{if-new-enough}, but if @var{version} is larger than the version
13158 currently executing, expand @var{if-old}, which defaults to printing an
13159 error message and exiting m4sugar with status 63.  When given only one
13160 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
13161 Remember that the autoconf philosophy favors feature checks over version
13162 checks.
13163 @end defmac
13165 @node Set manipulation Macros
13166 @subsection Set manipulation in M4
13167 @cindex Set manipulation
13168 @cindex Data structure, set
13169 @cindex Unordered set manipulation
13171 Sometimes, it is necessary to track a set of data, where the order does
13172 not matter and where there are no duplicates in the set.  The following
13173 macros facilitate set manipulations.  Each set is an opaque object,
13174 which can only be accessed via these basic operations.  The underlying
13175 implementation guarantees linear scaling for set creation, which is more
13176 efficient than using the quadratic @code{m4_append_uniq}.  Both set
13177 names and values can be arbitrary strings, except for unbalanced quotes.
13178 This implementation ties up memory for removed elements until the next
13179 operation that must traverse all the elements of a set; and although
13180 that may slow down some operations until the memory for removed elements
13181 is pruned, it still guarantees linear performance.
13183 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
13184 @msindex{set_add}
13185 Adds the string @var{value} as a member of set @var{set}.  Expand
13186 @var{if-uniq} if the element was added, or @var{if-dup} if it was
13187 previously in the set.  Operates in amortized constant time, so that set
13188 creation scales linearly.
13189 @end defmac
13191 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
13192 @msindex{set_add_all}
13193 Adds each @var{value} to the set @var{set}.  This is slightly more
13194 efficient than repeatedly invoking @code{m4_set_add}.
13195 @end defmac
13197 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
13198  @ovar{if-absent})
13199 @msindex{set_contains}
13200 Expands @var{if-present} if the string @var{value} is a member of
13201 @var{set}, otherwise @var{if-absent}.
13203 @example
13204 m4_set_contains([a], [1], [yes], [no])
13205 @result{}no
13206 m4_set_add([a], [1], [added], [dup])
13207 @result{}added
13208 m4_set_add([a], [1], [added], [dup])
13209 @result{}dup
13210 m4_set_contains([a], [1], [yes], [no])
13211 @result{}yes
13212 m4_set_remove([a], [1], [removed], [missing])
13213 @result{}removed
13214 m4_set_contains([a], [1], [yes], [no])
13215 @result{}no
13216 m4_set_remove([a], [1], [removed], [missing])
13217 @result{}missing
13218 @end example
13219 @end defmac
13221 @defmac m4_set_contents (@var{set}, @ovar{sep})
13222 @defmacx m4_set_dump (@var{set}, @ovar{sep})
13223 @msindex{set_contents}
13224 @msindex{set_dump}
13225 Expands to a single string consisting of all the members of the set
13226 @var{set}, each separated by @var{sep}, which is not expanded.
13227 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
13228 memory occupied by removed elements, while @code{m4_set_dump} is a
13229 faster one-shot action that also deletes the set.  No provision is made
13230 for disambiguating members that contain a non-empty @var{sep} as a
13231 substring; use @code{m4_set_empty} to distinguish between an empty set
13232 and the set containing only the empty string.  The order of the output
13233 is unspecified; in the current implementation, part of the speed of
13234 @code{m4_set_dump} results from using a different output order than
13235 @code{m4_set_contents}.  These macros scale linearly in the size of the
13236 set before memory pruning, and @code{m4_set_contents([@var{set}],
13237 [@var{sep}])} is faster than
13238 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
13240 @example
13241 m4_set_add_all([a], [1], [2], [3])
13242 @result{}
13243 m4_set_contents([a], [-])
13244 @result{}1-2-3
13245 m4_joinall([-]m4_set_listc([a]))
13246 @result{}1-2-3
13247 m4_set_dump([a], [-])
13248 @result{}3-2-1
13249 m4_set_contents([a])
13250 @result{}
13251 m4_set_add([a], [])
13252 @result{}
13253 m4_set_contents([a], [-])
13254 @result{}
13255 @end example
13256 @end defmac
13258 @defmac m4_set_delete (@var{set})
13259 @msindex{set_delete}
13260 Delete all elements and memory associated with @var{set}.  This is
13261 linear in the set size, and faster than removing one element at a time.
13262 @end defmac
13264 @defmac m4_set_difference (@var{seta}, @var{setb})
13265 @defmacx m4_set_intersection (@var{seta}, @var{setb})
13266 @defmacx m4_set_union (@var{seta}, @var{setb})
13267 @msindex{set_difference}
13268 @msindex{set_intersection}
13269 @msindex{set_union}
13270 Compute the relation between @var{seta} and @var{setb}, and output the
13271 result as a list of quoted arguments without duplicates and with a
13272 leading comma.  Set difference selects the elements in @var{seta} but
13273 not @var{setb}, intersection selects only elements in both sets, and
13274 union selects elements in either set.  These actions are linear in the
13275 sum of the set sizes.  The leading comma is necessary to distinguish
13276 between no elements and the empty string as the only element.
13278 @example
13279 m4_set_add_all([a], [1], [2], [3])
13280 @result{}
13281 m4_set_add_all([b], [3], [], [4])
13282 @result{}
13283 m4_set_difference([a], [b])
13284 @result{},1,2
13285 m4_set_difference([b], [a])
13286 @result{},,4
13287 m4_set_intersection([a], [b])
13288 @result{},3
13289 m4_set_union([a], [b])
13290 @result{},1,2,3,,4
13291 @end example
13292 @end defmac
13294 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
13295 @msindex{set_empty}
13296 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
13297 expand @var{if-elements}.  This macro operates in constant time.  Using
13298 this macro can help disambiguate output from @code{m4_set_contents} or
13299 @code{m4_set_list}.
13300 @end defmac
13302 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
13303 @msindex{set_foreach}
13304 For each element in the set @var{set}, expand @var{action} with the
13305 macro @var{variable} defined as the set element.  Behavior is
13306 unspecified if @var{action} recursively lists the contents of @var{set}
13307 (although listing other sets is acceptable), or if it modifies the set
13308 in any way other than removing the element currently contained in
13309 @var{variable}.  This macro is faster than the corresponding
13310 @code{m4_foreach([@var{variable}],
13311 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
13312 although @code{m4_set_map} might be faster still.
13314 @example
13315 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
13316 @result{}
13317 m4_set_contents([a])
13318 @result{}12345
13319 m4_set_foreach([a], [i],
13320   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
13321 @result{}24
13322 m4_set_contents([a])
13323 @result{}135
13324 @end example
13325 @end defmac
13327 @defmac m4_set_list (@var{set})
13328 @defmacx m4_set_listc (@var{set})
13329 @msindex{set_list}
13330 @msindex{set_listc}
13331 Produce a list of arguments, where each argument is a quoted element
13332 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
13333 by adding a leading comma if there are any set elements, whereas the
13334 variant @code{m4_set_list} cannot distinguish between an empty set and a
13335 set containing only the empty string.  These can be directly used in
13336 macros that take multiple arguments, such as @code{m4_join} or
13337 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
13338 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
13339 memory occupied by removed elements is reclaimed during these macros.
13341 @example
13342 m4_set_add_all([a], [1], [2], [3])
13343 @result{}
13344 m4_set_list([a])
13345 @result{}1,2,3
13346 m4_set_list([b])
13347 @result{}
13348 m4_set_listc([b])
13349 @result{}
13350 m4_count(m4_set_list([b]))
13351 @result{}1
13352 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13353 @result{}0
13354 m4_set_add([b], [])
13355 @result{}
13356 m4_set_list([b])
13357 @result{}
13358 m4_set_listc([b])
13359 @result{},
13360 m4_count(m4_set_list([b]))
13361 @result{}1
13362 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
13363 @result{}1
13364 @end example
13365 @end defmac
13367 @defmac m4_set_map (@var{set}, @var{action})
13368 @msindex{set_map}
13369 For each element in the set @var{set}, expand @var{action} with a single
13370 argument of the set element.  Behavior is unspecified if @var{action}
13371 recursively lists the contents of @var{set} (although listing other sets
13372 is acceptable), or if it modifies the set in any way other than removing
13373 the element passed as an argument.  This macro is faster than either
13374 corresponding counterpart of
13375 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
13376 @code{m4_set_foreach([@var{set}], [var],
13377 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
13378 if more than one argument is needed for @var{action}, although it is
13379 more efficient to use @code{m4_set_map_sep} in that case.
13380 @end defmac
13382 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
13383 @msindex{set_map_sep}
13384 For each element in the set @var{set}, expand
13385 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
13386 between elements.  Behavior is unspecified if the expansion recursively
13387 lists the contents of @var{set} (although listing other sets
13388 is acceptable), or if it modifies the set in any way other than removing
13389 the element visited by the expansion.  This macro provides the most
13390 efficient means for non-destructively visiting the elements of a set; in
13391 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
13392 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
13393 @end defmac
13395 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
13396  @ovar{if-absent})
13397 @msindex{set_remove}
13398 If @var{value} is an element in the set @var{set}, then remove it and
13399 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
13400 operates in constant time so that multiple removals will scale linearly
13401 rather than quadratically; but when used outside of
13402 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
13403 until the set is later
13404 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
13405 other set operations are then less efficient between the time of element
13406 removal and subsequent memory compaction, but still maintain their
13407 guaranteed scaling performance.
13408 @end defmac
13410 @defmac m4_set_size (@var{set})
13411 @msindex{set_size}
13412 Expand to the size of the set @var{set}.  This implementation operates
13413 in constant time, and is thus more efficient than
13414 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
13415 @end defmac
13418 @node Forbidden Patterns
13419 @subsection Forbidden Patterns
13420 @cindex Forbidden patterns
13421 @cindex Patterns, forbidden
13423 M4sugar provides a means to define suspicious patterns, patterns
13424 describing tokens which should not be found in the output.  For
13425 instance, if an Autoconf @file{configure} script includes tokens such as
13426 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
13427 wrong (typically a macro was not evaluated because of overquotation).
13429 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
13430 Additional layers, such as M4sh and Autoconf, add additional forbidden
13431 patterns to the list.
13433 @defmac m4_pattern_forbid (@var{pattern})
13434 @msindex{pattern_forbid}
13435 Declare that no token matching @var{pattern} must be found in the
13436 output.  The output file is (temporarily) split into one word per line
13437 as part of the @command{autom4te} post-processing, with each line (and
13438 therefore word) then being checked against the Perl regular expression
13439 @var{pattern}.  If the regular expression matches, and
13440 @code{m4_pattern_allow} does not also match, then an error is raised.
13442 Comments are not checked; this can be a problem if, for instance, you
13443 have some macro left unexpanded after an @samp{#include}.  No consensus
13444 is currently found in the Autoconf community, as some people consider it
13445 should be valid to name macros in comments (which doesn't make sense to
13446 the authors of this documentation: input, such as macros, should be
13447 documented by @samp{dnl} comments; reserving @samp{#}-comments to
13448 document the output).
13450 As an example, if you define your own macros that begin with @samp{M_}
13451 and are composed from capital letters and underscores, the specification
13452 of @code{m4_pattern_forbid([^M_[A-Z_]+])} will ensure all your macros
13453 are expanded when not used in comments.
13455 As an example of a common use of this macro, consider what happens in
13456 packages that want to use the @command{pkg-config} script via the
13457 third-party @code{PKG_CHECK_MODULES} macro.  By default, if a developer
13458 checks out the development tree but has not yet installed the pkg-config
13459 macros locally, they can manage to successfully run @command{autoconf}
13460 on the package, but the resulting @file{configure} file will likely
13461 result in a confusing shell message about a syntax error on the line
13462 mentioning the unexpanded @code{PKG_CHECK_MODULES} macro.  On the other hand,
13463 if @file{configure.ac} includes @code{m4_pattern_forbid([^PKG_])}, the
13464 missing pkg-config macros will be detected immediately without allowing
13465 @command{autoconf} to succeed.
13466 @end defmac
13468 Of course, you might encounter exceptions to these generic rules, for
13469 instance you might have to refer to @samp{$m4_flags}.
13471 @defmac m4_pattern_allow (@var{pattern})
13472 @msindex{pattern_allow}
13473 Any token matching @var{pattern} is allowed, including if it matches an
13474 @code{m4_pattern_forbid} pattern.
13476 For example, gnulib uses @code{m4_pattern_forbid([^gl_])} to reserve the
13477 @code{gl_} namespace for itself, but also uses
13478 @code{m4_pattern_allow([^gl_ES$])} to avoid a false negative on the
13479 valid locale name.
13480 @end defmac
13482 @node Debugging via autom4te
13483 @section Debugging via autom4te
13484 @cindex debugging tips
13485 @cindex autom4te debugging tips
13486 @cindex m4sugar debugging tips
13487 At times, it is desirable to see what was happening inside m4, to see
13488 why output was not matching expectations.  However, post-processing done
13489 by @command{autom4te} means that directly using the m4 builtin
13490 @code{m4_traceon} is likely to interfere with operation.  Also, frequent
13491 diversion changes and the concept of forbidden tokens make it difficult
13492 to use @code{m4_defn} to generate inline comments in the final output.
13494 There are a couple of tools to help with this.  One is the use of the
13495 @option{--trace} option provided by @command{autom4te} (as well as each
13496 of the programs that wrap @command{autom4te}, such as
13497 @command{autoconf}), in order to inspect when a macro is called and with
13498 which arguments.  For example, when this paragraph was written, the
13499 autoconf version could be found by:
13501 @example
13502 $ @kbd{autoconf --trace=AC_INIT}
13503 configure.ac:23:AC_INIT:GNU Autoconf:2.63b.95-3963:bug-autoconf@@gnu.org
13504 $ @kbd{autoconf --trace='AC_INIT:version is $2'}
13505 version is 2.63b.95-3963
13506 @end example
13508 Another trick is to print out the expansion of various m4 expressions to
13509 standard error or to an independent file, with no further m4 expansion,
13510 and without interfering with diversion changes or the post-processing
13511 done to standard output.  @code{m4_errprintn} shows a given expression
13512 on standard error.  For example, if you want to see the expansion of an
13513 autoconf primitive or of one of your autoconf macros, you can do it like
13514 this:
13516 @example
13517 $ @kbd{cat <<\EOF > configure.ac}
13518 AC_INIT
13519 m4_errprintn([The definition of AC_DEFINE_UNQUOTED:])
13520 m4_errprintn(m4_defn([AC_DEFINE_UNQUOTED]))
13521 AC_OUTPUT
13523 $ @kbd{autoconf}
13524 @error{}The definition of AC_DEFINE_UNQUOTED:
13525 @error{}_AC_DEFINE_Q([], $@@)
13526 @end example
13528 @node Programming in M4sh
13529 @chapter Programming in M4sh
13531 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
13532 scripts.  This name was coined by Lars J. Aas, who notes that,
13533 according to the Webster's Revised Unabridged Dictionary (1913):
13535 @quotation
13536 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
13537 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
13539 @enumerate 1
13540 @item
13541 A mass of mixed ingredients reduced to a soft pulpy state by beating or
13542 pressure@enddots{}
13544 @item
13545 A mixture of meal or bran and water fed to animals.
13547 @item
13548 A mess; trouble.  [Obs.] --Beau.@: & Fl.
13549 @end enumerate
13550 @end quotation
13552 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
13553 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
13554 and environment variable namespace @samp{^as_}, and the here-document
13555 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
13556 define your own macros or output shell code that conflicts with these
13557 namespaces.
13559 @menu
13560 * Common Shell Constructs::     Portability layer for common shell constructs
13561 * Polymorphic Variables::       Support for indirect variable names
13562 * Initialization Macros::       Macros to establish a sane shell environment
13563 * File Descriptor Macros::      File descriptor macros for input and output
13564 @end menu
13566 @node Common Shell Constructs
13567 @section Common Shell Constructs
13569 M4sh provides portable alternatives for some common shell constructs
13570 that unfortunately are not portable in practice.
13572 @c Deprecated, to be replaced by a better API
13573 @ignore
13574 @defmac AS_BASENAME (@var{file-name})
13575 @asindex{BASENAME}
13576 Output the non-directory portion of @var{file-name}.  For example,
13577 if @code{$file} is @samp{/one/two/three}, the command
13578 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
13579 @end defmac
13580 @end ignore
13582 @defmac AS_BOX (@var{text}, @dvar{char, -})
13583 @asindex{BOX}
13584 Expand into shell code that will output @var{text} surrounded by a box
13585 with @var{char} in the top and bottom border.  @var{text} should not
13586 contain a newline, but may contain shell expansions valid for unquoted
13587 here-documents.  @var{char} defaults to @samp{-}, but can be any
13588 character except @samp{/}, @samp{'}, @samp{"}, @samp{\},
13589 @samp{&}, or @samp{`}.  This is useful for outputting a comment box into
13590 log files to separate distinct phases of script operation.
13591 @end defmac
13593 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
13594   @dots{}, @ovar{default})
13595 @asindex{CASE}
13596 Expand into a shell @samp{case} statement, where @var{word} is matched
13597 against one or more patterns.  @var{if-matched} is run if the
13598 corresponding pattern matched @var{word}, else @var{default} is run.
13599 Avoids several portability issues (@pxref{case, , Limitations of Shell
13600 Builtins}).
13601 @end defmac
13603 @c Deprecated, to be replaced by a better API
13604 @defmac AS_DIRNAME (@var{file-name})
13605 @asindex{DIRNAME}
13606 Output the directory portion of @var{file-name}.  For example,
13607 if @code{$file} is @samp{/one/two/three}, the command
13608 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
13610 This interface may be improved in the future to avoid forks and losing
13611 trailing newlines.
13612 @end defmac
13614 @defmac AS_ECHO (@var{word})
13615 @asindex{ECHO}
13616 Emits @var{word} to the standard output, followed by a newline.  @var{word}
13617 must be a single shell word (typically a quoted string).  The bytes of
13618 @var{word} are output as-is, even if it starts with "-" or contains "\".
13619 Redirections can be placed outside the macro invocation.  This is much
13620 more portable than using @command{echo} (@pxref{echo, , Limitations of
13621 Shell Builtins}).
13622 @end defmac
13624 @defmac AS_ECHO_N (@var{word})
13625 @asindex{ECHO_N}
13626 Emits @var{word} to the standard output, without a following newline.
13627 @var{word} must be a single shell word (typically a quoted string) and,
13628 for portability, should not include more than one newline.  The bytes of
13629 @var{word} are output as-is, even if it starts with "-" or contains "\".
13630 Redirections can be placed outside the macro invocation.
13631 @end defmac
13633 @c We cannot use @dvar because the macro expansion mistreats backslashes.
13634 @defmac AS_ESCAPE (@var{string}, @r{[}@var{chars} = @samp{`\"$}@r{]})
13635 @asindex{ESCAPE}
13636 Expands to @var{string}, with any characters in @var{chars} escaped with
13637 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
13638 and only contain characters from the set @samp{`\"$}; however,
13639 characters may be safely listed more than once in @var{chars} for the
13640 sake of syntax highlighting editors.  The current implementation expands
13641 @var{string} after adding escapes; if @var{string} contains macro calls
13642 that in turn expand to text needing shell quoting, you can use
13643 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
13645 The default for @var{chars} (@samp{\"$`}) is the set of characters
13646 needing escapes when @var{string} will be used literally within double
13647 quotes.  One common variant is the set of characters to protect when
13648 @var{string} will be used literally within back-ticks or an unquoted
13649 here-document (@samp{\$`}).  Another common variant is @samp{""}, which can
13650 be used to form a double-quoted string containing the same expansions
13651 that would have occurred if @var{string} were expanded in an unquoted
13652 here-document; however, when using this variant, care must be taken that
13653 @var{string} does not use double quotes within complex variable
13654 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
13655 with improper escapes.
13657 This macro is often used with @code{AS_ECHO}.  For an example, observe
13658 the output generated by the shell code generated from this snippet:
13660 @example
13661 foo=bar
13662 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
13663 @result{}"$foo" = "bar"
13664 m4_define([macro], [a, [\b]])
13665 AS_ECHO(["AS_ESCAPE([[macro]])"])
13666 @result{}macro
13667 AS_ECHO(["AS_ESCAPE([macro])"])
13668 @result{}a, b
13669 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
13670 @result{}a, \b
13671 @end example
13673 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
13674 @comment the case of @var{string} that does not contain '.
13675 To escape a string that will be placed within single quotes, use:
13677 @example
13678 m4_bpatsubst([[@var{string}]], ['], ['\\''])
13679 @end example
13680 @end defmac
13682 @defmac AS_EXECUTABLE_P (@var{file})
13683 @asindex{EXECUTABLE_P}
13684 Emit code to probe whether @var{file} is a regular file with executable
13685 permissions (and not a directory with search permissions).  The caller
13686 is responsible for quoting @var{file}.
13687 @end defmac
13689 @defmac AS_EXIT (@dvar{status, $?})
13690 @asindex{EXIT}
13691 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
13692 This macro
13693 works around shells that see the exit status of the command prior to
13694 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
13695 of Shell Builtins}).
13696 @end defmac
13698 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
13699 @asindex{IF}
13700 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
13701 run shell code @var{run-if-true1}, else examine further tests.  If no test
13702 exits with a zero status, run shell code @var{run-if-false}, with
13703 simplifications if either @var{run-if-true1} or @var{run-if-false}
13704 is empty.  For example,
13706 @example
13707 AS_IF([test "x$foo" = xyes], [HANDLE_FOO([yes])],
13708       [test "x$foo" != xno], [HANDLE_FOO([maybe])],
13709       [echo foo not specified])
13710 @end example
13712 @noindent
13713 ensures any required macros of @code{HANDLE_FOO}
13714 are expanded before the first test.
13715 @end defmac
13717 @defmac AS_MKDIR_P (@var{file-name})
13718 @asindex{MKDIR_P}
13719 Make the directory @var{file-name}, including intervening directories
13720 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
13721 except that it is portable to older versions of @command{mkdir} that
13722 lack support for the @option{-p} option or for the @option{--}
13723 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
13724 @code{AS_MKDIR_P}
13725 succeeds if @var{file-name} is a symbolic link to an existing directory,
13726 even though Posix is unclear whether @samp{mkdir -p} should
13727 succeed in that case.  If creation of @var{file-name} fails, exit the
13728 script.
13730 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
13731 @end defmac
13733 @defmac AS_SET_STATUS (@var{status})
13734 @asindex{SET_STATUS}
13735 Emit shell code to set the value of @samp{$?} to @var{status}, as
13736 efficiently as possible.  However, this is not guaranteed to abort a
13737 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
13738 Builtins}).  This should also be used at the end of a complex shell
13739 function instead of @samp{return} (@pxref{Shell Functions}) to avoid
13740 a DJGPP shell bug.
13741 @end defmac
13743 @defmac AS_TR_CPP (@var{expression})
13744 @asindex{TR_CPP}
13745 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
13746 For example:
13748 @example
13749 # This outputs "#define HAVE_CHAR_P 1".
13750 # Notice the m4 quoting around #, to prevent an m4 comment
13751 type="char *"
13752 echo "[#]define AS_TR_CPP([HAVE_$type]) 1"
13753 @end example
13754 @end defmac
13756 @defmac AS_TR_SH (@var{expression})
13757 @asindex{TR_SH}
13758 Transform @var{expression} into shell code that generates a valid shell
13759 variable name.  The result is literal when possible at m4 time, but must
13760 be used with @code{eval} if @var{expression} causes shell indirections.
13761 For example:
13763 @example
13764 # This outputs "Have it!".
13765 header="sys/some file.h"
13766 eval AS_TR_SH([HAVE_$header])=yes
13767 if test "x$HAVE_sys_some_file_h" = xyes; then echo "Have it!"; fi
13768 @end example
13769 @end defmac
13771 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
13772 @asindex{SET_CATFILE}
13773 Set the polymorphic shell variable @var{var} to @var{dir}/@var{file},
13774 but optimizing the common cases (@var{dir} or @var{file} is @samp{.},
13775 @var{file} is absolute, etc.).
13776 @end defmac
13778 @defmac AS_UNSET (@var{var})
13779 @asindex{UNSET}
13780 Unsets the shell variable @var{var}, working around bugs in older
13781 shells (@pxref{unset, , Limitations of Shell
13782 Builtins}).  @var{var} can be a literal or indirect variable name.
13783 @end defmac
13785 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
13786   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
13787 @asindex{VERSION_COMPARE}
13788 Compare two strings @var{version-1} and @var{version-2}, possibly
13789 containing shell variables, as version strings, and expand
13790 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
13791 depending upon the result.
13792 The algorithm to compare is similar to the one used by strverscmp in
13793 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
13794 The GNU C Library}).
13795 @end defmac
13797 @node Polymorphic Variables
13798 @section Support for indirect variable names
13799 @cindex variable name indirection
13800 @cindex polymorphic variable name
13801 @cindex indirection, variable name
13803 Often, it is convenient to write a macro that will emit shell code
13804 operating on a shell variable.  The simplest case is when the variable
13805 name is known.  But a more powerful idiom is writing shell code that can
13806 work through an indirection, where another variable or command
13807 substitution produces the name of the variable to actually manipulate.
13808 M4sh supports the notion of polymorphic shell variables, making it easy
13809 to write a macro that can deal with either literal or indirect variable
13810 names and output shell code appropriate for both use cases.  Behavior is
13811 undefined if expansion of an indirect variable does not result in a
13812 literal variable name.
13814 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not}, @
13815   @dvarv{if-simple-ref, if-not})
13816 @defmacx AS_LITERAL_WORD_IF (@var{expression}, @ovar{if-literal}, @
13817   @ovar{if-not}, @dvarv{if-simple-ref, if-not})
13818 @asindex{LITERAL_IF}
13819 @asindex{LITERAL_WORD_IF}
13820 If the expansion of @var{expression} is definitely a shell literal,
13821 expand @var{if-literal}.  If the expansion of @var{expression} looks
13822 like it might contain shell indirections (such as @code{$var} or
13823 @code{`expr`}), then @var{if-not} is expanded.  Sometimes, it is
13824 possible to output optimized code if @var{expression} consists only of
13825 shell variable expansions (such as @code{$@{var@}}), in which case
13826 @var{if-simple-ref} can be provided; but defaulting to @var{if-not}
13827 should always be safe.  @code{AS_LITERAL_WORD_IF} only expands
13828 @var{if-literal} if @var{expression} looks like a single shell word,
13829 containing no whitespace; while @code{AS_LITERAL_IF} allows whitespace
13830 in @var{expression}.
13832 In order to reduce the time spent recognizing whether an
13833 @var{expression} qualifies as a literal or a simple indirection, the
13834 implementation is somewhat conservative: @var{expression} must be a
13835 single shell word (possibly after stripping whitespace), consisting only
13836 of bytes that would have the same meaning whether unquoted or enclosed
13837 in double quotes (for example, @samp{a.b} results in @var{if-literal},
13838 even though it is not a valid shell variable name; while both @samp{'a'}
13839 and @samp{[$]} result in @var{if-not}, because they behave differently
13840 than @samp{"'a'"} and @samp{"[$]"}).  This macro can be used in contexts
13841 for recognizing portable file names (such as in the implementation of
13842 @code{AC_LIBSOURCE}), or coupled with some transliterations for forming
13843 valid variable names (such as in the implementation of @code{AS_TR_SH},
13844 which uses an additional @code{m4_translit} to convert @samp{.} to
13845 @samp{_}).
13847 This example shows how to read the contents of the shell variable
13848 @code{bar}, exercising all three arguments to @code{AS_LITERAL_IF}.  It
13849 results in a script that will output the line @samp{hello} three times.
13851 @example
13852 AC_DEFUN([MY_ACTION],
13853 [AS_LITERAL_IF([$1],
13854   [echo "$$1"],
13855 @c $$
13856   [AS_VAR_COPY([var], [$1])
13857    echo "$var"],
13858   [eval 'echo "$'"$1"\"])])
13859 foo=bar bar=hello
13860 MY_ACTION([bar])
13861 MY_ACTION([`echo bar`])
13862 MY_ACTION([$foo])
13863 @end example
13864 @end defmac
13866 @defmac AS_VAR_APPEND (@var{var}, @var{text})
13867 @asindex{VAR_APPEND}
13868 Emit shell code to append the shell expansion of @var{text} to the end
13869 of the current contents of the polymorphic shell variable @var{var},
13870 taking advantage of shells that provide the @samp{+=} extension for more
13871 efficient scaling.
13873 For situations where the final contents of @var{var} are relatively
13874 short (less than 256 bytes), it is more efficient to use the simpler
13875 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
13876 polymorphic equivalent of @code{AS_VAR_COPY([t], [@var{var}])} and
13877 @code{AS_VAR_SET([@var{var}], ["$t"@var{text}])}).  But in the case
13878 when the script will be repeatedly appending text into @code{var},
13879 issues of scaling start to become apparent.  A naive implementation
13880 requires execution time linear to the length of the current contents of
13881 @var{var} as well as the length of @var{text} for a single append, for
13882 an overall quadratic scaling with multiple appends.  This macro takes
13883 advantage of shells which provide the extension
13884 @code{@var{var}+=@var{text}}, which can provide amortized constant time
13885 for a single append, for an overall linear scaling with multiple
13886 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
13887 @var{text} be quoted properly to avoid field splitting and file name
13888 expansion.
13889 @end defmac
13891 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
13892 @asindex{VAR_ARITH}
13893 Emit shell code to compute the arithmetic expansion of @var{expression},
13894 assigning the result as the contents of the polymorphic shell variable
13895 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
13896 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
13897 syntax for a valid @var{expression} is rather limited: all operators
13898 must occur as separate shell arguments and with proper quoting, there is
13899 no portable equality operator, all variables containing numeric values
13900 must be expanded prior to the computation, all numeric values must be
13901 provided in decimal without leading zeroes, and the first shell argument
13902 should not be a negative number.  In the following example, this snippet
13903 will print @samp{(2+3)*4 == 20}.
13905 @example
13906 bar=3
13907 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
13908 echo "(2+$bar)*4 == $foo"
13909 @end example
13910 @end defmac
13912 @defmac AS_VAR_COPY (@var{dest}, @var{source})
13913 @asindex{VAR_COPY}
13914 Emit shell code to assign the contents of the polymorphic shell variable
13915 @var{source} to the polymorphic shell variable @var{dest}.  For example,
13916 executing this M4sh snippet will output @samp{bar hi}:
13918 @example
13919 foo=bar bar=hi
13920 AS_VAR_COPY([a], [foo])
13921 AS_VAR_COPY([b], [$foo])
13922 echo "$a $b"
13923 @end example
13925 When it is necessary to access the contents of an indirect variable
13926 inside a shell double-quoted context, the recommended idiom is to first
13927 copy the contents into a temporary literal shell variable.
13929 @smallexample
13930 for header in stdint_h inttypes_h ; do
13931   AS_VAR_COPY([var], [ac_cv_header_$header])
13932   echo "$header detected: $var"
13933 done
13934 @end smallexample
13935 @end defmac
13937 @comment AS_VAR_GET is intentionally undocumented; it can't handle
13938 @comment trailing newlines uniformly, and forks too much.
13940 @defmac AS_VAR_IF (@var{var}, @ovar{word}, @ovar{if-equal}, @
13941   @ovar{if-not-equal})
13942 @asindex{VAR_IF}
13943 Output a shell conditional statement.  If the contents of the
13944 polymorphic shell variable @var{var} match the string @var{word},
13945 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  @var{word}
13946 must be a single shell word (typically a quoted string).  Avoids
13947 shell bugs if an interrupt signal arrives while a command substitution
13948 in @var{var} is being expanded.
13949 @end defmac
13951 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
13952 @defmacx AS_VAR_POPDEF (@var{m4-name})
13953 @asindex{VAR_PUSHDEF}
13954 @asindex{VAR_POPDEF}
13955 @cindex composing variable names
13956 @cindex variable names, composing
13957 A common M4sh idiom involves composing shell variable names from an m4
13958 argument (for example, writing a macro that uses a cache variable).
13959 @var{value} can be an arbitrary string, which will be transliterated
13960 into a valid shell name by @code{AS_TR_SH}.  In order to access the
13961 composed variable name based on @var{value}, it is easier to declare a
13962 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
13963 that macro as the argument to subsequent @code{AS_VAR} macros as a
13964 polymorphic variable name, and finally free the temporary macro with
13965 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
13966 to avoid excess newlines in the output.
13968 Here is an involved example, that shows the power of writing macros that
13969 can handle composed shell variable names:
13971 @example
13972 m4_define([MY_CHECK_HEADER],
13973 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
13974 AS_VAR_IF([my_Header], [yes], [echo "header $1 detected"])dnl
13975 AS_VAR_POPDEF([my_Header])dnl
13977 MY_CHECK_HEADER([stdint.h])
13978 for header in inttypes.h stdlib.h ; do
13979   MY_CHECK_HEADER([$header])
13980 done
13981 @end example
13983 @noindent
13984 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
13985 variable names.  In the first invocation, the m4 argument is
13986 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
13987 As a result, the temporary macro @code{my_Header} expands to the literal
13988 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
13989 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
13990 temporary macro @code{my_Header} expands to the indirect shell name
13991 @samp{$as_my_Header}.  During the shell execution of the for loop, when
13992 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
13993 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
13994 platform where all three headers have been previously detected, the
13995 output of the script will include:
13997 @smallexample
13998 header stdint.h detected
13999 header inttypes.h detected
14000 header stdlib.h detected
14001 @end smallexample
14002 @end defmac
14004 @defmac AS_VAR_SET (@var{var}, @ovar{value})
14005 @asindex{VAR_SET}
14006 Emit shell code to assign the contents of the polymorphic shell variable
14007 @var{var} to the shell expansion of @var{value}.  @var{value} is not
14008 subject to field splitting or file name expansion, so if command
14009 substitution is used, it may be done with @samp{`""`} rather than using
14010 an intermediate variable (@pxref{Shell Substitutions}).  However,
14011 @var{value} does undergo rescanning for additional macro names; behavior
14012 is unspecified if late expansion results in any shell meta-characters.
14013 @end defmac
14015 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
14016 @asindex{VAR_SET_IF}
14017 Emit a shell conditional statement, which executes @var{if-set} if the
14018 polymorphic shell variable @code{var} is set to any value, and
14019 @var{if-undef} otherwise.
14020 @end defmac
14022 @defmac AS_VAR_TEST_SET (@var{var})
14023 @asindex{VAR_TEST_SET}
14024 Emit a shell statement that results in a successful exit status only if
14025 the polymorphic shell variable @code{var} is set.
14026 @end defmac
14028 @node Initialization Macros
14029 @section Initialization Macros
14031 @defmac AS_BOURNE_COMPATIBLE
14032 @asindex{BOURNE_COMPATIBLE}
14033 Set up the shell to be more compatible with the Bourne shell as
14034 standardized by Posix, if possible.  This may involve setting
14035 environment variables, or setting options, or similar
14036 implementation-specific actions.  This macro is deprecated, since
14037 @code{AS_INIT} already invokes it.
14038 @end defmac
14040 @defmac AS_INIT
14041 @asindex{INIT}
14042 @evindex LC_ALL
14043 @evindex SHELL
14044 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
14045 outputs the @code{#! /bin/sh} line, a notice about where the output was
14046 generated from, and code to sanitize the environment for the rest of the
14047 script.  Among other initializations, this sets @env{SHELL} to the shell
14048 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
14049 ensure the C locale.  Finally, it changes the current diversion to
14050 @code{BODY}.  @code{AS_INIT} is called automatically by @code{AC_INIT}
14051 and @code{AT_INIT}, so shell code in @file{configure},
14052 @file{config.status}, and @file{testsuite} all benefit from a sanitized
14053 shell environment.
14054 @end defmac
14056 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
14057 @asindex{INIT_GENERATED}
14058 Emit shell code to start the creation of a subsidiary shell script in
14059 @var{file}, including changing @var{file} to be executable.  This macro
14060 populates the child script with information learned from the parent
14061 (thus, the emitted code is equivalent in effect, but more efficient,
14062 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
14063 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
14064 beginning of the child, prior to the shell initialization code, and is
14065 subject to parameter expansion, command substitution, and backslash
14066 quote removal.  The
14067 parent script should check the exit status after this macro, in case
14068 @var{file} could not be properly created (for example, if the disk was
14069 full).  If successfully created, the parent script can then proceed to
14070 append additional M4sh constructs into the child script.
14072 Note that the child script starts life without a log file open, so if
14073 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
14074 must temporarily disable any attempts to use the log file until after
14075 emitting code to open a log within the child.  On the other hand, if the
14076 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
14077 @samp{1}, then the child script already has code that copies stdout to
14078 that descriptor.  Currently, the suggested
14079 idiom for writing a M4sh shell script from within another script is:
14081 @example
14082 AS_INIT_GENERATED([@var{file}], [[# My child script.
14083 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
14084 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
14085 cat >> "@var{file}" <<\__EOF__
14086 # Code to initialize AS_MESSAGE_LOG_FD
14087 m4_popdef([AS_MESSAGE_LOG_FD])dnl
14088 # Additional code
14089 __EOF__
14090 @end example
14092 This, however, may change in the future as the M4sh interface is
14093 stabilized further.
14095 Also, be aware that use of @env{LINENO} within the child script may
14096 report line numbers relative to their location in the parent script,
14097 even when using @code{AS_LINENO_PREPARE}, if the parent script was
14098 unable to locate a shell with working @env{LINENO} support.
14099 @end defmac
14101 @defmac AS_LINENO_PREPARE
14102 @asindex{LINENO_PREPARE}
14103 @evindex LINENO
14104 Find a shell that supports the special variable @env{LINENO}, which
14105 contains the number of the currently executing line.  This macro is
14106 automatically invoked by @code{AC_INIT} in configure scripts.
14107 @end defmac
14109 @defmac AS_ME_PREPARE
14110 @asindex{ME_PREPARE}
14111 Set up variable @env{as_me} to be the basename of the currently executing
14112 script.  This macro is automatically invoked by @code{AC_INIT} in
14113 configure scripts.
14114 @end defmac
14116 @defmac AS_TMPDIR (@var{prefix}, @dvar{dir, $@{TMPDIR:=/tmp@}})
14117 @asindex{TMPDIR}
14118 @evindex TMPDIR
14119 @ovindex tmp
14120 Create, as safely as possible, a temporary sub-directory within
14121 @var{dir} with a name starting with @var{prefix}.  @var{prefix} should
14122 be 2--4 characters, to make it slightly easier to identify the owner of
14123 the directory.  If @var{dir} is omitted, then the value of @env{TMPDIR}
14124 will be used (defaulting to @samp{/tmp}).  On success, the name of the
14125 newly created directory is stored in the shell variable @code{tmp}.  On
14126 error, the script is aborted.
14128 Typically, this macro is coupled with some exit traps to delete the created
14129 directory and its contents on exit or interrupt.  However, there is a
14130 slight window between when the directory is created and when the name is
14131 actually known to the shell, so an interrupt at the right moment might
14132 leave the temporary directory behind.  Hence it is important to use a
14133 @var{prefix} that makes it easier to determine if a leftover temporary
14134 directory from an interrupted script is safe to delete.
14136 The use of the output variable @samp{$tmp} rather than something in the
14137 @samp{as_} namespace is historical; it has the unfortunate consequence
14138 that reusing this otherwise common name for any other purpose inside
14139 your script has the potential to break any cleanup traps designed to
14140 remove the temporary directory.
14141 @end defmac
14143 @defmac AS_SHELL_SANITIZE
14144 @asindex{SHELL_SANITIZE}
14145 Initialize the shell suitably for @command{configure} scripts.  This has
14146 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
14147 environment variables for predictable results from configuration tests.
14148 For example, it sets @env{LC_ALL} to change to the default C locale.
14149 @xref{Special Shell Variables}.  This macro is deprecated, since
14150 @code{AS_INIT} already invokes it.
14151 @end defmac
14154 @node File Descriptor Macros
14155 @section File Descriptor Macros
14156 @cindex input
14157 @cindex standard input
14158 @cindex file descriptors
14159 @cindex descriptors
14160 @cindex low-level output
14161 @cindex output, low-level
14163 The following macros define file descriptors used to output messages
14164 (or input values) from @file{configure} scripts.
14165 For example:
14167 @example
14168 echo "$wombats found" >&AS_MESSAGE_LOG_FD
14169 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
14170 read kangaroos <&AS_ORIGINAL_STDIN_FD`
14171 @end example
14173 @noindent
14174 However doing so is seldom needed, because Autoconf provides higher
14175 level macros as described below.
14177 @defmac AS_MESSAGE_FD
14178 @asindex{MESSAGE_FD}
14179 The file descriptor for @samp{checking for...}  messages and results.
14180 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
14181 clients.  However, @code{AC_INIT} shuffles things around to another file
14182 descriptor, in order to allow the @option{-q} option of
14183 @command{configure} to choose whether messages should go to the script's
14184 standard output or be discarded.
14186 If you want to display some messages, consider using one of the printing
14187 macros (@pxref{Printing Messages}) instead.  Copies of messages output
14188 via these macros are also recorded in @file{config.log}.
14189 @end defmac
14191 @anchor{AS_MESSAGE_LOG_FD}
14192 @defmac AS_MESSAGE_LOG_FD
14193 @asindex{MESSAGE_LOG_FD}
14194 This must either be empty, or expand to a file descriptor for log
14195 messages.  By default, @code{AS_INIT} sets this macro to the empty
14196 string for standalone M4sh clients, thus disabling logging.  However,
14197 @code{AC_INIT} shuffles things around so that both @command{configure}
14198 and @command{config.status} use @file{config.log} for log messages.
14199 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
14200 Compiler}), redirect all output to this descriptor.  You may want to do
14201 so if you develop such a low-level macro.
14202 @end defmac
14204 @defmac AS_ORIGINAL_STDIN_FD
14205 @asindex{ORIGINAL_STDIN_FD}
14206 This must expand to a file descriptor for the original standard input.
14207 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
14208 M4sh clients.  However, @code{AC_INIT} shuffles things around for
14209 safety.
14211 When @command{configure} runs, it may accidentally execute an
14212 interactive command that has the same name as the non-interactive meant
14213 to be used or checked.  If the standard input was the terminal, such
14214 interactive programs would cause @command{configure} to stop, pending
14215 some user input.  Therefore @command{configure} redirects its standard
14216 input from @file{/dev/null} during its initialization.  This is not
14217 normally a problem, since @command{configure} normally does not need
14218 user input.
14220 In the extreme case where your @file{configure} script really needs to
14221 obtain some values from the original standard input, you can read them
14222 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
14223 @end defmac
14226 @c =================================================== Writing Autoconf Macros.
14228 @node Writing Autoconf Macros
14229 @chapter Writing Autoconf Macros
14231 When you write a feature test that could be applicable to more than one
14232 software package, the best thing to do is encapsulate it in a new macro.
14233 Here are some instructions and guidelines for writing Autoconf macros.
14235 @menu
14236 * Macro Definitions::           Basic format of an Autoconf macro
14237 * Macro Names::                 What to call your new macros
14238 * Reporting Messages::          Notifying @command{autoconf} users
14239 * Dependencies Between Macros::  What to do when macros depend on other macros
14240 * Obsoleting Macros::           Warning about old ways of doing things
14241 * Coding Style::                Writing Autoconf macros @`a la Autoconf
14242 @end menu
14244 @node Macro Definitions
14245 @section Macro Definitions
14247 @defmac AC_DEFUN (@var{name}, @ovar{body})
14248 @acindex{DEFUN}
14249 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
14250 similar to the M4 builtin @code{m4_define} macro; this creates a macro
14251 named @var{name} and with @var{body} as its expansion.  In addition to
14252 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
14253 constrain the order in which macros are called, while avoiding redundant
14254 output (@pxref{Prerequisite Macros}).
14255 @end defmac
14257 An Autoconf macro definition looks like this:
14259 @example
14260 AC_DEFUN(@var{macro-name}, @var{macro-body})
14261 @end example
14263 You can refer to any arguments passed to the macro as @samp{$1},
14264 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4,
14265 GNU M4}, for more complete information on writing M4 macros.
14267 Most macros fall in one of two general categories.  The first category
14268 includes macros which take arguments, in order to generate output
14269 parameterized by those arguments.  Macros in this category are designed
14270 to be directly expanded, often multiple times, and should not be used as
14271 the argument to @code{AC_REQUIRE}.  The other category includes macros
14272 which are shorthand for a fixed block of text, and therefore do not take
14273 arguments.  For this category of macros, directly expanding the macro
14274 multiple times results in redundant output, so it is more common to use
14275 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
14276 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
14278 Be sure to properly quote both the @var{macro-body} @emph{and} the
14279 @var{macro-name} to avoid any problems if the macro happens to have
14280 been previously defined.
14282 Each macro should have a header comment that gives its prototype, and a
14283 brief description.  When arguments have default values, display them in
14284 the prototype.  For example:
14286 @example
14287 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
14288 # --------------------------------------
14289 m4_define([AC_MSG_ERROR],
14290   [@{ AS_MESSAGE([error: $1], [2])
14291      exit m4_default([$2], [1]); @}])
14292 @end example
14294 Comments about the macro should be left in the header comment.  Most
14295 other comments make their way into @file{configure}, so just keep
14296 using @samp{#} to introduce comments.
14298 @cindex @code{dnl}
14299 If you have some special comments about pure M4 code, comments
14300 that make no sense in @file{configure} and in the header comment, then
14301 use the builtin @code{dnl}: it causes M4 to discard the text
14302 through the next newline.
14304 Keep in mind that @code{dnl} is rarely needed to introduce comments;
14305 @code{dnl} is more useful to get rid of the newlines following macros
14306 that produce no output, such as @code{AC_REQUIRE}.
14308 Public third-party macros need to use @code{AC_DEFUN}, and not
14309 @code{m4_define}, in order to be found by @command{aclocal}
14310 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14311 Additionally, if it is ever determined that a macro should be made
14312 obsolete, it is easy to convert from @code{AC_DEFUN} to @code{AU_DEFUN}
14313 in order to have @command{autoupdate} assist the user in choosing a
14314 better alternative, but there is no corresponding way to make
14315 @code{m4_define} issue an upgrade notice (@pxref{AU_DEFUN}).
14317 There is another subtle, but important, difference between using
14318 @code{m4_define} and @code{AC_DEFUN}: only the former is unaffected by
14319 @code{AC_REQUIRE}.  When writing a file, it is always safe to replace a
14320 block of text with a @code{m4_define} macro that will expand to the same
14321 text.  But replacing a block of text with an @code{AC_DEFUN} macro with
14322 the same content does not necessarily give the same results, because it
14323 changes the location where any embedded but unsatisfied
14324 @code{AC_REQUIRE} invocations within the block will be expanded.  For an
14325 example of this, see @ref{Expanded Before Required}.
14327 @node Macro Names
14328 @section Macro Names
14330 All of the public Autoconf macros have all-uppercase names in the
14331 namespace @samp{^AC_} to prevent them from accidentally conflicting with
14332 other text; Autoconf also reserves the namespace @samp{^_AC_} for
14333 internal macros.  All shell variables that they use for internal
14334 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
14335 also uses here-document delimiters in the namespace @samp{^_AC[A-Z]}.  During
14336 @command{configure}, files produced by Autoconf make heavy use of the
14337 file system namespace @samp{^conf}.
14339 Since Autoconf is built on top of M4sugar (@pxref{Programming in
14340 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
14341 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
14342 @file{configure.ac} is also designed to be scanned by Autoheader,
14343 Autoscan, Autoupdate, and Automake, you should be aware of the
14344 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
14345 the namespace of a package that does not own the macro or shell code you
14346 are writing.
14348 To ensure that your macros don't conflict with present or future
14349 Autoconf macros, you should prefix your own macro names and any shell
14350 variables they use with some other sequence.  Possibilities include your
14351 initials, or an abbreviation for the name of your organization or
14352 software package.  Historically, people have not always followed the
14353 rule of using a namespace appropriate for their package, and this has
14354 made it difficult for determining the origin of a macro (and where to
14355 report bugs about that macro), as well as difficult for the true
14356 namespace owner to add new macros without interference from pre-existing
14357 uses of third-party macros.  Perhaps the best example of this confusion
14358 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
14359 to Gettext.
14361 Most of the Autoconf macros' names follow a structured naming convention
14362 that indicates the kind of feature check by the name.  The macro names
14363 consist of several words, separated by underscores, going from most
14364 general to most specific.  The names of their cache variables use the
14365 same convention (@pxref{Cache Variable Names}, for more information on
14366 them).
14368 The first word of the name after the namespace initials (such as
14369 @samp{AC_}) usually tells the category
14370 of the feature being tested.  Here are the categories used in Autoconf for
14371 specific test macros, the kind of macro that you are more likely to
14372 write.  They are also used for cache variables, in all-lowercase.  Use
14373 them where applicable; where they're not, invent your own categories.
14375 @table @code
14376 @item C
14377 C language builtin features.
14378 @item DECL
14379 Declarations of C variables in header files.
14380 @item FUNC
14381 Functions in libraries.
14382 @item GROUP
14383 Posix group owners of files.
14384 @item HEADER
14385 Header files.
14386 @item LIB
14387 C libraries.
14388 @item PROG
14389 The base names of programs.
14390 @item MEMBER
14391 Members of aggregates.
14392 @item SYS
14393 Operating system features.
14394 @item TYPE
14395 C builtin or declared types.
14396 @item VAR
14397 C variables in libraries.
14398 @end table
14400 After the category comes the name of the particular feature being
14401 tested.  Any further words in the macro name indicate particular aspects
14402 of the feature.  For example, @code{AC_PROG_MAKE_SET} checks whether
14403 @command{make} sets a variable to its own name.
14405 An internal macro should have a name that starts with an underscore;
14406 Autoconf internals should therefore start with @samp{_AC_}.
14407 Additionally, a macro that is an internal subroutine of another macro
14408 should have a name that starts with an underscore and the name of that
14409 other macro, followed by one or more words saying what the internal
14410 macro does.  For example, @code{AC_PATH_X} has internal macros
14411 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
14413 @node Reporting Messages
14414 @section Reporting Messages
14415 @cindex Messages, from @command{autoconf}
14417 When macros statically diagnose abnormal situations, benign or fatal, it
14418 is possible to make @command{autoconf} detect the problem, and refuse to
14419 create @file{configure} in the case of an error.  The macros in this
14420 section are considered obsolescent, and new code should use M4sugar
14421 macros for this purpose, see @ref{Diagnostic Macros}.
14423 On the other hand, it is possible to want to detect errors when
14424 @command{configure} is run, which are dependent on the environment of
14425 the user rather than the maintainer.  For dynamic diagnostics, see
14426 @ref{Printing Messages}.
14428 @defmac AC_DIAGNOSE (@var{category}, @var{message})
14429 @acindex{DIAGNOSE}
14430 Report @var{message} as a warning (or as an error if requested by the
14431 user) if warnings of the @var{category} are turned on.  This macro is
14432 obsolescent; you are encouraged to use:
14433 @example
14434 m4_warn([@var{category}], [@var{message}])
14435 @end example
14436 @noindent
14437 instead.  @xref{m4_warn}, for more details, including valid
14438 @var{category} names.
14439 @end defmac
14441 @defmac AC_WARNING (@var{message})
14442 @acindex{WARNING}
14443 Report @var{message} as a syntax warning.  This macro is obsolescent;
14444 you are encouraged to use:
14445 @example
14446 m4_warn([syntax], [@var{message}])
14447 @end example
14448 @noindent
14449 instead.  @xref{m4_warn}, for more details, as well as better
14450 finer-grained categories of warnings (not all problems have to do with
14451 syntax).
14452 @end defmac
14454 @defmac AC_FATAL (@var{message})
14455 @acindex{FATAL}
14456 Report a severe error @var{message}, and have @command{autoconf} die.
14457 This macro is obsolescent; you are encouraged to use:
14458 @example
14459 m4_fatal([@var{message}])
14460 @end example
14461 @noindent
14462 instead.  @xref{m4_fatal}, for more details.
14463 @end defmac
14465 When the user runs @samp{autoconf -W error}, warnings from
14466 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
14467 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
14469 @node Dependencies Between Macros
14470 @section Dependencies Between Macros
14471 @cindex Dependencies between macros
14473 Some Autoconf macros depend on other macros having been called first in
14474 order to work correctly.  Autoconf provides a way to ensure that certain
14475 macros are called if needed and a way to warn the user if macros are
14476 called in an order that might cause incorrect operation.
14478 @menu
14479 * Prerequisite Macros::         Ensuring required information
14480 * Suggested Ordering::          Warning about possible ordering problems
14481 * One-Shot Macros::             Ensuring a macro is called only once
14482 @end menu
14484 @node Prerequisite Macros
14485 @subsection Prerequisite Macros
14486 @cindex Prerequisite macros
14487 @cindex Macros, prerequisites
14489 A macro that you write might need to use values that have previously
14490 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
14491 examines the output of @code{flex} or @code{lex}, so it depends on
14492 @code{AC_PROG_LEX} having been called first to set the shell variable
14493 @code{LEX}.
14495 Rather than forcing the user of the macros to keep track of the
14496 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
14497 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
14498 called if it is needed, and only called once.
14500 @defmac AC_REQUIRE (@var{macro-name})
14501 @acindex{REQUIRE}
14502 If the M4 macro @var{macro-name} has not already been called, call it
14503 (without any arguments).  Make sure to quote @var{macro-name} with
14504 square brackets.  @var{macro-name} must have been defined using
14505 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14506 that it has been called.
14508 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
14509 must not be called from the top level.  Also, it does not make sense to
14510 require a macro that takes parameters.
14511 @end defmac
14513 @code{AC_REQUIRE} is often misunderstood.  It really implements
14514 dependencies between macros in the sense that if one macro depends upon
14515 another, the latter is expanded @emph{before} the body of the
14516 former.  To be more precise, the required macro is expanded before
14517 the outermost defined macro in the current expansion stack.
14518 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
14519 @code{FOO}.  For instance, this definition of macros:
14521 @example
14522 @group
14523 AC_DEFUN([TRAVOLTA],
14524 [test "$body_temperature_in_celsius" -gt "38" &&
14525   dance_floor=occupied])
14526 AC_DEFUN([NEWTON_JOHN],
14527 [test "x$hair_style" = xcurly &&
14528   dance_floor=occupied])
14529 @end group
14531 @group
14532 AC_DEFUN([RESERVE_DANCE_FLOOR],
14533 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14534   AC_REQUIRE([TRAVOLTA])
14535   AC_REQUIRE([NEWTON_JOHN])
14536 fi])
14537 @end group
14538 @end example
14540 @noindent
14541 with this @file{configure.ac}
14543 @example
14544 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
14545 RESERVE_DANCE_FLOOR
14546 if test "x$dance_floor" = xoccupied; then
14547   AC_MSG_ERROR([cannot pick up here, let's move])
14549 @end example
14551 @noindent
14552 does not leave you with a better chance to meet a kindred soul at
14553 other times than Saturday night since it expands into:
14555 @example
14556 @group
14557 test "$body_temperature_in_Celsius" -gt "38" &&
14558   dance_floor=occupied
14559 test "x$hair_style" = xcurly &&
14560   dance_floor=occupied
14562 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
14566 @end group
14567 @end example
14569 This behavior was chosen on purpose: (i) it prevents messages in
14570 required macros from interrupting the messages in the requiring macros;
14571 (ii) it avoids bad surprises when shell conditionals are used, as in:
14573 @example
14574 @group
14575 if @dots{}; then
14576   AC_REQUIRE([SOME_CHECK])
14578 @dots{}
14579 SOME_CHECK
14580 @end group
14581 @end example
14583 However, this implementation can lead to another class of problems.
14584 Consider the case where an outer macro first expands, then indirectly
14585 requires, an inner macro:
14587 @example
14588 AC_DEFUN([TESTA], [[echo in A
14589 if test -n "$SEEN_A" ; then echo duplicate ; fi
14590 SEEN_A=:]])
14591 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
14592 if test -z "$SEEN_A" ; then echo bug ; fi]])
14593 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14594 AC_DEFUN([OUTER], [[echo in OUTER]
14595 TESTA
14596 TESTC])
14597 OUTER
14598 @end example
14600 @noindent
14601 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
14602 recognized that @code{TESTB} needed to be hoisted prior to the expansion
14603 of @code{OUTER}, but because @code{TESTA} had already been directly
14604 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
14605 @code{TESTB} occurs prior to its prerequisites, leading to the following
14606 output:
14608 @example
14609 in B
14611 in OUTER
14612 in A
14613 in C
14614 @end example
14616 @noindent
14617 Newer Autoconf is smart enough to recognize this situation, and hoists
14618 @code{TESTA} even though it has already been expanded, but issues a
14619 syntax warning in the process.  This is because the hoisted expansion of
14620 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
14621 redundant code, and causes its own set of problems if the hoisted macro
14622 is not idempotent:
14624 @example
14625 in A
14626 in B
14627 in OUTER
14628 in A
14629 duplicate
14630 in C
14631 @end example
14633 The bug is not in Autoconf, but in the macro definitions.  If you ever
14634 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
14635 that the macro only needs to be expanded once.  But to enforce this,
14636 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
14637 this only helps in Autoconf 2.64 or newer), or all
14638 uses of that macro should be through @code{AC_REQUIRE}; directly
14639 expanding the macro defeats the point of using @code{AC_REQUIRE} to
14640 eliminate redundant expansion.  In the example, this rule of thumb was
14641 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
14642 directly expands it.  One way of fixing the bug is to factor
14643 @code{TESTA} into two macros, the portion designed for direct and
14644 repeated use (here, named @code{TESTA}), and the portion designed for
14645 one-shot output and used only inside @code{AC_REQUIRE} (here, named
14646 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
14647 calling convention according to their needs:
14649 @example
14650 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
14651 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
14652 if test -n "$SEEN_A" ; then echo duplicate ; fi
14653 SEEN_A=:]])
14654 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
14655 if test -z "$SEEN_A" ; then echo bug ; fi]])
14656 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
14657 AC_DEFUN([OUTER], [[echo in OUTER]
14658 TESTA
14659 TESTC])
14660 OUTER
14661 @end example
14663 @noindent
14664 the resulting output will then obey all dependency rules and avoid any
14665 syntax warnings, whether the script is built with old or new Autoconf
14666 versions:
14668 @example
14669 in A_PREREQ
14670 in B
14671 in OUTER
14672 in A
14673 in C
14674 @end example
14676 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
14677 enforce expansion of required macros outside of shell conditional
14678 constructs.  You are furthermore encouraged, although not required, to
14679 put all @code{AC_REQUIRE} calls
14680 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
14681 lines they leave.
14683 Autoconf will normally warn if an @code{AC_REQUIRE} call refers to a
14684 macro that has not been defined.  However, the @command{aclocal} tool
14685 relies on parsing an incomplete set of input files to trace which macros
14686 have been required, in order to then pull in additional files that
14687 provide those macros; for this particular use case, pre-defining the
14688 macro @code{m4_require_silent_probe} will avoid the warnings.
14690 @node Suggested Ordering
14691 @subsection Suggested Ordering
14692 @cindex Macros, ordering
14693 @cindex Ordering macros
14695 Some macros should be run before another macro if both are called, but
14696 neither @emph{requires} that the other be called.  For example, a macro
14697 that changes the behavior of the C compiler should be called before any
14698 macros that run the C compiler.  Many of these dependencies are noted in
14699 the documentation.
14701 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
14702 with this kind of dependency appear out of order in a
14703 @file{configure.ac} file.  The warning occurs when creating
14704 @command{configure} from @file{configure.ac}, not when running
14705 @command{configure}.
14707 For example, @code{AC_PROG_CPP} checks whether the C compiler
14708 can run the C preprocessor when given the @option{-E} option.  It should
14709 therefore be called after any macros that change which C compiler is
14710 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
14712 @example
14713 AC_BEFORE([$0], [AC_PROG_CPP])dnl
14714 @end example
14716 @noindent
14717 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
14718 when @code{AC_PROG_CC} is called.
14720 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
14721 @acindex{BEFORE}
14722 Make M4 print a warning message to the standard error output if
14723 @var{called-macro-name} has already been called.  @var{this-macro-name}
14724 should be the name of the macro that is calling @code{AC_BEFORE}.  The
14725 macro @var{called-macro-name} must have been defined using
14726 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
14727 that it has been called.
14728 @end defmac
14730 @node One-Shot Macros
14731 @subsection One-Shot Macros
14732 @cindex One-shot macros
14733 @cindex Macros, called once
14735 Some macros should be called only once, either because calling them
14736 multiple time is unsafe, or because it is bad style.  For instance
14737 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
14738 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
14739 sense to run these expensive checks more than once.  Such one-shot
14740 macros can be defined using @code{AC_DEFUN_ONCE}.
14742 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
14743 @acindex{DEFUN_ONCE}
14744 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
14745 Definitions}), but add additional logic that guarantees that only the
14746 first use of the macro (whether by direct expansion or
14747 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
14748 expansion will occur before the start of any enclosing macro defined by
14749 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
14750 Generally, it does not make sense for @var{macro-body} to use parameters
14751 such as @code{$1}.
14752 @end defmac
14754 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
14755 emit a warning if it was directly expanded a second time, so for
14756 portability, it is better to use @code{AC_REQUIRE} than direct
14757 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
14758 (@pxref{Prerequisite Macros}).
14760 @node Obsoleting Macros
14761 @section Obsoleting Macros
14762 @cindex Obsoleting macros
14763 @cindex Macros, obsoleting
14765 Configuration and portability technology has evolved over the years.
14766 Often better ways of solving a particular problem are developed, or
14767 ad-hoc approaches are systematized.  This process has occurred in many
14768 parts of Autoconf.  One result is that some of the macros are now
14769 considered @dfn{obsolete}; they still work, but are no longer considered
14770 the best thing to do, hence they should be replaced with more modern
14771 macros.  Ideally, @command{autoupdate} should replace the old macro calls
14772 with their modern implementation.
14774 Autoconf provides a simple means to obsolete a macro.
14776 @anchor{AU_DEFUN}
14777 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
14778 @auindex{DEFUN}
14779 Define @var{old-macro} as @var{implementation}.  The only difference
14780 with @code{AC_DEFUN} is that the user is warned that
14781 @var{old-macro} is now obsolete.
14783 If she then uses @command{autoupdate}, the call to @var{old-macro} is
14784 replaced by the modern @var{implementation}.  @var{message} should
14785 include information on what to do after running @command{autoupdate};
14786 @command{autoupdate} prints it as a warning, and includes it
14787 in the updated @file{configure.ac} file.
14789 The details of this macro are hairy: if @command{autoconf} encounters an
14790 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
14791 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
14792 macros are expanded here, while all other macros are disabled and
14793 appear literally in the updated @file{configure.ac}.
14794 @end defmac
14796 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
14797 @auindex{ALIAS}
14798 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
14799 with the same parameters.  This happens for example if the macro was renamed.
14800 @end defmac
14802 @node Coding Style
14803 @section Coding Style
14804 @cindex Coding style
14806 The Autoconf macros follow a strict coding style.  You are encouraged to
14807 follow this style, especially if you intend to distribute your macro,
14808 either by contributing it to Autoconf itself or the
14809 @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
14810 Archive}, or by other means.
14812 The first requirement is to pay great attention to the quotation.  For
14813 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
14815 Do not try to invent new interfaces.  It is likely that there is a macro
14816 in Autoconf that resembles the macro you are defining: try to stick to
14817 this existing interface (order of arguments, default values, etc.).  We
14818 @emph{are} conscious that some of these interfaces are not perfect;
14819 nevertheless, when harmless, homogeneity should be preferred over
14820 creativity.
14822 Be careful about clashes both between M4 symbols and between shell
14823 variables.
14825 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
14826 you are unlikely to generate conflicts.  Nevertheless, when you need to
14827 set a special value, @emph{avoid using a regular macro name}; rather,
14828 use an ``impossible'' name.  For instance, up to version 2.13, the macro
14829 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
14830 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
14831 But since there is a macro named @code{AC_SUBST_FILE}, it was just
14832 impossible to @samp{AC_SUBST(FILE)}!  In this case,
14833 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
14834 have been used (yes, with the parentheses).
14835 @c or better yet, high-level macros such as @code{m4_expand_once}
14837 No Autoconf macro should ever enter the user-variable name space; i.e.,
14838 except for the variables that are the actual result of running the
14839 macro, all shell variables should start with @code{ac_}.  In
14840 addition, small macros or any macro that is likely to be embedded in
14841 other macros should be careful not to use obvious names.
14843 @cindex @code{dnl}
14844 Do not use @code{dnl} to introduce comments: most of the comments you
14845 are likely to write are either header comments which are not output
14846 anyway, or comments that should make their way into @file{configure}.
14847 There are exceptional cases where you do want to comment special M4
14848 constructs, in which case @code{dnl} is right, but keep in mind that it
14849 is unlikely.
14851 M4 ignores the leading blanks and newlines before each argument.
14852 Use this feature to
14853 indent in such a way that arguments are (more or less) aligned with the
14854 opening parenthesis of the macro being called.  For instance, instead of
14856 @example
14857 AC_CACHE_CHECK(for EMX OS/2 environment,
14858 ac_cv_emxos2,
14859 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
14860 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
14861 @end example
14863 @noindent
14864 write
14866 @example
14867 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
14868 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
14869                    [ac_cv_emxos2=yes],
14870                    [ac_cv_emxos2=no])])
14871 @end example
14873 @noindent
14874 or even
14876 @example
14877 AC_CACHE_CHECK([for EMX OS/2 environment],
14878                [ac_cv_emxos2],
14879                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
14880                                                    [return __EMX__;])],
14881                                   [ac_cv_emxos2=yes],
14882                                   [ac_cv_emxos2=no])])
14883 @end example
14885 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
14886 cross-compiling, provide a pessimistic value (typically @samp{no}).
14888 Feel free to use various tricks to prevent auxiliary tools, such as
14889 syntax-highlighting editors, from behaving improperly.  For instance,
14890 instead of:
14892 @example
14893 m4_bpatsubst([$1], [$"])
14894 @end example
14896 @noindent
14899 @example
14900 m4_bpatsubst([$1], [$""])
14901 @end example
14903 @noindent
14904 so that Emacsen do not open an endless ``string'' at the first quote.
14905 For the same reasons, avoid:
14907 @example
14908 test $[#] != 0
14909 @end example
14911 @noindent
14912 and use:
14914 @example
14915 test $[@@%:@@] != 0
14916 @end example
14918 @noindent
14919 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
14920 breaking the bracket-matching highlighting from Emacsen.  Note the
14921 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
14922 not escape when it is unnecessary.  Common examples of useless quotation
14923 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
14924 etc.  If you add portability issues to the picture, you'll prefer
14925 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
14926 better than hacking Autoconf @code{:-)}.
14928 When using @command{sed}, don't use @option{-e} except for indenting
14929 purposes.  With the @code{s} and @code{y} commands, the preferred
14930 separator is @samp{/} unless @samp{/} itself might appear in the pattern
14931 or replacement, in which case you should use @samp{|}, or optionally
14932 @samp{,} if you know the pattern and replacement cannot contain a file
14933 name.  If none of these characters will do, choose a printable character
14934 that cannot appear in the pattern or replacement.  Characters from the
14935 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
14936 replacement might contain a file name, since they have special meaning
14937 to the shell and are less likely to occur in file names.
14939 @xref{Macro Definitions}, for details on how to define a macro.  If a
14940 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
14941 of an @code{AC_REQUIRE} directive, and macros required by other macros
14942 inside arguments do not need to be expanded before this macro, then
14943 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
14944 Also take into account that public third-party macros need to use
14945 @code{AC_DEFUN} in order to be found by @command{aclocal}
14946 (@pxref{Extending aclocal,,, automake, GNU Automake}).
14947 All the @code{AC_REQUIRE} statements should be at the beginning of the
14948 macro, and each statement should be followed by @code{dnl}.
14950 You should not rely on the number of arguments: instead of checking
14951 whether an argument is missing, test that it is not empty.  It provides
14952 both a simpler and a more predictable interface to the user, and saves
14953 room for further arguments.
14955 Unless the macro is short, try to leave the closing @samp{])} at the
14956 beginning of a line, followed by a comment that repeats the name of the
14957 macro being defined.  This introduces an additional newline in
14958 @command{configure}; normally, that is not a problem, but if you want to
14959 remove it you can use @samp{[]dnl} on the last line.  You can similarly
14960 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
14961 is recommended instead of @samp{dnl} to ensure that M4 does not
14962 interpret the @samp{dnl} as being attached to the preceding text or
14963 macro output.  For example, instead of:
14965 @example
14966 AC_DEFUN([AC_PATH_X],
14967 [AC_MSG_CHECKING([for X])
14968 AC_REQUIRE_CPP()
14969 @r{# @dots{}omitted@dots{}}
14970   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14971 fi])
14972 @end example
14974 @noindent
14975 you would write:
14977 @example
14978 AC_DEFUN([AC_PATH_X],
14979 [AC_REQUIRE_CPP()[]dnl
14980 AC_MSG_CHECKING([for X])
14981 @r{# @dots{}omitted@dots{}}
14982   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
14983 fi[]dnl
14984 ])# AC_PATH_X
14985 @end example
14987 If the macro is long, try to split it into logical chunks.  Typically,
14988 macros that check for a bug in a function and prepare its
14989 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
14990 this setup.  Do not hesitate to introduce auxiliary macros to factor
14991 your code.
14993 In order to highlight the recommended coding style, here is a macro
14994 written the old way:
14996 @example
14997 dnl Check for EMX on OS/2.
14998 dnl _AC_EMXOS2
14999 AC_DEFUN(_AC_EMXOS2,
15000 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
15001 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
15002 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
15003 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes])
15004 @end example
15006 @noindent
15007 and the new way:
15009 @example
15010 # _AC_EMXOS2
15011 # ----------
15012 # Check for EMX on OS/2.
15013 m4_define([_AC_EMXOS2],
15014 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
15015 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
15016                    [ac_cv_emxos2=yes],
15017                    [ac_cv_emxos2=no])])
15018 test "x$ac_cv_emxos2" = xyes && EMXOS2=yes[]dnl
15019 ])# _AC_EMXOS2
15020 @end example
15025 @c ============================================= Portable Shell Programming
15027 @node Portable Shell
15028 @chapter Portable Shell Programming
15029 @cindex Portable shell programming
15031 When writing your own checks, there are some shell-script programming
15032 techniques you should avoid in order to make your code portable.  The
15033 Bourne shell and upward-compatible shells like the Korn shell and Bash
15034 have evolved over the years, and many features added to the original
15035 System7 shell are now supported on all interesting porting targets.
15036 However, the following discussion between Russ Allbery and Robert Lipe
15037 is worth reading:
15039 @noindent
15040 Russ Allbery:
15042 @quotation
15043 The GNU assumption that @command{/bin/sh} is the one and only shell
15044 leads to a permanent deadlock.  Vendors don't want to break users'
15045 existing shell scripts, and there are some corner cases in the Bourne
15046 shell that are not completely compatible with a Posix shell.  Thus,
15047 vendors who have taken this route will @emph{never} (OK@dots{}``never say
15048 never'') replace the Bourne shell (as @command{/bin/sh}) with a
15049 Posix shell.
15050 @end quotation
15052 @noindent
15053 Robert Lipe:
15055 @quotation
15056 This is exactly the problem.  While most (at least most System V's) do
15057 have a Bourne shell that accepts shell functions most vendor
15058 @command{/bin/sh} programs are not the Posix shell.
15060 So while most modern systems do have a shell @emph{somewhere} that meets the
15061 Posix standard, the challenge is to find it.
15062 @end quotation
15064 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
15065 is to find such a shell.  But to prevent trouble, if you're not using
15066 M4sh you should not take advantage of features that were added after Unix
15067 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
15068 negated character classes, or even @command{unset}.  @code{#} comments,
15069 while not in Unix version 7, were retrofitted in the original Bourne
15070 shell and can be assumed to be part of the least common denominator.
15072 On the other hand, if you're using M4sh you can assume that the shell
15073 has the features that were added in SVR2 (circa 1984), including shell
15074 functions,
15075 @command{return}, @command{unset}, and I/O redirection for builtins.  For
15076 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
15077 However, some pitfalls have to be avoided for portable use of these
15078 constructs; these will be documented in the rest of this chapter.
15079 See in particular @ref{Shell Functions} and @ref{Limitations of
15080 Builtins, , Limitations of Shell Builtins}.
15082 Some ancient systems have quite
15083 small limits on the length of the @samp{#!} line; for instance, 32
15084 bytes (not including the newline) on SunOS 4.
15085 However, these ancient systems are no longer of practical concern.
15087 The set of external programs you should run in a @command{configure} script
15088 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
15089 Makefiles, standards, The GNU Coding Standards}, for the list.  This
15090 restriction allows users to start out with a fairly small set of
15091 programs and build the rest, avoiding too many interdependencies between
15092 packages.
15094 Some of these external utilities have a portable subset of features; see
15095 @ref{Limitations of Usual Tools}.
15097 There are other sources of documentation about shells.  The
15098 specification for the Posix
15099 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
15100 Command Language}, though more generous than the restrictive shell
15101 subset described above, is fairly portable nowadays.  Also please see
15102 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
15104 @menu
15105 * Shellology::                  A zoology of shells
15106 * Invoking the Shell::          Invoking the shell as a command
15107 * Here-Documents::              Quirks and tricks
15108 * File Descriptors::            FDs and redirections
15109 * Signal Handling::             Shells, signals, and headaches
15110 * File System Conventions::     File names
15111 * Shell Pattern Matching::      Pattern matching
15112 * Shell Substitutions::         Variable and command expansions
15113 * Assignments::                 Varying side effects of assignments
15114 * Parentheses::                 Parentheses in shell scripts
15115 * Slashes::                     Slashes in shell scripts
15116 * Special Shell Variables::     Variables you should not change
15117 * Shell Functions::             What to look out for if you use them
15118 * Limitations of Builtins::     Portable use of not so portable /bin/sh
15119 * Limitations of Usual Tools::  Portable use of portable tools
15120 @end menu
15122 @node Shellology
15123 @section Shellology
15124 @cindex Shellology
15126 There are several families of shells, most prominently the Bourne family
15127 and the C shell family which are deeply incompatible.  If you want to
15128 write portable shell scripts, avoid members of the C shell family.  The
15129 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
15130 Shell difference FAQ} includes a small history of Posix shells, and a
15131 comparison between several of them.
15133 Below we describe some of the members of the Bourne shell family.
15135 @table @asis
15136 @item Ash
15137 @cindex Ash
15138 Ash is often used on GNU/Linux and BSD
15139 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
15140 bugs that are fixed in the 0.3.x series, but portable shell scripts
15141 should work around them, since version 0.2 is still shipped with many
15142 GNU/Linux distributions.
15144 To be compatible with Ash 0.2:
15146 @itemize @minus
15147 @item
15148 don't use @samp{$?} after expanding empty or unset variables,
15149 or at the start of an @command{eval}:
15151 @example
15152 foo=
15153 false
15154 $foo
15155 echo "Do not use it: $?"
15156 false
15157 eval 'echo "Do not use it: $?"'
15158 @end example
15160 @item
15161 don't use command substitution within variable expansion:
15163 @example
15164 cat $@{FOO=`bar`@}
15165 @end example
15167 @item
15168 beware that single builtin substitutions are not performed by a
15169 subshell, hence their effect applies to the current shell!  @xref{Shell
15170 Substitutions}, item ``Command Substitution''.
15171 @end itemize
15173 @item Bash
15174 @cindex Bash
15175 To detect whether you are running Bash, test whether
15176 @code{BASH_VERSION} is set.  To require
15177 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
15178 Mode, , Bash Posix Mode, bash, The GNU Bash Reference
15179 Manual}, for details.
15181 @item Bash 2.05 and later
15182 @cindex Bash 2.05 and later
15183 Versions 2.05 and later of Bash use a different format for the
15184 output of the @command{set} builtin, designed to make evaluating its
15185 output easier.  However, this output is not compatible with earlier
15186 versions of Bash (or with many other shells, probably).  So if
15187 you use Bash 2.05 or higher to execute @command{configure},
15188 you'll need to use Bash 2.05 for all other build tasks as well.
15190 @item Ksh
15191 @cindex Ksh
15192 @cindex Korn shell
15193 @prindex @samp{ksh}
15194 @prindex @samp{ksh88}
15195 @prindex @samp{ksh93}
15196 The Korn shell is compatible with the Bourne family and it mostly
15197 conforms to Posix.  It has two major variants commonly
15198 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
15199 release.  It is usually called @command{ksh}, but is called @command{sh}
15200 on some hosts if you set your path appropriately.
15202 Solaris systems have three variants:
15203 @prindex @command{/usr/bin/ksh} on Solaris
15204 @command{/usr/bin/ksh} is @samp{ksh88}; it is
15205 standard on Solaris 2.0 and later.
15206 @prindex @command{/usr/xpg4/bin/sh} on Solaris
15207 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
15208 @samp{ksh88}; it is standard on Solaris 9 and later.
15209 @prindex @command{/usr/dt/bin/dtksh} on Solaris
15210 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
15211 Variants that are not standard may be parts of optional
15212 packages.  There is no extra charge for these packages, but they are
15213 not part of a minimal OS install and therefore some installations may
15214 not have it.
15216 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
15217 is also available as @command{/usr/bin/posix/sh}.  If the environment
15218 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
15219 the standard shell conform to Posix.
15221 @item Pdksh
15222 @prindex @samp{pdksh}
15223 A public-domain clone of the Korn shell called @command{pdksh} is widely
15224 available: it has most of the @samp{ksh88} features along with a few of
15225 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
15226 @command{/bin/sh} on OpenBSD, and similarly to Bash you can require
15227 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
15228 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
15229 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
15230 at least one respect, see @ref{Shell Substitutions}.
15232 @item Zsh
15233 @cindex Zsh
15234 To detect whether you are running @command{zsh}, test whether
15235 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
15236 compatible with the Bourne shell: you must execute @samp{emulate sh},
15237 and for @command{zsh} versions before 3.1.6-dev-18 you must also
15238 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
15239 zsh, The Z Shell Manual}, for details.
15241 The default Mac OS X @command{sh} was originally Zsh; it was changed to
15242 Bash in Mac OS X 10.2.
15243 @end table
15245 @node Invoking the Shell
15246 @section Invoking the Shell
15247 @cindex invoking the shell
15248 @cindex shell invocation
15250 The Korn shell (up to at least version M-12/28/93d) has a bug when
15251 invoked on a file whose name does not contain a slash.  It first
15252 searches for the file's name in @env{PATH}, and if found it executes
15253 that rather than the original file.  For example, assuming there is a
15254 binary executable @file{/usr/bin/script} in your @env{PATH}, the last
15255 command in the following example fails because the Korn shell finds
15256 @file{/usr/bin/script} and refuses to execute it as a shell script:
15258 @example
15259 $ @kbd{touch xxyzzyz script}
15260 $ @kbd{ksh xxyzzyz}
15261 $ @kbd{ksh ./script}
15262 $ @kbd{ksh script}
15263 ksh: script: cannot execute
15264 @end example
15266 Bash 2.03 has a bug when invoked with the @option{-c} option: if the
15267 option-argument ends in backslash-newline, Bash incorrectly reports a
15268 syntax error.  The problem does not occur if a character follows the
15269 backslash:
15271 @example
15272 $ @kbd{$ bash -c 'echo foo \}
15273 > @kbd{'}
15274 bash: -c: line 2: syntax error: unexpected end of file
15275 $ @kbd{bash -c 'echo foo \}
15276 > @kbd{ '}
15278 @end example
15280 @noindent
15281 @xref{Backslash-Newline-Empty}, for how this can cause problems in makefiles.
15283 @node Here-Documents
15284 @section Here-Documents
15285 @cindex Here-documents
15286 @cindex Shell here-documents
15288 Don't rely on @samp{\} being preserved just because it has no special
15289 meaning together with the next symbol.  In the native @command{sh}
15290 on OpenBSD 2.7 @samp{\"} expands to @samp{"} in here-documents with
15291 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
15292 use @samp{\\} to get @samp{\}.
15294 With OpenBSD 2.7's @command{sh}
15296 @example
15297 @group
15298 $ @kbd{cat <<EOF
15299 > \" \\
15300 > EOF}
15301 " \
15302 @end group
15303 @end example
15305 @noindent
15306 and with Bash:
15308 @example
15309 @group
15310 bash-2.04$ @kbd{cat <<EOF
15311 > \" \\
15312 > EOF}
15313 \" \
15314 @end group
15315 @end example
15317 Using command substitutions in a here-document that is fed to a shell
15318 function is not portable.  For example, with Solaris 10 @command{/bin/sh}:
15320 @example
15321 $ @kbd{kitty () @{ cat; @}}
15322 $ @kbd{kitty <<EOF
15323 > `echo ok`
15324 > EOF}
15325 /tmp/sh199886: cannot open
15326 $ @kbd{echo $?}
15328 @end example
15330 Some shells mishandle large here-documents: for example,
15331 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
15332 derived from Korn shell version M-12/28/93d, mishandle braced variable
15333 expansion that crosses a 1024- or 4096-byte buffer boundary
15334 within a here-document.  Only the part of the variable name after the boundary
15335 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
15336 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
15337 boundary, the shell reports an error, as if you used @code{$@{@}}.
15338 Instead of @code{$@{variable-default@}}, the shell may expand
15339 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
15340 be worked around by omitting the braces: @code{$variable}.  The bug was
15341 fixed in
15342 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
15343 still shipping older versions with the bug.
15345 Empty here-documents are not portable either; with the following code,
15346 @command{zsh} up to at least version 4.3.10 creates a file with a single
15347 newline, whereas other shells create an empty file:
15349 @example
15350 cat >file <<EOF
15352 @end example
15354 Many shells (including the Bourne shell) implement here-documents
15355 inefficiently.  In particular, some shells can be extremely inefficient when
15356 a single statement contains many here-documents.  For instance if your
15357 @file{configure.ac} includes something like:
15359 @example
15360 @group
15361 if <cross_compiling>; then
15362   assume this and that
15363 else
15364   check this
15365   check that
15366   check something else
15367   @dots{}
15368   on and on forever
15369   @dots{}
15371 @end group
15372 @end example
15374 A shell parses the whole @code{if}/@code{fi} construct, creating
15375 temporary files for each here-document in it.  Some shells create links
15376 for such here-documents on every @code{fork}, so that the clean-up code
15377 they had installed correctly removes them.  It is creating the links
15378 that can take the shell forever.
15380 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
15381 @code{if}/@code{fi} constructs, would improve the performance
15382 significantly.  Anyway, this kind of construct is not exactly the
15383 typical use of Autoconf.  In fact, it's even not recommended, because M4
15384 macros can't look into shell conditionals, so we may fail to expand a
15385 macro when it was expanded before in a conditional path, and the
15386 condition turned out to be false at runtime, and we end up not
15387 executing the macro at all.
15389 Be careful with the use of @samp{<<-} to unindent here-documents.  The
15390 behavior is only portable for stripping leading @key{TAB}s, and things
15391 can silently break if an overzealous editor converts to using leading
15392 spaces (not all shells are nice enough to warn about unterminated
15393 here-documents).
15395 @example
15396 $ @kbd{printf 'cat <<-x\n\t1\n\t 2\n\tx\n' | bash && echo done}
15399 done
15400 $ @kbd{printf 'cat <<-x\n 1\n  2\n x\n' | bash-3.2 && echo done}
15402   2
15404 done
15405 @end example
15407 @node File Descriptors
15408 @section File Descriptors
15409 @cindex Descriptors
15410 @cindex File descriptors
15411 @cindex Shell file descriptors
15413 Most shells, if not all (including Bash, Zsh, Ash), output traces on
15414 stderr, even for subshells.  This might result in undesirable content
15415 if you meant to capture the standard-error output of the inner command:
15417 @example
15418 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
15419 $ @kbd{cat stderr}
15420 + eval echo foo >&2
15421 + echo foo
15423 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
15424 $ @kbd{cat stderr}
15425 + eval 'echo foo >&2'
15426 ++ echo foo
15428 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
15429 @i{# Traces on startup files deleted here.}
15430 $ @kbd{cat stderr}
15431 +zsh:1> eval echo foo >&2
15432 +zsh:1> echo foo
15434 @end example
15436 @noindent
15437 One workaround is to grep out uninteresting lines, hoping not to remove
15438 good ones.
15440 If you intend to redirect both standard error and standard output,
15441 redirect standard output first.  This works better with HP-UX,
15442 since its shell mishandles tracing if standard error is redirected
15443 first:
15445 @example
15446 $ @kbd{sh -x -c ': 2>err >out'}
15447 + :
15448 + 2> err $ @kbd{cat err}
15449 1> out
15450 @end example
15452 Don't try to redirect the standard error of a command substitution.  It
15453 must be done @emph{inside} the command substitution.  When running
15454 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
15455 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
15457 On the other hand, some shells, such as Solaris or FreeBSD
15458 @command{/bin/sh}, warn about missing programs before performing
15459 redirections.  Therefore, to silently check whether a program exists, it
15460 is necessary to perform redirections on a subshell or brace group:
15461 @example
15462 $ @kbd{/bin/sh -c 'nosuch 2>/dev/null'}
15463 nosuch: not found
15464 $ @kbd{/bin/sh -c '(nosuch) 2>/dev/null'}
15465 $ @kbd{/bin/sh -c '@{ nosuch; @} 2>/dev/null'}
15466 $ @kbd{bash -c 'nosuch 2>/dev/null'}
15467 @end example
15469 FreeBSD 6.2 sh may mix the trace output lines from the statements in a
15470 shell pipeline.
15472 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
15473 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
15475 Some shells, like @command{ash}, don't recognize bi-directional
15476 redirection (@samp{<>}).  And even on shells that recognize it, it is
15477 not portable to use on fifos: Posix does not require read-write support
15478 for named pipes, and Cygwin does not support it:
15480 @example
15481 $ @kbd{mkfifo fifo}
15482 $ @kbd{exec 5<>fifo}
15483 $ @kbd{echo hi >&5}
15484 bash: echo: write error: Communication error on send
15485 @end example
15487 @noindent
15488 Furthermore, versions of @command{dash} before 0.5.6 mistakenly truncate
15489 regular files when using @samp{<>}:
15491 @example
15492 $ @kbd{echo a > file}
15493 $ @kbd{bash -c ': 1<>file'; cat file}
15495 $ @kbd{dash -c ': 1<>file'; cat file}
15496 $ rm a
15497 @end example
15499 When catering to old systems, don't redirect the same file descriptor
15500 several times, as you are doomed to failure under Ultrix.
15502 @example
15503 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
15504 UWS V4.4 (Rev. 11)
15505 $ @kbd{eval 'echo matter >fullness' >void}
15506 illegal io
15507 $ @kbd{eval '(echo matter >fullness)' >void}
15508 illegal io
15509 $ @kbd{(eval '(echo matter >fullness)') >void}
15510 Ambiguous output redirect.
15511 @end example
15513 @noindent
15514 In each case the expected result is of course @file{fullness} containing
15515 @samp{matter} and @file{void} being empty.  However, this bug is
15516 probably not of practical concern to modern platforms.
15518 Solaris 10 @command{sh} will try to optimize away a @command{:} command
15519 (even if it is redirected) in a loop after the first iteration, or in a
15520 shell function after the first call:
15522 @example
15523 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
15524 $ @kbd{ls x*}
15526 $ @kbd{f () @{ : >$1; @}; f y1; f y2; f y3;}
15527 $ @kbd{ls y*}
15529 @end example
15531 @noindent
15532 As a workaround, @command{echo} or @command{eval} can be used.
15534 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
15535 subsidiary program.  If any of these descriptors is closed, the
15536 operating system may open an unspecified file for the descriptor in the
15537 new process image.  Posix 2008 says this may be done only if the
15538 subsidiary program is set-user-ID or set-group-ID, but HP-UX 11.23 does
15539 it even for ordinary programs, and the next version of Posix will allow
15540 HP-UX behavior.
15542 If you want a file descriptor above 2 to be inherited into a child
15543 process, then you must use redirections specific to that command or a
15544 containing subshell or command group, rather than relying on
15545 @command{exec} in the shell. In @command{ksh} as well as HP-UX
15546 @command{sh}, file descriptors above 2 which are opened using
15547 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
15548 that involved in the fork-and-exec which runs a program or script):
15550 @example
15551 $ @kbd{echo 'echo hello >&5' >k}
15552 $ @kbd{/bin/sh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15553 hello
15554 $ @kbd{bash -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15555 hello
15556 $ @kbd{ksh -c 'exec 5>t; ksh ./k; exec 5>&-; cat t}
15557 ./k[1]: 5: cannot open [Bad file number]
15558 $ @kbd{ksh -c '(ksh ./k) 5>t; cat t'}
15559 hello
15560 $ @kbd{ksh -c '@{ ksh ./k; @} 5>t; cat t'}
15561 hello
15562 $ @kbd{ksh -c '5>t ksh ./k; cat t}
15563 hello
15564 @end example
15566 Don't rely on duplicating a closed file descriptor to cause an
15567 error.  With Solaris @command{/bin/sh}, failed duplication is silently
15568 ignored, which can cause unintended leaks to the original file
15569 descriptor.  In this example, observe the leak to standard output:
15571 @example
15572 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
15573 bash: 3: Bad file descriptor
15575 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
15578 @end example
15580 Fortunately, an attempt to close an already closed file descriptor will
15581 portably succeed.  Likewise, it is safe to use either style of
15582 @samp{@var{n}<&-} or @samp{@var{n}>&-} for closing a file descriptor,
15583 even if it doesn't match the read/write mode that the file descriptor
15584 was opened with.
15586 DOS variants cannot rename or remove open files, such as in
15587 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
15588 perfectly portable among Posix hosts.
15590 A few ancient systems reserved some file descriptors.  By convention,
15591 file descriptor 3 was opened to @file{/dev/tty} when you logged into
15592 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
15593 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
15594 1990), though we don't now remember what it was.  Both these systems are
15595 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
15596 other file descriptors.
15598 On the other hand, you can't portably use multi-digit file descriptors.
15599 Solaris @command{ksh} doesn't understand any file descriptor larger than
15600 @samp{9}:
15602 @example
15603 $ @kbd{bash -c 'exec 10>&-'; echo $?}
15605 $ @kbd{ksh -c 'exec 9>&-'; echo $?}
15607 $ @kbd{ksh -c 'exec 10>&-'; echo $?}
15608 ksh[1]: exec: 10: not found
15610 @end example
15612 @c <http://lists.gnu.org/archive/html/bug-autoconf/2011-09/msg00004.html>
15613 @node Signal Handling
15614 @section Signal Handling
15615 @cindex Signal handling in the shell
15616 @cindex Signals, shells and
15618 Portable handling of signals within the shell is another major source of
15619 headaches.  This is worsened by the fact that various different, mutually
15620 incompatible approaches are possible in this area, each with its
15621 distinctive merits and demerits.  A detailed description of these possible
15622 approaches, as well as of their pros and cons, can be found in
15623 @uref{http://www.cons.org/cracauer/sigint.html, this article}.
15625 Solaris 10 @command{/bin/sh} automatically traps most signals by default;
15626 @c See: <http://dbaspot.com/shell/396118-bourne-shell-exit-code-term.html>
15627 the shell still exits with error upon termination by one of those signals,
15628 but in such a case the exit status might be somewhat unexpected (even if
15629 allowed by POSIX, strictly speaking):
15631 @example
15632 $ @kbd{bash -c 'kill -1 $$'; echo $?} # Will exit 128 + (signal number).
15633 Hangup
15635 $ @kbd{/bin/ksh -c 'kill -15 $$'; echo $?} # Likewise.
15636 Terminated
15638 $ @kbd{for sig in 1 2 3 15; do}
15639 > @kbd{  echo $sig:}
15640 > @kbd{  /bin/sh -c "kill -$s \$\$"; echo $?}
15641 > @kbd{done}
15642 signal 1:
15643 Hangup
15645 signal 2:
15647 signal 3:
15649 signal 15:
15651 @end example
15653 This gets even worse if one is using the POSIX ``wait'' interface to get
15654 details about the shell process terminations: it will result in the shell
15655 having exited normally, rather than by receiving a signal.
15657 @example
15658 $ @kbd{cat > foo.c <<'END'}
15659 #include <stdio.h>    /* for printf */
15660 #include <stdlib.h>   /* for system */
15661 #include <sys/wait.h> /* for WIF* macros */
15662 int main(void)
15664   int status = system ("kill -15 $$");
15665   printf ("Terminated by signal: %s\n",
15666           WIFSIGNALED (status) ? "yes" : "no");
15667   printf ("Exited normally: %s\n",
15668           WIFEXITED (status) ? "yes" : "no");
15669   return 0;
15672 @c $$ font-lock
15673 $ @kbd{cc -o foo foo.c}
15674 $ @kbd{./a.out} # On GNU/Linux
15675 Terminated by signal: no
15676 Exited normally: yes
15677 $ @kbd{./a.out} # On Solaris 10
15678 Terminated by signal: yes
15679 Exited normally: no
15680 @end example
15682 Various shells seem to handle @code{SIGQUIT} specially: they ignore it even
15683 if it is not blocked, and even if the shell is not running interactively
15684 (in fact, even if the shell has no attached tty); among these shells
15685 are at least Bash (from version 2 onwards), Zsh 4.3.12, Solaris 10
15686 @code{/bin/ksh} and @code{/usr/xpg4/bin/sh}, and AT&T @code{ksh93} (2011).
15687 Still, @code{SIGQUIT} seems to be trappable quite portably within all
15688 these shells.  OTOH, some other shells doesn't special-case the handling
15689 of @code{SIGQUIT}; among these shells are at least @code{pdksh} 5.2.14,
15690 Solaris 10 and NetBSD 5.1 @code{/bin/sh}, and the Almquist Shell 0.5.5.1.
15692 @c See: <http://mail.opensolaris.org/pipermail/ksh93-integration-discuss/2009-February/004121.html>
15693 Some shells (especially Korn shells and derivatives) might try to
15694 propagate to themselves a signal that has killed a child process; this is
15695 not a bug, but a conscious design choice (although its overall value might
15696 be debatable).  The exact details of how this is attained vary from shell
15697 to shell.  For example, upon running @code{perl -e 'kill 2, $$'}, after
15698 the perl process has been interrupted AT&T @code{ksh93} (2011) will
15699 proceed to send itself a @code{SIGINT}, while Solaris 10 @code{/bin/ksh}
15700 and @code{/usr/xpg4/bin/sh} will proceed to exit with status 130 (i.e.,
15701 128 + 2). In any case, if there is an active trap associated with
15702 @code{SIGINT}, those shells will correctly execute it.
15704 @c See: <http://www.austingroupbugs.net/view.php?id=51>
15705 Some Korn shells, when a child process die due receiving a signal with
15706 signal number @var{n}, can leave in @samp{$?} an exit status of
15707 256+@var{n} instead of the more common 128+@var{n}.  Observe the
15708 difference between AT&T @code{ksh93} (2011) and @code{bash} 4.1.5 on
15709 Debian:
15711 @example
15712 $ @kbd{/bin/ksh -c 'sh -c "kill -1 \$\$"; echo $?'}
15713 /bin/ksh: line 1: 7837: Hangup
15715 $ @kbd{/bin/bash -c 'sh -c "kill -1 \$\$"; echo $?'}
15716 /bin/bash: line 1:  7861 Hangup        (sh -c "kill -1 \$\$")
15718 @end example
15720 @noindent
15721 This @command{ksh} behavior is allowed by POSIX, if implemented with
15722 due care; see this @uref{http://www.austingroupbugs.net/view.php?id=51,
15723 Austin Group discussion} for more background.  However, if it is not
15724 implemented with proper care, such a behavior might cause problems
15725 in some corner cases.  To see why, assume we have a ``wrapper'' script
15726 like this:
15728 @example
15729 #!/bin/sh
15730 # Ignore some signals in the shell only, not in its child processes.
15731 trap : 1 2 13 15
15732 wrapped_command "$@@"
15733 ret=$?
15734 other_command
15735 exit $ret
15736 @end example
15738 @noindent
15739 If @command{wrapped_command} is interrupted by a @code{SIGHUP} (which
15740 has signal number 1), @code{ret} will be set to 257.  Unless the
15741 @command{exit} shell builtin is smart enough to understand that such
15742 a value can only have originated from a signal, and adjust the final
15743 wait status of the shell appropriately, the value 257 will just get
15744 truncated to 1 by the closing @code{exit} call, so that a caller of
15745 the script will have no way to determine that termination by a signal
15746 was involved.  Observe the different behavior of AT&T @code{ksh93}
15747 (2011) and @code{bash} 4.1.5 on Debian:
15749 @example
15750 $ @kbd{cat foo.sh}
15751 #!/bin/sh
15752 sh -c 'kill -1 $$'
15753 ret=$?
15754 echo $ret
15755 exit $ret
15756 $ @kbd{/bin/ksh foo.sh; echo $?}
15757 foo.sh: line 2: 12479: Hangup
15760 $ @kbd{/bin/bash foo.sh; echo $?}
15761 foo.sh: line 2: 12487 Hangup        (sh -c 'kill -1 $$')
15764 @end example
15766 @node File System Conventions
15767 @section File System Conventions
15768 @cindex File system conventions
15770 Autoconf uses shell-script processing extensively, so the file names
15771 that it processes should not contain characters that are special to the
15772 shell.  Special characters include space, tab, newline, NUL, and
15773 the following:
15775 @example
15776 " # $ & ' ( ) * ; < = > ? [ \ ` |
15777 @end example
15779 Also, file names should not begin with @samp{~} or @samp{-}, and should
15780 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
15781 immediately after @samp{:}.  On Posix-like platforms, directory names
15782 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
15783 path separator.
15785 These restrictions apply not only to the files that you distribute, but
15786 also to the absolute file names of your source, build, and destination
15787 directories.
15789 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
15790 they should be avoided.
15792 Posix lets implementations treat leading @file{//} specially, but
15793 requires leading @file{///} and beyond to be equivalent to @file{/}.
15794 Most Unix variants treat @file{//} like @file{/}.  However, some treat
15795 @file{//} as a ``super-root'' that can provide access to files that are
15796 not otherwise reachable from @file{/}.  The super-root tradition began
15797 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
15798 has revived it.
15800 While @command{autoconf} and friends are usually run on some Posix
15801 variety, they can be used on other systems, most notably DOS
15802 variants.  This impacts several assumptions regarding file names.
15804 @noindent
15805 For example, the following code:
15807 @example
15808 case $foo_dir in
15809   /*) # Absolute
15810      ;;
15811   *)
15812      foo_dir=$dots$foo_dir ;;
15813 esac
15814 @end example
15816 @noindent
15817 fails to properly detect absolute file names on those systems, because
15818 they can use a drivespec, and usually use a backslash as directory
15819 separator.  If you want to be portable to DOS variants (at the
15820 price of rejecting valid but oddball Posix file names like @file{a:\b}),
15821 you can check for absolute file names like this:
15823 @cindex absolute file names, detect
15824 @example
15825 case $foo_dir in
15826   [\\/]* | ?:[\\/]* ) # Absolute
15827      ;;
15828   *)
15829      foo_dir=$dots$foo_dir ;;
15830 esac
15831 @end example
15833 @noindent
15834 Make sure you quote the brackets if appropriate and keep the backslash as
15835 first character (@pxref{case, , Limitations of Shell Builtins}).
15837 Also, because the colon is used as part of a drivespec, these systems don't
15838 use it as path separator.  When creating or accessing paths, you can use the
15839 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
15840 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
15841 starts up.
15843 File names need extra care as well.  While DOS variants
15844 that are Posixy enough to run @command{autoconf} (such as DJGPP)
15845 are usually able to handle long file names properly, there are still
15846 limitations that can seriously break packages.  Several of these issues
15847 can be easily detected by the
15848 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
15849 package.
15851 A short overview follows; problems are marked with SFN/LFN to
15852 indicate where they apply: SFN means the issues are only relevant to
15853 plain DOS, not to DOS under Microsoft Windows
15854 variants, while LFN identifies problems that exist even under
15855 Microsoft Windows variants.
15857 @table @asis
15858 @item No multiple dots (SFN)
15859 DOS cannot handle multiple dots in file names.  This is an especially
15860 important thing to remember when building a portable configure script,
15861 as @command{autoconf} uses a .in suffix for template files.
15863 This is perfectly OK on Posix variants:
15865 @example
15866 AC_CONFIG_HEADERS([config.h])
15867 AC_CONFIG_FILES([source.c foo.bar])
15868 AC_OUTPUT
15869 @end example
15871 @noindent
15872 but it causes problems on DOS, as it requires @samp{config.h.in},
15873 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
15874 to DOS-based environments, you should use this instead:
15876 @example
15877 AC_CONFIG_HEADERS([config.h:config.hin])
15878 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
15879 AC_OUTPUT
15880 @end example
15882 @item No leading dot (SFN)
15883 DOS cannot handle file names that start with a dot.  This is usually
15884 not important for @command{autoconf}.
15886 @item Case insensitivity (LFN)
15887 DOS is case insensitive, so you cannot, for example, have both a
15888 file called @samp{INSTALL} and a directory called @samp{install}.  This
15889 also affects @command{make}; if there's a file called @samp{INSTALL} in
15890 the directory, @samp{make install} does nothing (unless the
15891 @samp{install} target is marked as PHONY).
15893 @item The 8+3 limit (SFN)
15894 Because the DOS file system only stores the first 8 characters of
15895 the file name and the first 3 of the extension, those must be unique.
15896 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
15897 @file{foobar-prettybird.c} all resolve to the same file name
15898 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
15899 @file{foo.bartender}.
15901 The 8+3 limit is not usually a problem under Microsoft Windows, as it
15902 uses numeric
15903 tails in the short version of file names to make them unique.  However, a
15904 registry setting can turn this behavior off.  While this makes it
15905 possible to share file trees containing long file names between SFN
15906 and LFN environments, it also means the above problem applies there
15907 as well.
15909 @item Invalid characters (LFN)
15910 Some characters are invalid in DOS file names, and should therefore
15911 be avoided.  In a LFN environment, these are @samp{/}, @samp{\},
15912 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
15913 In a SFN environment, other characters are also invalid.  These
15914 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
15916 @item Invalid names (LFN)
15917 Some DOS file names are reserved, and cause problems if you
15918 try to use files with those names.  These names include @file{CON},
15919 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
15920 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
15921 File names are case insensitive, so even names like
15922 @file{aux/config.guess} are disallowed.
15924 @end table
15926 @node Shell Pattern Matching
15927 @section Shell Pattern Matching
15928 @cindex Shell pattern matching
15930 Nowadays portable patterns can use negated character classes like
15931 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
15932 some shells but not others; hence portable scripts should never use
15933 @samp{^} as the first character of a bracket pattern.
15935 Outside the C locale, patterns like @samp{[a-z]} are problematic since
15936 they may match characters that are not lower-case letters.
15938 @node Shell Substitutions
15939 @section Shell Substitutions
15940 @cindex Shell substitutions
15942 Contrary to a persistent urban legend, the Bourne shell does not
15943 systematically split variables and back-quoted expressions, in particular
15944 on the right-hand side of assignments and in the argument of @code{case}.
15945 For instance, the following code:
15947 @example
15948 case "$given_srcdir" in
15949 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
15950 *)  top_srcdir="$dots$given_srcdir" ;;
15951 esac
15952 @end example
15954 @noindent
15955 is more readable when written as:
15957 @example
15958 case $given_srcdir in
15959 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
15960 *)  top_srcdir=$dots$given_srcdir ;;
15961 esac
15962 @end example
15964 @noindent
15965 and in fact it is even @emph{more} portable: in the first case of the
15966 first attempt, the computation of @code{top_srcdir} is not portable,
15967 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"},
15968 for example Solaris 10 ksh:
15970 @example
15971 $ @kbd{foo="`echo " bar" | sed 's, ,,'`"}
15972 ksh: : cannot execute
15973 ksh: bar | sed 's, ,,': cannot execute
15974 @end example
15976 @noindent
15977 Posix does not specify behavior for this sequence.  On the other hand,
15978 behavior for @code{"`@dots{}\"@dots{}\"@dots{}`"} is specified by Posix,
15979 but in practice, not all shells understand it the same way: pdksh 5.2.14
15980 prints spurious quotes when in Posix mode:
15982 @example
15983 $ @kbd{echo "`echo \"hello\"`"}
15984 hello
15985 $ @kbd{set -o posix}
15986 $ @kbd{echo "`echo \"hello\"`"}
15987 "hello"
15988 @end example
15990 @noindent
15991 There is just no portable way to use double-quoted strings inside
15992 double-quoted back-quoted expressions (pfew!).
15994 Bash 4.1 has a bug where quoted empty strings adjacent to unquoted
15995 parameter expansions are elided during word splitting.  Meanwhile, zsh
15996 does not perform word splitting except when in Bourne compatibility
15997 mode.  In the example below, the correct behavior is to have five
15998 arguments to the function, and exactly two spaces on either side of the
15999 middle @samp{-}, since word splitting collapses multiple spaces in
16000 @samp{$f} but leaves empty arguments intact.
16002 @example
16003 $ @kbd{bash -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16004 3- - -
16005 $ @kbd{ksh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16006 5-  -  -
16007 $ @kbd{zsh -c 'n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16008 3-   -   -
16009 $ @kbd{zsh -c 'emulate sh;}
16010 > @kbd{n() @{ echo "$#$@@"; @}; f="  -  "; n - ""$f"" -'}
16011 5-  -  -
16012 @end example
16014 @noindent
16015 You can work around this by doing manual word splitting, such as using
16016 @samp{"$str" $list} rather than @samp{"$str"$list}.
16018 There are also portability pitfalls with particular expansions:
16020 @table @code
16021 @item $@@
16022 @cindex @code{"$@@"}
16023 One of the most famous shell-portability issues is related to
16024 @samp{"$@@"}.  When there are no positional arguments, Posix says
16025 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
16026 original Unix version 7 Bourne shell treated it as equivalent to
16027 @samp{""} instead, and this behavior survives in later implementations
16028 like Digital Unix 5.0.
16030 The traditional way to work around this portability problem is to use
16031 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
16032 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
16033 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
16035 @example
16036 zsh $ @kbd{emulate sh}
16037 zsh $ @kbd{for i in "$@@"; do echo $i; done}
16038 Hello World
16040 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
16041 Hello
16042 World
16044 @end example
16046 @noindent
16047 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
16048 @samp{"$@@"} because of the portability problems mentioned above.
16049 One workaround relies on Zsh's ``global aliases'' to convert
16050 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
16052 @example
16053 test $@{ZSH_VERSION+y@} && alias -g '$@{1+"$@@"@}'='"$@@"'
16054 @end example
16056 Zsh only recognizes this alias when a shell word matches it exactly;
16057 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
16058 case always yields at least one shell word, use plain @samp{"$@@"}.
16060 A more conservative workaround is to avoid @samp{"$@@"} if it is
16061 possible that there may be no positional arguments.  For example,
16062 instead of:
16064 @example
16065 cat conftest.c "$@@"
16066 @end example
16068 you can use this instead:
16070 @example
16071 case $# in
16072 0) cat conftest.c;;
16073 *) cat conftest.c "$@@";;
16074 esac
16075 @end example
16077 Autoconf macros often use the @command{set} command to update
16078 @samp{$@@}, so if you are writing shell code intended for
16079 @command{configure} you should not assume that the value of @samp{$@@}
16080 persists for any length of time.
16083 @item $@{10@}
16084 @cindex positional parameters
16085 The 10th, 11th, @dots{} positional parameters can be accessed only after
16086 a @code{shift}.  The 7th Edition shell reported an error if given
16087 @code{$@{10@}}, and
16088 Solaris 10 @command{/bin/sh} still acts that way:
16090 @example
16091 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
16092 $ @kbd{echo $@{10@}}
16093 bad substitution
16094 @end example
16096 Conversely, not all shells obey the Posix rule that when braces are
16097 omitted, multiple digits beyond a @samp{$} imply the single-digit
16098 positional parameter expansion concatenated with the remaining literal
16099 digits.  To work around the issue, you must use braces.
16101 @example
16102 $ @kbd{bash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16103 a0 a0
16104 $ @kbd{dash -c 'set a b c d e f g h i j; echo $10 $@{1@}0'}
16105 j a0
16106 @end example
16108 @item $@{@var{var}:-@var{value}@}
16109 @c Info cannot handle ':' in index entries.
16110 @ifnotinfo
16111 @cindex @code{$@{@var{var}:-@var{value}@}}
16112 @end ifnotinfo
16113 @cindex @code{$@{@var{var}-@var{value}@}}
16114 Old BSD shells, including the Ultrix @code{sh}, don't accept the
16115 colon for any shell substitution, and complain and die.
16116 Similarly for @code{$@{@var{var}:=@var{value}@}},
16117 @code{$@{@var{var}:?@var{value}@}}, etc.
16118 However, all shells that support functions allow the use of colon in
16119 shell substitution, and since m4sh requires functions, you can portably
16120 use null variable substitution patterns in configure scripts.
16122 @item $@{@var{var}+@var{value}@}
16123 @cindex @code{$@{@var{var}+@var{value}@}}
16124 When using @samp{$@{@var{var}-@var{value}@}} or
16125 @samp{$@{@var{var}-@var{value}@}} for providing alternate substitutions,
16126 @var{value} must either be a single shell word, quoted, or in the
16127 context of an unquoted here-document.  Solaris
16128 @command{/bin/sh} complains otherwise.
16130 @example
16131 $ @kbd{/bin/sh -c 'echo $@{a-b c@}'}
16132 /bin/sh: bad substitution
16133 $ @kbd{/bin/sh -c 'echo $@{a-'\''b c'\''@}'}
16134 b c
16135 $ @kbd{/bin/sh -c 'echo "$@{a-b c@}"'}
16136 b c
16137 $ @kbd{/bin/sh -c 'cat <<EOF
16138 $@{a-b c@}
16139 EOF}
16140 b c
16141 @end example
16143 Most shells treat the special parameters @code{*} and @code{@@} as being
16144 unset if there are no positional parameters.  However, some shells treat
16145 them as being set to the empty string.  Posix does not clearly specify
16146 either behavior.
16148 @example
16149 $ @kbd{bash -c 'echo "* is $@{*-unset@}."'}
16150 * is unset.
16151 $ @kbd{dash -c 'echo "* is $@{*-unset@}."'}
16152 * is .
16153 @end example
16155 According to Posix, if an expansion occurs inside double quotes, then
16156 the use of unquoted double quotes within @var{value} is unspecified, and
16157 any single quotes become literal characters; in that case, escaping must
16158 be done with backslash.  Likewise, the use of unquoted here-documents is
16159 a case where double quotes have unspecified results:
16161 @example
16162 $ @kbd{/bin/sh -c 'echo "$@{a-"b  c"@}"'}
16163 /bin/sh: bad substitution
16164 $ @kbd{ksh -c 'echo "$@{a-"b  c"@}"'}
16165 b c
16166 $ @kbd{bash -c 'echo "$@{a-"b  c"@}"'}
16167 b  c
16168 $ @kbd{/bin/sh -c 'a=; echo $@{a+'\''b  c'\''@}'}
16169 b  c
16170 $ @kbd{/bin/sh -c 'a=; echo "$@{a+'\''b  c'\''@}"'}
16171 'b  c'
16172 $ @kbd{/bin/sh -c 'a=; echo "$@{a+\"b  c\"@}"'}
16173 "b  c"
16174 $ @kbd{/bin/sh -c 'a=; echo "$@{a+b  c@}"'}
16175 b  c
16176 $ @kbd{/bin/sh -c 'cat <<EOF
16177 $@{a-"b  c"@}
16178 EOF'}
16179 "b  c"
16180 $ @kbd{/bin/sh -c 'cat <<EOF
16181 $@{a-'b  c'@}
16182 EOF'}
16183 'b  c'
16184 $ @kbd{bash -c 'cat <<EOF
16185 $@{a-"b  c"@}
16186 EOF'}
16187 b  c
16188 $ @kbd{bash -c 'cat <<EOF
16189 $@{a-'b  c'@}
16190 EOF'}
16191 'b  c'
16192 @end example
16194 Perhaps the easiest way to work around quoting issues in a manner
16195 portable to all shells is to place the results in a temporary variable,
16196 then use @samp{$t} as the @var{value}, rather than trying to inline
16197 the expression needing quoting.
16199 @example
16200 $ @kbd{/bin/sh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16201 b  c"'@}\
16202 $ @kbd{ksh -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16203 b  c"'@}\
16204 $ @kbd{bash -c 't="b  c\"'\''@}\\"; echo "$@{a-$t@}"'}
16205 b  c"'@}\
16206 @end example
16208 @item $@{@var{var}=@var{value}@}
16209 @cindex @code{$@{@var{var}=@var{value}@}}
16210 When using @samp{$@{@var{var}=@var{value}@}} to assign a default value
16211 to @var{var}, remember that even though the assignment to @var{var} does
16212 not undergo file name expansion, the result of the variable expansion
16213 does unless the expansion occurred within double quotes.  In particular,
16214 when using @command{:} followed by unquoted variable expansion for the
16215 side effect of setting a default value, if the final value of
16216 @samp{$var} contains any globbing characters (either from @var{value} or
16217 from prior contents), the shell has to spend time performing file name
16218 expansion and field splitting even though those results will not be
16219 used.  Therefore, it is a good idea to consider double quotes when performing
16220 default initialization; while remembering how this impacts any quoting
16221 characters appearing in @var{value}.
16223 @example
16224 $ @kbd{time bash -c ': "$@{a=/usr/bin/*@}"; echo "$a"'}
16225 /usr/bin/*
16227 real    0m0.005s
16228 user    0m0.002s
16229 sys     0m0.003s
16230 $ @kbd{time bash -c ': $@{a=/usr/bin/*@}; echo "$a"'}
16231 /usr/bin/*
16233 real    0m0.039s
16234 user    0m0.026s
16235 sys     0m0.009s
16236 $ @kbd{time bash -c 'a=/usr/bin/*; : $@{a=noglob@}; echo "$a"'}
16237 /usr/bin/*
16239 real    0m0.031s
16240 user    0m0.020s
16241 sys     0m0.010s
16243 $ @kbd{time bash -c 'a=/usr/bin/*; : "$@{a=noglob@}"; echo "$a"'}
16244 /usr/bin/*
16246 real    0m0.006s
16247 user    0m0.002s
16248 sys     0m0.003s
16249 @end example
16251 As with @samp{+} and @samp{-}, you must use quotes when using @samp{=}
16252 if the @var{value} contains more than one shell word; either single
16253 quotes for just the @var{value}, or double quotes around the entire
16254 expansion:
16256 @example
16257 $ @kbd{: $@{var1='Some words'@}}
16258 $ @kbd{: "$@{var2=like this@}"}
16259 $ @kbd{echo $var1 $var2}
16260 Some words like this
16261 @end example
16263 @noindent
16264 otherwise some shells, such as Solaris @command{/bin/sh} or on Digital
16265 Unix V 5.0, die because of a ``bad substitution''.  Meanwhile, Posix
16266 requires that with @samp{=}, quote removal happens prior to the
16267 assignment, and the expansion be the final contents of @var{var} without
16268 quoting (and thus subject to field splitting), in contrast to the
16269 behavior with @samp{-} passing the quoting through to the final
16270 expansion.  However, @command{bash} 4.1 does not obey this rule.
16272 @example
16273 $ @kbd{ksh -c 'echo $@{var-a\ \ b@}'}
16274 a  b
16275 $ @kbd{ksh -c 'echo $@{var=a\ \ b@}'}
16276 a b
16277 $ @kbd{bash -c 'echo $@{var=a\ \ b@}'}
16278 a  b
16279 @end example
16281 Finally, Posix states that when mixing @samp{$@{a=b@}} with regular
16282 commands, it is unspecified whether the assignments affect the parent
16283 shell environment.  It is best to perform assignments independently from
16284 commands, to avoid the problems demonstrated in this example:
16286 @example
16287 $ @kbd{bash -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16288 +b+b+
16290 $ @kbd{/bin/sh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16291 ++b+
16293 $ @kbd{ksh -c 'x= y=$@{x:=b@} sh -c "echo +\$x+\$y+";echo -$x-'}
16294 +b+b+
16296 @end example
16298 @item $@{@var{var}=@var{value}@}
16299 @cindex @code{$@{@var{var}=@var{literal}@}}
16300 Solaris @command{/bin/sh} has a frightening bug in its handling of
16301 literal assignments.  Imagine you need set a variable to a string containing
16302 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
16303 when the affected variable was already set.  This bug can be exercised
16304 by running:
16306 @example
16307 $ @kbd{unset foo}
16308 $ @kbd{foo=$@{foo='@}'@}}
16309 $ @kbd{echo $foo}
16311 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
16312 $ @kbd{echo $foo}
16314 $ @kbd{foo=$@{foo='@}'@}}
16315 $ @kbd{echo $foo}
16316 @}@}
16317  ^ ugh!
16318 @end example
16320 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
16321 though it is enclosed in single quotes.  The problem doesn't happen
16322 using double quotes, or when using a temporary variable holding the
16323 problematic string.
16325 @item $@{@var{var}=@var{expanded-value}@}
16326 @cindex @code{$@{@var{var}=@var{expanded-value}@}}
16327 On Ultrix,
16328 running
16330 @example
16331 default="yu,yaa"
16332 : $@{var="$default"@}
16333 @end example
16335 @noindent
16336 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
16337 each char is set.  You don't observe the phenomenon using a simple
16338 @samp{echo $var} since apparently the shell resets the 8th bit when it
16339 expands $var.  Here are two means to make this shell confess its sins:
16341 @example
16342 $ @kbd{cat -v <<EOF
16343 $var
16344 EOF}
16345 @end example
16347 @noindent
16350 @example
16351 $ @kbd{set | grep '^var=' | cat -v}
16352 @end example
16354 One classic incarnation of this bug is:
16356 @example
16357 default="a b c"
16358 : $@{list="$default"@}
16359 for c in $list; do
16360   echo $c
16361 done
16362 @end example
16364 @noindent
16365 You'll get @samp{a b c} on a single line.  Why?  Because there are no
16366 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
16367 bit set, hence no IFS splitting is performed!!!
16369 One piece of good news is that Ultrix works fine with @samp{:
16370 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
16371 then that QNX 4.25 then sets @var{list} to the @emph{last} item of
16372 @var{default}!
16374 The portable way out consists in using a double assignment, to switch
16375 the 8th bit twice on Ultrix:
16377 @example
16378 list=$@{list="$default"@}
16379 @end example
16381 @noindent
16382 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
16383 use:
16385 @example
16386 test $@{var+y@} || var=@var{@{value@}}
16387 @end example
16389 @item $@{#@var{var}@}
16390 @itemx $@{@var{var}%@var{word}@}
16391 @itemx $@{@var{var}%%@var{word}@}
16392 @itemx $@{@var{var}#@var{word}@}
16393 @itemx $@{@var{var}##@var{word}@}
16394 @cindex @code{$@{#@var{var}@}}
16395 @cindex @code{$@{@var{var}%@var{word}@}}
16396 @cindex @code{$@{@var{var}%%@var{word}@}}
16397 @cindex @code{$@{@var{var}#@var{word}@}}
16398 @cindex @code{$@{@var{var}##@var{word}@}}
16399 Posix requires support for these usages, but they do not work with many
16400 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
16402 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
16403 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
16404 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
16405 yields the empty string.
16408 @item `@var{commands}`
16409 @cindex @code{`@var{commands}`}
16410 @cindex Command Substitution
16411 Posix requires shells to trim all trailing newlines from command
16412 output before substituting it, so assignments like
16413 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
16414 @samp{$file} ends in a newline.
16416 While in general it makes no sense, do not substitute a single builtin
16417 with side effects, because Ash 0.2, trying to optimize, does not fork a
16418 subshell to perform the command.
16420 For instance, if you wanted to check that @command{cd} is silent, do not
16421 use @samp{test -z "`cd /`"} because the following can happen:
16423 @example
16424 $ @kbd{pwd}
16425 /tmp
16426 $ @kbd{test -z "`cd /`" && pwd}
16428 @end example
16430 @noindent
16431 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
16433 The MSYS shell leaves a stray byte in the expansion of a double-quoted
16434 command substitution of a native program, if the end of the substitution
16435 is not aligned with the end of the double quote.  This may be worked
16436 around by inserting another pair of quotes:
16438 @example
16439 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
16440 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
16441 - broken differ: char 4, line 1
16442 @end example
16444 Upon interrupt or SIGTERM, some shells may abort a command substitution,
16445 replace it with a null string, and wrongly evaluate the enclosing
16446 command before entering the trap or ending the script.  This can lead to
16447 spurious errors:
16449 @example
16450 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
16451 $ @kbd{^C}
16452 sh: test: hi: unexpected operator/operand
16453 @end example
16455 @noindent
16456 You can avoid this by assigning the command substitution to a temporary
16457 variable:
16459 @example
16460 $ @kbd{sh -c 'res=`sleep 5; echo hi`
16461          if test "x$res" = xhi; then echo yes; fi'}
16462 $ @kbd{^C}
16463 @end example
16465 @item $(@var{commands})
16466 @cindex @code{$(@var{commands})}
16467 This construct is meant to replace @samp{`@var{commands}`},
16468 and it has most of the problems listed under @code{`@var{commands}`}.
16470 This construct can be
16471 nested while this is impossible to do portably with back quotes.
16472 Although it is almost universally supported, unfortunately Solaris 10
16473 and earlier releases lack it:
16475 @example
16476 $ @kbd{showrev -c /bin/sh | grep version}
16477 Command version: SunOS 5.10 Generic 142251-02 Sep 2010
16478 $ @kbd{echo $(echo blah)}
16479 syntax error: `(' unexpected
16480 @end example
16482 @noindent
16483 nor does IRIX 6.5's Bourne shell:
16484 @example
16485 $ @kbd{uname -a}
16486 IRIX firebird-image 6.5 07151432 IP22
16487 $ @kbd{echo $(echo blah)}
16488 $(echo blah)
16489 @end example
16491 If you do use @samp{$(@var{commands})}, make sure that the commands
16492 do not start with a parenthesis, as that would cause confusion with
16493 a different notation @samp{$((@var{expression}))} that in modern
16494 shells is an arithmetic expression not a command.  To avoid the
16495 confusion, insert a space between the two opening parentheses.
16497 Avoid @var{commands} that contain unbalanced parentheses in
16498 here-documents, comments, or case statement patterns, as many shells
16499 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
16500 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
16502 @example
16503 echo $(case x in x) echo hello;; esac)
16504 @end example
16507 @item $((@var{expression}))
16508 @cindex @code{$((@var{expression}))}
16509 Arithmetic expansion is not portable as some shells (most
16510 notably Solaris 10 @command{/bin/sh}) don't support it.
16512 Among shells that do support @samp{$(( ))}, not all of them obey the
16513 Posix rule that octal and hexadecimal constants must be recognized:
16515 @example
16516 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
16518 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
16520 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
16522 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
16523 pdksh:  010 + 0x10 : bad number `0x10'
16524 $ @kbd{pdksh -c 'echo $(( 010 ))'}
16526 @end example
16528 When it is available, using arithmetic expansion provides a noticeable
16529 speedup in script execution; but testing for support requires
16530 @command{eval} to avoid syntax errors.  The following construct is used
16531 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
16532 arguments are provided in decimal and without a leading zero, and all
16533 operators are properly quoted and appear as distinct arguments:
16535 @example
16536 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
16537   eval 'func_arith ()
16538   @{
16539     func_arith_result=$(( $* ))
16540   @}'
16541 else
16542   func_arith ()
16543   @{
16544     func_arith_result=`expr "$@@"`
16545   @}
16547 func_arith 1 + 1
16548 foo=$func_arith_result
16549 @end example
16552 @item ^
16553 @cindex @code{^} quoting
16554 Always quote @samp{^}, otherwise traditional shells such as
16555 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
16557 @end table
16560 @node Assignments
16561 @section Assignments
16562 @cindex Shell assignments
16564 When setting several variables in a row, be aware that the order of the
16565 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
16566 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
16567 You must use
16568 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
16570 Don't rely on the following to find @file{subdir/program}:
16572 @example
16573 PATH=subdir$PATH_SEPARATOR$PATH program
16574 @end example
16576 @noindent
16577 as this does not work with Zsh 3.0.6.  Use something like this
16578 instead:
16580 @example
16581 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
16582 @end example
16584 Don't rely on the exit status of an assignment: Ash 0.2 does not change
16585 the status and propagates that of the last statement:
16587 @example
16588 $ @kbd{false || foo=bar; echo $?}
16590 $ @kbd{false || foo=`:`; echo $?}
16592 @end example
16594 @noindent
16595 and to make things even worse, QNX 4.25 just sets the exit status
16596 to 0 in any case:
16598 @example
16599 $ @kbd{foo=`exit 1`; echo $?}
16601 @end example
16603 To assign default values, follow this algorithm:
16605 @enumerate
16606 @item
16607 If the default value is a literal and does not contain any closing
16608 brace, use:
16610 @example
16611 : "$@{var='my literal'@}"
16612 @end example
16614 @item
16615 If the default value contains no closing brace, has to be expanded, and
16616 the variable being initialized is not intended to be IFS-split
16617 (i.e., it's not a list), then use:
16619 @example
16620 : $@{var="$default"@}
16621 @end example
16623 @item
16624 If the default value contains no closing brace, has to be expanded, and
16625 the variable being initialized is intended to be IFS-split (i.e., it's a list),
16626 then use:
16628 @example
16629 var=$@{var="$default"@}
16630 @end example
16632 @item
16633 If the default value contains a closing brace, then use:
16635 @example
16636 test $@{var+y@} || var="has a '@}'"
16637 @end example
16638 @end enumerate
16640 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
16641 doubt, just use the last form.  @xref{Shell Substitutions}, items
16642 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
16643 for the rationale.
16645 @node Parentheses
16646 @section Parentheses in Shell Scripts
16647 @cindex Shell parentheses
16649 Beware of two opening parentheses in a row, as many shell
16650 implementations treat them specially, and Posix says that a portable
16651 script cannot use @samp{((} outside the @samp{$((} form used for shell
16652 arithmetic.  In traditional shells, @samp{((cat))} behaves like
16653 @samp{(cat)}; but many shells, including
16654 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
16655 expression equivalent to @samp{let "cat"}, and may or may not report an
16656 error when they detect that @samp{cat} is not a number.  As another
16657 example, @samp{pdksh} 5.2.14 does not treat the following code
16658 as a traditional shell would:
16660 @example
16661 if ((true) || false); then
16662   echo ok
16664 @end example
16666 @noindent
16667 To work around this problem, insert a space between the two opening
16668 parentheses.  There is a similar problem and workaround with
16669 @samp{$((}; see @ref{Shell Substitutions}.
16671 @node Slashes
16672 @section Slashes in Shell Scripts
16673 @cindex Shell slashes
16675 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
16676 arguments that contain two trailing slashes:
16678 @example
16679 $ @kbd{echo / // /// //// .// //.}
16680 / / // /// ./ //.
16681 $ @kbd{x=//}
16682 $ @kbd{eval "echo \$x"}
16684 $ @kbd{set -x}
16685 $ @kbd{echo abc | tr -t ab //}
16686 + echo abc
16687 + tr -t ab /
16689 @end example
16691 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
16692 variable is empty and the second double-quote is followed by a word that
16693 begins and ends with slash:
16695 @example
16696 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
16698 + echo //ouch/
16699 //ouch/
16700 @end example
16702 However, our understanding is that patches are available, so perhaps
16703 it's not worth worrying about working around these horrendous bugs.
16705 @node Special Shell Variables
16706 @section Special Shell Variables
16707 @cindex Shell variables
16708 @cindex Special shell variables
16710 Some shell variables should not be used, since they can have a deep
16711 influence on the behavior of the shell.  In order to recover a sane
16712 behavior from the shell, some variables should be unset; M4sh takes
16713 care of this and provides fallback values, whenever needed, to cater
16714 for a very old @file{/bin/sh} that does not support @command{unset}.
16715 (@pxref{Portable Shell, , Portable Shell Programming}).
16717 As a general rule, shell variable names containing a lower-case letter
16718 are safe; you can define and use these variables without worrying about
16719 their effect on the underlying system, and without worrying about
16720 whether the shell changes them unexpectedly.  (The exception is the
16721 shell variable @code{status}, as described below.)
16723 Here is a list of names that are known to cause trouble.  This list is
16724 not exhaustive, but you should be safe if you avoid the name
16725 @code{status} and names containing only upper-case letters and
16726 underscores.
16728 @c Alphabetical order, case insensitive, `A' before `a'.
16729 @table @code
16730 @item ?
16731 Not all shells correctly reset @samp{$?} after conditionals (@pxref{if,
16732 , Limitations of Shell Builtins}).  Not all shells manage @samp{$?}
16733 correctly in shell functions (@pxref{Shell Functions}) or in traps
16734 (@pxref{trap, , Limitations of Shell Builtins}).  Not all shells reset
16735 @samp{$?} to zero after an empty command.
16737 @example
16738 $ @kbd{bash -c 'false; $empty; echo $?'}
16740 $ @kbd{zsh -c 'false; $empty; echo $?'}
16742 @end example
16744 @item _
16745 @evindex _
16746 Many shells reserve @samp{$_} for various purposes, e.g., the name of
16747 the last command executed.
16749 @item BIN_SH
16750 @evindex BIN_SH
16751 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
16752 the standard shell conform to Posix.
16754 @item CDPATH
16755 @evindex CDPATH
16756 When this variable is set it specifies a list of directories to search
16757 when invoking @code{cd} with a relative file name that did not start
16758 with @samp{./} or @samp{../}.  Posix
16759 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
16760 is used successfully, @code{cd} prints the resulting absolute
16761 file name.  Unfortunately this output can break idioms like
16762 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
16763 Also, many shells do not conform to this part of Posix; for
16764 example, @command{zsh} prints the result only if a directory name
16765 other than @file{.} was chosen from @env{CDPATH}.
16767 In practice the shells that have this problem also support
16768 @command{unset}, so you can work around the problem as follows:
16770 @example
16771 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
16772 @end example
16774 You can also avoid output by ensuring that your directory name is
16775 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
16777 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
16778 possible, so you need not worry about this problem in those scripts.
16780 @item CLICOLOR_FORCE
16781 @evindex CLICOLOR_FORCE
16782 When this variable is set, some implementations of tools like
16783 @command{ls} attempt to add color to their output via terminal escape
16784 sequences, even when the output is not directed to a terminal, and can
16785 thus cause spurious failures in scripts.  Configure scripts use M4sh,
16786 which automatically unsets this variable.
16788 @item DUALCASE
16789 @evindex DUALCASE
16790 In the MKS shell, case statements and file name generation are
16791 case-insensitive unless @env{DUALCASE} is nonzero.
16792 Autoconf-generated scripts export this variable when they start up.
16794 @item ENV
16795 @itemx MAIL
16796 @itemx MAILPATH
16797 @itemx PS1
16798 @itemx PS2
16799 @itemx PS4
16800 @evindex ENV
16801 @evindex MAIL
16802 @evindex MAILPATH
16803 @evindex PS1
16804 @evindex PS2
16805 @evindex PS4
16806 These variables should not matter for shell scripts, since they are
16807 supposed to affect only interactive shells.  However, at least one
16808 shell (the pre-3.0 UWIN Korn shell) gets confused about
16809 whether it is interactive, which means that (for example) a @env{PS1}
16810 with a side effect can unexpectedly modify @samp{$?}.  To work around
16811 this bug, M4sh scripts (including @file{configure} scripts) do something
16812 like this:
16814 @example
16815 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
16816 PS1='$ '
16817 PS2='> '
16818 PS4='+ '
16819 @end example
16821 @noindent
16822 (actually, there is some complication due to bugs in @command{unset};
16823 @pxref{unset, , Limitations of Shell Builtins}).
16825 @item FPATH
16826 @evindex FPATH
16827 The Korn shell uses @env{FPATH} to find shell functions, so avoid
16828 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
16829 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
16830 to find whether a command exists, since they might report the wrong
16831 result if @env{FPATH} is also set.
16833 @item GREP_OPTIONS
16834 @evindex GREP_OPTIONS
16835 When this variable is set, some implementations of @command{grep} honor
16836 these options, even if the options include direction to enable colored
16837 output via terminal escape sequences, and the result can cause spurious
16838 failures when the output is not directed to a terminal.  Configure
16839 scripts use M4sh, which automatically unsets this variable.
16841 @item IFS
16842 @evindex IFS
16843 Long ago, shell scripts inherited @env{IFS} from the environment,
16844 but this caused many problems so modern shells ignore any environment
16845 settings for @env{IFS}.
16847 Don't set the first character of @env{IFS} to backslash.  Indeed,
16848 Bourne shells use the first character (backslash) when joining the
16849 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
16850 backslash escapes, so you can end up with backspace and other strange
16851 characters.
16853 The proper value for @env{IFS} (in regular code, not when performing
16854 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
16855 especially important, as it is used to join the arguments in @samp{$*};
16856 however, note that traditional shells, but also bash-2.04, fail to adhere
16857 to this and join with a space anyway.
16859 M4sh guarantees that @env{IFS} will have the default value at the
16860 beginning of a script, and many macros within autoconf rely on this
16861 setting.  It is okay to use blocks of shell code that temporarily change
16862 the value of @env{IFS} in order to split on another character, but
16863 remember to restore it before expanding further macros.
16865 Unsetting @code{IFS} instead of resetting it to the default sequence
16866 is not suggested, since code that tries to save and restore the
16867 variable's value will incorrectly reset it to an empty value, thus
16868 disabling field splitting:
16870 @example
16871 unset IFS
16872 # default separators used for field splitting
16874 save_IFS=$IFS
16875 IFS=:
16876 # ...
16877 IFS=$save_IFS
16878 # no field splitting performed
16879 @end example
16881 @item LANG
16882 @itemx LC_ALL
16883 @itemx LC_COLLATE
16884 @itemx LC_CTYPE
16885 @itemx LC_MESSAGES
16886 @itemx LC_MONETARY
16887 @itemx LC_NUMERIC
16888 @itemx LC_TIME
16889 @evindex LANG
16890 @evindex LC_ALL
16891 @evindex LC_COLLATE
16892 @evindex LC_CTYPE
16893 @evindex LC_MESSAGES
16894 @evindex LC_MONETARY
16895 @evindex LC_NUMERIC
16896 @evindex LC_TIME
16898 You should set all these variables to @samp{C} because so much
16899 configuration code assumes the C locale and Posix requires that locale
16900 environment variables be set to @samp{C} if the C locale is desired;
16901 @file{configure} scripts and M4sh do that for you.
16902 Export these variables after setting them.
16904 @c  However, some older, nonstandard
16905 @c  systems (notably SCO) break if locale environment variables
16906 @c  are set to @samp{C}, so when running on these systems
16907 @c  Autoconf-generated scripts unset the variables instead.
16909 @item LANGUAGE
16910 @evindex LANGUAGE
16912 @env{LANGUAGE} is not specified by Posix, but it is a GNU
16913 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
16914 should set it too.
16916 @item LC_ADDRESS
16917 @itemx LC_IDENTIFICATION
16918 @itemx LC_MEASUREMENT
16919 @itemx LC_NAME
16920 @itemx LC_PAPER
16921 @itemx LC_TELEPHONE
16922 @evindex LC_ADDRESS
16923 @evindex LC_IDENTIFICATION
16924 @evindex LC_MEASUREMENT
16925 @evindex LC_NAME
16926 @evindex LC_PAPER
16927 @evindex LC_TELEPHONE
16929 These locale environment variables are GNU extensions.  They
16930 are treated like their Posix brethren (@env{LC_COLLATE},
16931 etc.)@: as described above.
16933 @item LINENO
16934 @evindex LINENO
16935 Most modern shells provide the current line number in @code{LINENO}.
16936 Its value is the line number of the beginning of the current command.
16937 M4sh, and hence Autoconf, attempts to execute @command{configure} with
16938 a shell that supports @code{LINENO}.  If no such shell is available, it
16939 attempts to implement @code{LINENO} with a Sed prepass that replaces each
16940 instance of the string @code{$LINENO} (not followed by an alphanumeric
16941 character) with the line's number.  In M4sh scripts you should execute
16942 @code{AS_LINENO_PREPARE} so that these workarounds are included in
16943 your script; configure scripts do this automatically in @code{AC_INIT}.
16945 You should not rely on @code{LINENO} within @command{eval} or shell
16946 functions, as the behavior differs in practice.  The presence of a
16947 quoted newline within simple commands can alter which line number is
16948 used as the starting point for @code{$LINENO} substitutions within that
16949 command.  Also, the possibility of the Sed prepass means that you should
16950 not rely on @code{$LINENO} when quoted, when in here-documents, or when
16951 line continuations are used.  Subshells should be OK, though.  In the
16952 following example, lines 1, 9, and 14 are portable, but the other
16953 instances of @code{$LINENO} do not have deterministic values:
16955 @example
16956 @group
16957 $ @kbd{cat lineno}
16958 echo 1. $LINENO
16959 echo "2. $LINENO
16960 3. $LINENO"
16961 cat <<EOF
16962 5. $LINENO
16963 6. $LINENO
16964 7. \$LINENO
16966 ( echo 9. $LINENO )
16967 eval 'echo 10. $LINENO'
16968 eval 'echo 11. $LINENO
16969 echo 12. $LINENO'
16970 echo 13. '$LINENO'
16971 echo 14. $LINENO '
16972 15.' $LINENO
16973 f () @{ echo $1 $LINENO;
16974 echo $1 $LINENO @}
16975 f 18.
16976 echo 19. \
16977 $LINENO
16978 @end group
16979 @group
16980 $ @kbd{bash-3.2 ./lineno}
16981 1. 1
16982 2. 3
16983 3. 3
16984 5. 4
16985 6. 4
16986 7. $LINENO
16987 9. 9
16988 10. 10
16989 11. 12
16990 12. 13
16991 13. $LINENO
16992 14. 14
16993 15. 14
16994 18. 16
16995 18. 17
16996 19. 19
16997 @end group
16998 @group
16999 $ @kbd{zsh-4.3.4 ./lineno}
17000 1. 1
17001 2. 2
17002 3. 2
17003 5. 4
17004 6. 4
17005 7. $LINENO
17006 9. 9
17007 10. 1
17008 11. 1
17009 12. 2
17010 13. $LINENO
17011 14. 14
17012 15. 14
17013 18. 0
17014 18. 1
17015 19. 19
17016 @end group
17017 @group
17018 $ @kbd{pdksh-5.2.14 ./lineno}
17019 1. 1
17020 2. 2
17021 3. 2
17022 5. 4
17023 6. 4
17024 7. $LINENO
17025 9. 9
17026 10. 0
17027 11. 0
17028 12. 0
17029 13. $LINENO
17030 14. 14
17031 15. 14
17032 18. 16
17033 18. 17
17034 19. 19
17035 @end group
17036 @group
17037 $ @kbd{sed '=' <lineno |}
17038 > @kbd{  sed '}
17039 > @kbd{    N}
17040 > @kbd{    s,$,-,}
17041 > @kbd{    t loop}
17042 > @kbd{    :loop}
17043 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
17044 > @kbd{    t loop}
17045 > @kbd{    s,-$,,}
17046 > @kbd{    s,^[0-9]*\n,,}
17047 > @kbd{  ' |}
17048 > @kbd{  sh}
17049 1. 1
17050 2. 2
17051 3. 3
17052 5. 5
17053 6. 6
17054 7. \7
17055 9. 9
17056 10. 10
17057 11. 11
17058 12. 12
17059 13. 13
17060 14. 14
17061 15. 15
17062 18. 16
17063 18. 17
17064 19. 20
17065 @end group
17066 @end example
17068 In particular, note that @file{config.status} (and any other subsidiary
17069 script created by @code{AS_INIT_GENERATED}) might report line numbers
17070 relative to the parent script as a result of the potential Sed pass.
17072 @item NULLCMD
17073 @evindex NULLCMD
17074 When executing the command @samp{>foo}, @command{zsh} executes
17075 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
17076 compatibility mode and the @command{zsh} version is newer
17077 than 3.1.6-dev-18.  If you are using an older @command{zsh}
17078 and forget to set @env{NULLCMD},
17079 your script might be suspended waiting for data on its standard input.
17081 @item options
17082 @evindex options
17083 For @command{zsh} 4.3.10, @env{options} is treated as an associative
17084 array even after @code{emulate sh}, so it should not be used.
17086 @item PATH_SEPARATOR
17087 @evindex PATH_SEPARATOR
17088 On DJGPP systems, the @env{PATH_SEPARATOR} environment
17089 variable can be set to either @samp{:} or @samp{;} to control the path
17090 separator Bash uses to set up certain environment variables (such as
17091 @env{PATH}).  You can set this variable to @samp{;} if you want
17092 @command{configure} to use @samp{;} as a separator; this might be useful
17093 if you plan to use non-Posix shells to execute files.  @xref{File System
17094 Conventions}, for more information about @code{PATH_SEPARATOR}.
17096 @item POSIXLY_CORRECT
17097 @evindex POSIXLY_CORRECT
17098 In the GNU environment, exporting @env{POSIXLY_CORRECT} with any value
17099 (even empty) causes programs to try harder to conform to Posix.
17100 Autoconf does not directly manipulate this variable, but @command{bash}
17101 ties the shell variable @env{POSIXLY_CORRECT} to whether the script is
17102 running in Posix mode.  Therefore, take care when exporting or unsetting
17103 this variable, so as not to change whether @command{bash} is in Posix
17104 mode.
17106 @example
17107 $ @kbd{bash --posix -c 'set -o | grep posix}
17108 > @kbd{unset POSIXLY_CORRECT}
17109 > @kbd{set -o | grep posix'}
17110 posix           on
17111 posix           off
17112 @end example
17114 @item PWD
17115 @evindex PWD
17116 Posix 1003.1-2001 requires that @command{cd} and
17117 @command{pwd} must update the @env{PWD} environment variable to point
17118 to the logical name of the current directory, but traditional shells
17119 do not support this.  This can cause confusion if one shell instance
17120 maintains @env{PWD} but a subsidiary and different shell does not know
17121 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
17122 points to the wrong directory.  Use @samp{`pwd`} rather than
17123 @samp{$PWD}.
17125 @item RANDOM
17126 @evindex RANDOM
17127 Many shells provide @code{RANDOM}, a variable that returns a different
17128 integer each time it is used.  Most of the time, its value does not
17129 change when it is not used, but on IRIX 6.5 the value changes all
17130 the time.  This can be observed by using @command{set}.  It is common
17131 practice to use @code{$RANDOM} as part of a file name, but code
17132 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
17134 @item status
17135 @evindex status
17136 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
17137 hence read-only.  Do not use it.
17138 @end table
17140 @node Shell Functions
17141 @section Shell Functions
17142 @cindex Shell Functions
17144 Nowadays, it is difficult to find a shell that does not support
17145 shell functions at all.  However, some differences should be expected.
17147 When declaring a shell function, you must include whitespace between the
17148 @samp{)} after the function name and the start of the compound
17149 expression, to avoid upsetting @command{ksh}.  While it is possible to
17150 use any compound command, most scripts use @samp{@{@dots{}@}}.
17152 @example
17153 $ @kbd{/bin/sh -c 'a()@{ echo hi;@}; a'}
17155 $ @kbd{ksh -c 'a()@{ echo hi;@}; a'}
17156 ksh: syntax error at line 1: `@}' unexpected
17157 $ @kbd{ksh -c 'a() @{ echo hi;@}; a'}
17159 @end example
17161 Inside a shell function, you should not rely on the error status of a
17162 subshell if the last command of that subshell was @code{exit} or
17163 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
17164 find a shell that does not exhibit the bug, zsh might be the only shell
17165 present on the user's machine.
17167 Likewise, the state of @samp{$?} is not reliable when entering a shell
17168 function.  This has the effect that using a function as the first
17169 command in a @command{trap} handler can cause problems.
17171 @example
17172 $ @kbd{bash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17175 $ @kbd{ash -c 'foo() @{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
17178 @end example
17180 DJGPP bash 2.04 has a bug in that @command{return} from a
17181 shell function which also used a command substitution causes a
17182 segmentation fault.  To work around the issue, you can use
17183 @command{return} from a subshell, or @samp{AS_SET_STATUS} as last command
17184 in the execution flow of the function (@pxref{Common Shell Constructs}).
17186 Not all shells treat shell functions as simple commands impacted by
17187 @samp{set -e}, for example with Solaris 10 @command{/bin/sh}:
17189 @example
17190 $ @kbd{bash -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17191 $ @kbd{/bin/sh -c 'f() @{ return 1; @}; set -e; f; echo oops'}
17192 oops
17193 @end example
17195 Shell variables and functions may share the same namespace, for example
17196 with Solaris 10 @command{/bin/sh}:
17198 @example
17199 $ @kbd{f () @{ :; @}; f=; f}
17200 f: not found
17201 @end example
17203 @noindent
17204 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
17205 uses the prefix @samp{as_fn_} for its functions.
17207 Handling of positional parameters and shell options varies among shells.
17208 For example, Korn shells reset and restore trace output (@samp{set -x})
17209 and other options upon function entry and exit.  Inside a function,
17210 IRIX sh sets @samp{$0} to the function name.
17212 It is not portable to pass temporary environment variables to shell
17213 functions.  Solaris @command{/bin/sh} does not see the variable.
17214 Meanwhile, not all shells follow the Posix rule that the assignment must
17215 affect the current environment in the same manner as special built-ins.
17217 @example
17218 $ @kbd{/bin/sh -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17219 @result{}
17220 @result{}
17221 $ @kbd{ash -c 'func() @{ echo $a;@}; a=1 func; echo $a'}
17222 @result{}1
17223 @result{}
17224 $ @kbd{bash -c 'set -o posix; func() @{ echo $a;@}; a=1 func; echo $a'}
17225 @result{}1
17226 @result{}1
17227 @end example
17229 Some ancient Bourne shell variants with function support did not reset
17230 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
17231 arguments of the script were lost after the first function invocation.
17232 It is probably not worth worrying about these shells any more.
17234 With AIX sh, a @command{trap} on 0 installed in a shell function
17235 triggers at function exit rather than at script exit.  @xref{trap, ,
17236 Limitations of Shell Builtins}.
17238 @node Limitations of Builtins
17239 @section Limitations of Shell Builtins
17240 @cindex Shell builtins
17241 @cindex Limitations of shell builtins
17243 No, no, we are serious: some shells do have limitations!  :)
17245 You should always keep in mind that any builtin or command may support
17246 options, and therefore differ in behavior with arguments
17247 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
17248 can give unexpected results when @code{word} starts with a dash.  It is
17249 often possible to avoid this problem using @samp{echo "x$word"}, taking
17250 the @samp{x} into account later in the pipe.  Many of these limitations
17251 can be worked around using M4sh (@pxref{Programming in M4sh}).
17253 @c This table includes things like `@command{test} (files)', so we can't
17254 @c use @table @command.
17255 @table @asis
17256 @item @command{.}
17257 @c --------------
17258 @prindex @command{.}
17259 Use @command{.} only with regular files (use @samp{test -f}).  Bash
17260 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
17261 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
17262 some shells, including bash 3.2, implicitly append the current directory
17263 to this @env{PATH} search, even though Posix forbids it.  So if you want
17264 to use @command{.} on a file @file{foo} in the current directory, you
17265 must use @samp{. ./foo}.
17267 Not all shells gracefully handle syntax errors within a sourced file.
17268 On one extreme, some non-interactive shells abort the entire script.  On
17269 the other, @command{zsh} 4.3.10 has a bug where it fails to react to the
17270 syntax error.
17272 @example
17273 $ @kbd{echo 'fi' > syntax}
17274 $ @kbd{bash -c '. ./syntax; echo $?'}
17275 ./syntax: line 1: syntax error near unexpected token `fi'
17276 ./syntax: line 1: `fi'
17278 $ @kbd{ash -c '. ./syntax; echo $?'}
17279 ./syntax: 1: Syntax error: "fi" unexpected
17280 $ @kbd{zsh -c '. ./syntax; echo $?'}
17281 ./syntax:1: parse error near `fi'
17283 @end example
17285 @item @command{!}
17286 @c --------------
17287 @prindex @command{!}
17288 The Unix version 7 shell did not support
17289 negating the exit status of commands with @command{!}, and this feature
17290 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
17291 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
17292 bugs when using @command{!}:
17294 @example
17295 $ @kbd{sh -c '! : | :'; echo $?}
17297 $ @kbd{ash -c '! : | :'; echo $?}
17299 $ @kbd{sh -c '! @{ :; @}'; echo $?}
17301 $ @kbd{ash -c '! @{ :; @}'; echo $?}
17302 @{: not found
17303 Syntax error: "@}" unexpected
17305 @end example
17307 Shell code like this:
17309 @example
17310 if ! cmp file1 file2 >/dev/null 2>&1; then
17311   echo files differ or trouble
17313 @end example
17315 is therefore not portable in practice.  Typically it is easy to rewrite
17316 such code, e.g.:
17318 @example
17319 cmp file1 file2 >/dev/null 2>&1 ||
17320   echo files differ or trouble
17321 @end example
17323 More generally, one can always rewrite @samp{! @var{command}} as:
17325 @example
17326 if @var{command}; then (exit 1); else :; fi
17327 @end example
17330 @item @command{@{...@}}
17331 @c --------------------
17332 @prindex @command{@{...@}}
17333 Bash 3.2 (and earlier versions) sometimes does not properly set
17334 @samp{$?} when failing to write redirected output of a compound command.
17335 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
17336 not occur with @samp{(@dots{})}.  For example:
17338 @example
17339 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
17340 bash: line 1: /bad: Permission denied
17342 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
17343 bash: line 1: /bad: Permission denied
17345 @end example
17347 To work around the bug, prepend @samp{:;}:
17349 @example
17350 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
17351 bash: line 1: /bad: Permission denied
17353 @end example
17355 Posix requires a syntax error if a brace list has no contents.  However,
17356 not all shells obey this rule; and on shells where empty lists are
17357 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
17358 ensure that a brace list is never empty.
17360 @example
17361 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
17362 bash: line 1: syntax error near unexpected token `@}'
17363 bash: line 1: `false; @{ @}; echo $?'
17365 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
17367 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
17369 @end example
17372 @item @command{break}
17373 @c ------------------
17374 @prindex @command{break}
17375 The use of @samp{break 2} etc.@: is safe.
17378 @anchor{case}
17379 @item @command{case}
17380 @c -----------------
17381 @prindex @command{case}
17382 You don't need to quote the argument; no splitting is performed.
17384 You don't need the final @samp{;;}, but you should use it.
17386 Posix requires support for @code{case} patterns with opening
17387 parentheses like this:
17389 @example
17390 case $file_name in
17391   (*.c) echo "C source code";;
17392 esac
17393 @end example
17395 @noindent
17396 but the @code{(} in this example is not portable to many Bourne
17397 shell implementations, which is a pity for those of us using tools that
17398 rely on balanced parentheses.  For instance, with Solaris
17399 @command{/bin/sh}:
17401 @example
17402 $ @kbd{case foo in (foo) echo foo;; esac}
17403 @error{}syntax error: `(' unexpected
17404 @end example
17406 @noindent
17407 The leading @samp{(} can be omitted safely.  Unfortunately, there are
17408 contexts where unbalanced parentheses cause other problems, such as when
17409 using a syntax-highlighting editor that searches for the balancing
17410 counterpart, or more importantly, when using a case statement as an
17411 underquoted argument to an Autoconf macro.  @xref{Balancing
17412 Parentheses}, for tradeoffs involved in various styles of dealing with
17413 unbalanced @samp{)}.
17415 Zsh handles pattern fragments derived from parameter expansions or
17416 command substitutions as though quoted:
17418 @example
17419 $ pat=\?; case aa in ?$pat) echo match;; esac
17420 $ pat=\?; case a? in ?$pat) echo match;; esac
17421 match
17422 @end example
17424 @noindent
17425 Because of a bug in its @code{fnmatch}, Bash fails to properly
17426 handle backslashes in character classes:
17428 @example
17429 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
17430 bash-2.02$
17431 @end example
17433 @noindent
17434 This is extremely unfortunate, since you are likely to use this code to
17435 handle Posix or MS-DOS absolute file names.  To work around this
17436 bug, always put the backslash first:
17438 @example
17439 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
17441 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
17443 @end example
17445 Many Bourne shells cannot handle closing brackets in character classes
17446 correctly.
17448 Some shells also have problems with backslash escaping in case you do not want
17449 to match the backslash: both a backslash and the escaped character match this
17450 pattern.  To work around this, specify the character class in a variable, so
17451 that quote removal does not apply afterwards, and the special characters don't
17452 have to be backslash-escaped:
17454 @example
17455 $ @kbd{case '\' in [\<]) echo OK;; esac}
17457 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
17459 @end example
17461 Even with this, Solaris @command{ksh} matches a backslash if the set
17462 contains any
17463 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
17465 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
17466 a closing parenthesis if not specified in a character class:
17468 @example
17469 $ @kbd{case foo in *\)*) echo fail ;; esac}
17470 fail
17471 $ @kbd{case foo in *')'*) echo fail ;; esac}
17472 fail
17473 @end example
17475 Some shells, such as Ash 0.3.8, are confused by an empty
17476 @code{case}/@code{esac}:
17478 @example
17479 ash-0.3.8 $ @kbd{case foo in esac;}
17480 @error{}Syntax error: ";" unexpected (expecting ")")
17481 @end example
17483 Posix requires @command{case} to give an exit status of 0 if no cases
17484 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
17485 rule.  Meanwhile, it is unclear whether a case that matches, but
17486 contains no statements, must also change the exit status to 0.  The M4sh
17487 macro @code{AS_CASE} works around these inconsistencies.
17489 @example
17490 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
17492 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
17494 @end example
17497 @item @command{cd}
17498 @c ---------------
17499 @prindex @command{cd}
17500 Posix 1003.1-2001 requires that @command{cd} must support
17501 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17502 with @option{-L} being the default.  However, traditional shells do
17503 not support these options, and their @command{cd} command has the
17504 @option{-P} behavior.
17506 Portable scripts should assume neither option is supported, and should
17507 assume neither behavior is the default.  This can be a bit tricky,
17508 since the Posix default behavior means that, for example,
17509 @samp{ls ..} and @samp{cd ..} may refer to different directories if
17510 the current logical directory is a symbolic link.  It is safe to use
17511 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
17512 Also, Autoconf-generated scripts check for this problem when computing
17513 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
17514 so it is safe to @command{cd} to these variables.
17516 Posix states that behavior is undefined if @command{cd} is given an
17517 explicit empty argument.  Some shells do nothing, some change to the
17518 first entry in @env{CDPATH}, some change to @env{HOME}, and some exit
17519 the shell rather than returning an error.  Unfortunately, this means
17520 that if @samp{$var} is empty, then @samp{cd "$var"} is less predictable
17521 than @samp{cd $var} (at least the latter is well-behaved in all shells
17522 at changing to @env{HOME}, although this is probably not what you wanted
17523 in a script).  You should check that a directory name was supplied
17524 before trying to change locations.
17526 @xref{Special Shell Variables}, for portability problems involving
17527 @command{cd} and the @env{CDPATH} environment variable.
17528 Also please see the discussion of the @command{pwd} command.
17531 @anchor{echo}
17532 @item @command{echo}
17533 @c -----------------
17534 @prindex @command{echo}
17535 The simple @command{echo} is probably the most surprising source of
17536 portability troubles.  It is not possible to use @samp{echo} portably
17537 unless both options and escape sequences are omitted.  Don't expect any
17538 option.
17540 Do not use backslashes in the arguments, as there is no consensus on
17541 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
17542 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
17543 The problem is truly @command{echo}: all the shells
17544 understand @samp{'\n'} as the string composed of a backslash and an
17545 @samp{n}.  Within a command substitution, @samp{echo 'string\c'} will
17546 mess up the internal state of ksh88 on AIX 6.1 so that it will print
17547 the first character @samp{s} only, followed by a newline, and then
17548 entirely drop the output of the next echo in a command substitution.
17550 Because of these problems, do not pass a string containing arbitrary
17551 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
17552 only if you know that @var{foo}'s value cannot contain backslashes and
17553 cannot start with @samp{-}.
17555 Normally, @command{printf} is safer and easier to use than @command{echo}
17556 and @command{echo -n}.  Thus, you should use @command{printf "%s\n"}
17557 instead of @command{echo}, and similarly use @command{printf %s} instead
17558 of @command{echo -n}.
17560 Older scripts, written before @command{printf} was portable,
17561 sometimes used a here-document as a safer alternative to @command{echo},
17562 like this:
17564 @example
17565 cat <<EOF
17566 $foo
17568 @end example
17571 @item @command{eval}
17572 @c -----------------
17573 @prindex @command{eval}
17574 The @command{eval} command is useful in limited circumstances, e.g.,
17575 using commands like @samp{eval table_$key=\$value} and @samp{eval
17576 value=table_$key} to simulate a hash table when the key is known to be
17577 alphanumeric.
17579 You should also be wary of common bugs in @command{eval} implementations.
17580 In some shell implementations (e.g., older @command{ash}, OpenBSD 3.8
17581 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
17582 4.2.5), the arguments of @samp{eval} are evaluated in a context where
17583 @samp{$?} is 0, so they exhibit behavior like this:
17585 @example
17586 $ @kbd{false; eval 'echo $?'}
17588 @end example
17590 The correct behavior here is to output a nonzero value,
17591 but portable scripts should not rely on this.
17593 You should not rely on @code{LINENO} within @command{eval}.
17594 @xref{Special Shell Variables}.
17596 Note that, even though these bugs are easily avoided,
17597 @command{eval} is tricky to use on arbitrary arguments.
17598 It is obviously unwise to use @samp{eval $cmd} if the string value of
17599 @samp{cmd} was derived from an untrustworthy source.  But even if the
17600 string value is valid, @samp{eval $cmd} might not work as intended,
17601 since it causes field splitting and file name expansion to occur twice,
17602 once for the @command{eval} and once for the command itself.  It is
17603 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
17604 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
17605 equivalent of @samp{cat test;.c} if there happens to be a file named
17606 @file{test;.c} in the current directory; and this in turn
17607 mistakenly attempts to invoke @command{cat} on the file @file{test} and
17608 then execute the command @command{.c}.  To avoid this problem, use
17609 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
17611 However, suppose that you want to output the text of the evaluated
17612 command just before executing it.  Assuming the previous example,
17613 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
17614 this output doesn't show the user that @samp{test;.c} is the actual name
17615 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
17616 works on this example, but it fails with @samp{cmd='cat foo >bar'},
17617 since it mistakenly replaces the contents of @file{bar} by the
17618 string @samp{cat foo}.  No simple, general, and portable solution to
17619 this problem is known.
17621 @item @command{exec}
17622 @c -----------------
17623 @prindex @command{exec}
17624 Posix describes several categories of shell built-ins.  Special
17625 built-ins (such as @command{exit}) must impact the environment of the
17626 current shell, and need not be available through @command{exec}.  All
17627 other built-ins are regular, and must not propagate variable assignments
17628 to the environment of the current shell.  However, the group of regular
17629 built-ins is further distinguished by commands that do not require a
17630 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
17631 are offered as a more efficient version of something that must still be
17632 found in a @env{PATH} search (such as @command{echo}).  Posix is not
17633 clear on whether @command{exec} must work with the list of 17 utilities
17634 that are invoked without a @env{PATH} search, and many platforms lack an
17635 executable for some of those built-ins:
17637 @example
17638 $ @kbd{sh -c 'exec cd /tmp'}
17639 sh: line 0: exec: cd: not found
17640 @end example
17642 All other built-ins that provide utilities specified by Posix must have
17643 a counterpart executable that exists on @env{PATH}, although Posix
17644 allows @command{exec} to use the built-in instead of the executable.
17645 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
17647 @example
17648 $ @kbd{bash -c 'pwd --version' | head -n1}
17649 bash: line 0: pwd: --: invalid option
17650 pwd: usage: pwd [-LP]
17651 $ @kbd{bash -c 'exec pwd --version' | head -n1}
17652 pwd (GNU coreutils) 6.10
17653 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
17654 pdksh: pwd: --: unknown option
17655 @end example
17657 When it is desired to avoid a regular shell built-in, the workaround is
17658 to use some other forwarding command, such as @command{env} or
17659 @command{nice}, that will ensure a path search:
17661 @example
17662 $ @kbd{pdksh -c 'exec true --version' | head -n1}
17663 $ @kbd{pdksh -c 'nice true --version' | head -n1}
17664 true (GNU coreutils) 6.10
17665 $ @kbd{pdksh -c 'env true --version' | head -n1}
17666 true (GNU coreutils) 6.10
17667 @end example
17669 @item @command{exit}
17670 @c -----------------
17671 @prindex @command{exit}
17672 The default value of @command{exit} is supposed to be @code{$?};
17673 unfortunately, some shells, such as the DJGPP port of Bash 2.04, just
17674 perform @samp{exit 0}.
17676 @example
17677 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
17678 fail
17679 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
17680 fail
17681 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
17682 bash-2.04$
17683 @end example
17685 Using @samp{exit $?} restores the expected behavior.
17687 Some shell scripts, such as those generated by @command{autoconf}, use a
17688 trap to clean up before exiting.  If the last shell command exited with
17689 nonzero status, the trap also exits with nonzero status so that the
17690 invoker can tell that an error occurred.
17692 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
17693 trap ignores the @code{exit} command's argument.  In these shells, a trap
17694 cannot determine whether it was invoked by plain @code{exit} or by
17695 @code{exit 1}.  Instead of calling @code{exit} directly, use the
17696 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
17699 @anchor{export}
17700 @item @command{export}
17701 @c -------------------
17702 @prindex @command{export}
17703 The builtin @command{export} dubs a shell variable @dfn{environment
17704 variable}.  Each update of exported variables corresponds to an update
17705 of the environment variables.  Conversely, each environment variable
17706 received by the shell when it is launched should be imported as a shell
17707 variable marked as exported.
17709 Alas, many shells, such as Solaris @command{/bin/sh},
17710 IRIX 6.3, IRIX 5.2,
17711 AIX 4.1.5, and Digital Unix 4.0, forget to
17712 @command{export} the environment variables they receive.  As a result,
17713 two variables coexist: the environment variable and the shell
17714 variable.  The following code demonstrates this failure:
17716 @example
17717 #!/bin/sh
17718 echo $FOO
17719 FOO=bar
17720 echo $FOO
17721 exec /bin/sh $0
17722 @end example
17724 @noindent
17725 when run with @samp{FOO=foo} in the environment, these shells print
17726 alternately @samp{foo} and @samp{bar}, although they should print only
17727 @samp{foo} and then a sequence of @samp{bar}s.
17729 Therefore you should @command{export} again each environment variable
17730 that you update; the export can occur before or after the assignment.
17732 Posix is not clear on whether the @command{export} of an undefined
17733 variable causes the variable to be defined with the value of an empty
17734 string, or merely marks any future definition of a variable by that name
17735 for export.  Various shells behave differently in this regard:
17737 @example
17738 $ @kbd{sh -c 'export foo; env | grep foo'}
17739 $ @kbd{ash -c 'export foo; env | grep foo'}
17740 foo=
17741 @end example
17743 Posix requires @command{export} to honor assignments made as arguments,
17744 but older shells do not support this, including @command{/bin/sh} in
17745 Solaris 10.  Portable scripts should separate assignments and exports
17746 into different statements.
17748 @example
17749 $ @kbd{bash -c 'export foo=bar; echo $foo'}
17751 $ @kbd{/bin/sh -c 'export foo=bar; echo $foo'}
17752 /bin/sh: foo=bar: is not an identifier
17753 $ @kbd{/bin/sh -c 'export foo; foo=bar; echo $foo'}
17755 @end example
17757 Posix requires @command{export} to work with any arbitrary value for the
17758 contents of the variable being exported, as long as the total size of
17759 the environment combined with arguments doesn't exceed @code{ARG_MAX}
17760 when executing a child process.  However, some shells have extensions
17761 that involve interpreting some environment values specially, regardless
17762 of the variable name.  We currently know of one case: all versions of
17763 Bash released prior to 27 September 2014 intepret an environment
17764 variable with an initial content substring of @code{() @{} as an
17765 exported function definition (this is the ``Shellshock'' remote
17766 execution bug, CVE-2014-6271 and friends, where it was possible to
17767 eploit the function parser to cause remote code execution on child bash
17768 startup; newer versions of Bash use special environment variable
17769 @emph{names} instead of values to implement the same feature).
17771 There may be entries inherited into the environment that are not valid
17772 as shell variable names; Posix states that processes should be tolerant
17773 of these names.  Some shells such as @command{dash} do this by removing
17774 those names from the environment at startup, while others such as
17775 @command{bash} hide the entry from shell access but still pass it on to
17776 child processes.  While you can set such names using @command{env} for a
17777 direct child process, you cannot rely on them being preserved through an
17778 intermediate pass through the shell.
17780 @item @command{false}
17781 @c ------------------
17782 @prindex @command{false}
17783 Don't expect @command{false} to exit with status 1: in native
17784 Solaris @file{/bin/false} exits with status 255.
17787 @item @command{for}
17788 @c ----------------
17789 @prindex @command{for}
17790 To loop over positional arguments, use:
17792 @example
17793 for arg
17795   echo "$arg"
17796 done
17797 @end example
17799 @noindent
17800 You may @emph{not} leave the @code{do} on the same line as @code{for},
17801 since some shells improperly grok:
17803 @example
17804 for arg; do
17805   echo "$arg"
17806 done
17807 @end example
17809 If you want to explicitly refer to the positional arguments, given the
17810 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
17812 @example
17813 for arg in $@{1+"$@@"@}; do
17814   echo "$arg"
17815 done
17816 @end example
17818 @noindent
17819 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
17820 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
17821 item @samp{$@@}, for more.
17823 Posix requires support for a @command{for} loop with no list after
17824 @code{in}.  However, Solaris @command{/bin/sh} treats that as a syntax
17825 error.  It is possible to work around this by providing any shell word
17826 that expands to nothing, or by ignoring an obvious sentinel.
17828 @example
17829 $ @kbd{/bin/sh -c 'for a in $empty; do echo hi; done'}
17830 $ @kbd{/bin/sh -c 'for a in ; do echo hi; done'}
17831 /bin/sh: syntax error at line 1: `;' unexpected
17832 @end example
17834 This syntax problem is most frequently encountered in code that goes
17835 through several layers of expansion, such as an m4 macro or makefile
17836 variable used as a list body, where the first layer of expansion (m4 or
17837 make) can end up expanding to nothing in the version handed to the
17838 shell.  In the makefile context, one common workaround is to use a shell
17839 variable rather than a make variable as the source of the list.
17841 @example
17842 $ @kbd{cat Makefile}
17843 list =
17844 bad:
17845         @@for arg in $(list); do echo $$arg; done
17846 good:
17847         @@list='$(list)'; for arg in $$list; do echo $$arg; done
17848 $ @kbd{make bad 2&>1 | head -n1}
17849 sh: syntax error at line 1: `;' unexpected
17850 $ @kbd{make bad list='a b'}
17853 $ @kbd{make good}
17854 $ @kbd{make good list='a b'}
17857 @end example
17859 In Solaris @command{/bin/sh}, when the list of arguments of a
17860 @command{for} loop starts with @emph{unquoted} tokens looking like
17861 variable assignments, the loop is not executed on those tokens:
17863 @example
17864 $ @kbd{/bin/sh -c 'for v in a=b c=d x e=f; do echo $v; done'}
17867 @end example
17869 @noindent
17870 Thankfully, quoting the assignment-like tokens, or starting the list
17871 with other tokens (including unquoted variable expansion that results in
17872 an assignment-like result), avoids the problem, so it is easy to work
17873 around:
17875 @example
17876 $ @kbd{/bin/sh -c 'for v in "a=b"; do echo $v; done'}
17878 $ @kbd{/bin/sh -c 'x=a=b; for v in $x c=d; do echo $v; done'}
17881 @end example
17883 @anchor{if}
17884 @item @command{if}
17885 @c ---------------
17886 @prindex @command{if}
17887 Using @samp{!} is not portable.  Instead of:
17889 @example
17890 if ! cmp -s file file.new; then
17891   mv file.new file
17893 @end example
17895 @noindent
17896 use:
17898 @example
17899 if cmp -s file file.new; then :; else
17900   mv file.new file
17902 @end example
17904 @noindent
17905 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
17906 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
17907 of conditionals:
17909 @example
17910 AS_IF([cmp -s file file.new], [], [mv file.new file])
17911 @end example
17913 This is especially useful in other M4 macros, where the @dfn{then} and
17914 @dfn{else} branches might be macro arguments.
17916 Some very old shells did not reset the exit status from an @command{if}
17917 with no @command{else}:
17919 @example
17920 $ @kbd{if (exit 42); then true; fi; echo $?}
17922 @end example
17924 @noindent
17925 whereas a proper shell should have printed @samp{0}.  But this is no
17926 longer a portability problem; any shell that supports functions gets it
17927 correct.  However, it explains why some makefiles have lengthy
17928 constructs:
17930 @example
17931 if test -f "$file"; then
17932   install "$file" "$dest"
17933 else
17934   :
17936 @end example
17939 @item @command{printf}
17940 @c ------------------
17941 @prindex @command{printf}
17942 A format string starting with a @samp{-} can cause problems.
17943 Bash interprets it as an option and
17944 gives an error.  And @samp{--} to mark the end of options is not good
17945 in the NetBSD Almquist shell (e.g., 0.4.6) which takes that
17946 literally as the format string.  Putting the @samp{-} in a @samp{%c}
17947 or @samp{%s} is probably easiest:
17949 @example
17950 printf %s -foo
17951 @end example
17953 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
17955 @example
17956 $ @kbd{printf '\045'}
17957 bash: printf: `%': missing format character
17958 @end example
17960 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
17961 example, @file{/usr/bin/printf} is buggy, so when using
17962 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
17963 core.
17965 Since @command{printf} is not always a shell builtin, there is a
17966 potential speed penalty for using @code{printf '%s\n'} as a replacement
17967 for an @command{echo} that does not interpret @samp{\} or leading
17968 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
17969 -r --} for this role instead.
17971 @xref{echo, , Limitations of Shell Builtins}, for a discussion of
17972 portable alternatives to both @command{printf} and @command{echo}.
17975 @item @command{pwd}
17976 @c ----------------
17977 @prindex @command{pwd}
17978 With modern shells, plain @command{pwd} outputs a ``logical''
17979 directory name, some of whose components may be symbolic links.  These
17980 directory names are in contrast to ``physical'' directory names, whose
17981 components are all directories.
17983 Posix 1003.1-2001 requires that @command{pwd} must support
17984 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
17985 with @option{-L} being the default.  However, traditional shells do
17986 not support these options, and their @command{pwd} command has the
17987 @option{-P} behavior.
17989 Portable scripts should assume neither option is supported, and should
17990 assume neither behavior is the default.  Also, on many hosts
17991 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
17992 does not require this behavior and portable scripts should not rely on
17995 Typically it's best to use plain @command{pwd}.  On modern hosts this
17996 outputs logical directory names, which have the following advantages:
17998 @itemize @bullet
17999 @item
18000 Logical names are what the user specified.
18001 @item
18002 Physical names may not be portable from one installation
18003 host to another due to network file system gymnastics.
18004 @item
18005 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
18006 some parent directory, but plain @command{pwd} cannot fail for this
18007 reason.
18008 @end itemize
18010 Also please see the discussion of the @command{cd} command.
18013 @item @command{read}
18014 @c -----------------
18015 @prindex @command{read}
18016 No options are portable, not even support @option{-r} (Solaris
18017 @command{/bin/sh} for example).  Tru64/OSF 5.1 @command{sh} treats
18018 @command{read} as a special built-in, so it may exit if input is
18019 redirected from a non-existent or unreadable file.
18022 @anchor{set}
18023 @item @command{set}
18024 @c ----------------
18025 @prindex @command{set}
18026 With the FreeBSD 6.0 shell, the @command{set} command (without
18027 any options) does not sort its output.
18029 The @command{set} builtin faces the usual problem with arguments
18030 starting with a
18031 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
18032 the end of the options (any argument after @option{--} is a parameter,
18033 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
18034 10 @command{/bin/sh}) simply stop option
18035 processing as soon as a non-option argument is found.  Therefore, use
18036 @samp{dummy} or simply @samp{x} to end the option processing, and use
18037 @command{shift} to pop it out:
18039 @example
18040 set x $my_list; shift
18041 @end example
18043 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
18044 longer requires support for this command, and in traditional shells
18045 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
18046 makes scripts harder to debug.
18048 Some nonstandard shells do not recognize more than one option
18049 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
18050 better to combine them:
18052 @example
18053 set -ex
18054 @end example
18056 @cindex @command{set -e}
18057 The option @option{-e} has historically been underspecified, with enough
18058 ambiguities to cause numerous differences across various shell
18059 implementations; see for example
18060 @uref{http://www.in-ulm.de/@/~mascheck/@/various/@/set-e/, this overview},
18061 or @uref{http://www.austingroupbugs.net/@/view.php?id=52, this link},
18062 documenting a change to Posix 2008 to match @command{ksh88} behavior.
18063 Note that mixing @code{set -e} and shell functions is asking for surprises:
18065 @example
18066 set -e
18067 doit()
18069   rm file
18070   echo one
18072 doit || echo two
18073 @end example
18075 @noindent
18076 According to the recommendation, @samp{one} should always be output
18077 regardless of whether the @command{rm} failed, because it occurs within
18078 the body of the shell function @samp{doit} invoked on the left side of
18079 @samp{||}, where the effects of @samp{set -e} are not enforced.
18080 Likewise, @samp{two} should never be printed, since the failure of
18081 @command{rm} does not abort the function, such that the status of
18082 @samp{doit} is 0.
18084 The BSD shell has had several problems with the @option{-e}
18085 option.  Older versions of the BSD
18086 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
18087 @samp{case} when @option{-e} was in effect, causing the shell to exit
18088 unexpectedly in some cases.  This was particularly a problem with
18089 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
18090 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
18091 wrapper works around the bug (@pxref{Failure in Make Rules}).
18093 Even relatively-recent versions of the BSD shell (e.g., OpenBSD 3.4)
18094 wrongly exit with @option{-e} if the last command within a compound
18095 statement fails and is guarded by an @samp{&&} only.  For example:
18097 @example
18098 #! /bin/sh
18099 set -e
18100 foo=''
18101 test -n "$foo" && exit 1
18102 echo one
18103 if :; then
18104   test -n "$foo" && exit 1
18105   echo two
18106   test -n "$foo" && exit 1
18108 echo three
18109 @end example
18111 @noindent
18112 does not print @samp{three}.  One workaround is to change the last
18113 instance of @samp{test -n "$foo" && exit 1} to be @samp{if test -n
18114 "$foo"; then exit 1; fi} instead.  Another possibility is to warn BSD
18115 users not to use @samp{sh -e}.
18117 When @samp{set -e} is in effect, a failed command substitution in
18118 Solaris @command{/bin/sh} cannot be ignored, even with @samp{||}.
18120 @example
18121 $ @kbd{/bin/sh -c 'set -e; foo=`false` || echo foo; echo bar'}
18122 $ @kbd{bash -c 'set -e; foo=`false` || echo foo; echo bar'}
18125 @end example
18127 @noindent
18128 Moreover, a command substitution, successful or not, causes this shell to
18129 exit from a failing outer command even in presence of an @samp{&&} list:
18131 @example
18132 $ @kbd{bash -c 'set -e; false `true` && echo notreached; echo ok'}
18134 $ @kbd{sh -c 'set -e; false `true` && echo notreached; echo ok'}
18136 @end example
18138 Portable scripts should not use @samp{set -e} if @command{trap} is used
18139 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
18140 sometimes enters the trap handler with the exit status of the command
18141 prior to the one that triggered the errexit handler:
18143 @example
18144 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
18146 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
18148 @end example
18150 @noindent
18151 Thus, when writing a script in M4sh, rather than trying to rely on
18152 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
18153 statement where it is desirable to abort on failure.
18155 @cindex @command{set -b}
18156 @cindex @command{set -m}
18157 Job control is not provided by all shells, so the use of @samp{set -m}
18158 or @samp{set -b} must be done with care.  When using @command{zsh} in
18159 native mode, asynchronous notification (@samp{set -b}) is enabled by
18160 default, and using @samp{emulate sh} to switch to Posix mode does not
18161 clear this setting (although asynchronous notification has no impact
18162 unless job monitoring is also enabled).  Also, @command{zsh} 4.3.10 and
18163 earlier have a bug where job control can be manipulated in interactive
18164 shells, but not in subshells or scripts.  Furthermore, some shells, like
18165 @command{pdksh}, fail to treat subshells as interactive, even though the
18166 parent shell was.
18168 @example
18169 $ @kbd{echo $ZSH_VERSION}
18170 4.3.10
18171 $ @kbd{set -m; echo $?}
18173 $ @kbd{zsh -c 'set -m; echo $?'}
18174 set: can't change option: -m
18175 $ @kbd{(set -m); echo $?}
18176 set: can't change option: -m
18178 $ @kbd{pdksh -ci 'echo $-; (echo $-)'}
18181 @end example
18183 @cindex @command{set -n}
18184 Use of @command{set -n} (typically via @command{sh -n script}) to
18185 validate a script is not foolproof.  Modern @command{ksh93} tries to be
18186 helpful by informing you about better syntax, but switching the script
18187 to use the suggested syntax in order to silence the warnings would
18188 render the script no longer portable to older shells:
18190 @example
18191 $ @kbd{ksh -nc '``'}
18192 ksh: warning: line 1: `...` obsolete, use $(...)
18194 @end example
18196 Furthermore, on ancient hosts, such as SunOS 4, @command{sh -n} could go
18197 into an infinite loop; even with that bug fixed, Solaris 8
18198 @command{/bin/sh} takes extremely long to parse large scripts.  Autoconf
18199 itself uses @command{sh -n} within its testsuite to check that correct
18200 scripts were generated, but only after first probing for other shell
18201 features (such as @code{test $@{BASH_VERSION+y@}}) that indicate
18202 a reasonably fast and working implementation.
18204 @item @command{shift}
18205 @c ------------------
18206 @prindex @command{shift}
18207 Not only is @command{shift}ing a bad idea when there is nothing left to
18208 shift, but in addition it is not portable: the shell of MIPS
18209 RISC/OS 4.52 refuses to do it.
18211 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
18212 it is also absent in many pre-Posix shells.
18215 @item @command{source}
18216 @c -------------------
18217 @prindex @command{source}
18218 This command is not portable, as Posix does not require it; use
18219 @command{.} instead.
18222 @item @command{test}
18223 @c -----------------
18224 @prindex @command{test}
18225 The @code{test} program is the way to perform many file and string
18226 tests.  It is often invoked by the alternate name @samp{[}, but using
18227 that name in Autoconf code is asking for trouble since it is an M4 quote
18228 character.
18230 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
18231 present in all implementations, and have been marked obsolete by Posix
18232 2008.  This is because there are inherent ambiguities in using them.
18233 For example, @samp{test "$1" -a "$2"} looks like a binary operator to
18234 check whether two strings are both non-empty, but if @samp{$1} is the
18235 literal @samp{!}, then some implementations of @command{test} treat it
18236 as a negation of the unary operator @option{-a}.
18238 Thus, portable uses of @command{test} should never have more than four
18239 arguments, and scripts should use shell constructs like @samp{&&} and
18240 @samp{||} instead.  If you combine @samp{&&} and @samp{||} in the same
18241 statement, keep in mind that they have equal precedence, so it is often
18242 better to parenthesize even when this is redundant.  For example:
18244 @smallexample
18245 # Not portable:
18246 test "X$a" = "X$b" -a \
18247   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
18249 # Portable:
18250 test "X$a" = "X$b" &&
18251   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
18252 @end smallexample
18254 @command{test} does not process options like most other commands do; for
18255 example, it does not recognize the @option{--} argument as marking the
18256 end of options.
18258 It is safe to use @samp{!} as a @command{test} operator.  For example,
18259 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
18260 -d foo; @dots{}} is not.
18263 @item @command{test} (files)
18264 @c -------------------------
18265 To enable @command{configure} scripts to support cross-compilation, they
18266 shouldn't do anything that tests features of the build system instead of
18267 the host system.  But occasionally you may find it necessary to check
18268 whether some arbitrary file exists.  To do so, use @samp{test -f},
18269 @samp{test -r}, or @samp{test -x}.  Do not use @samp{test -e}, because
18270 Solaris 10 @command{/bin/sh}
18271 lacks it.  To test for symbolic links on systems that have them, use
18272 @samp{test -h} rather than @samp{test -L}; either form conforms to
18273 Posix 1003.1-2001, but older shells like Solaris 8
18274 @code{/bin/sh} support only @option{-h}.
18276 For historical reasons, Posix reluctantly allows implementations of
18277 @samp{test -x} that will succeed for the root user, even if no execute
18278 permissions are present.  Furthermore, shells do not all agree on
18279 whether Access Control Lists should affect @samp{test -r}, @samp{test
18280 -w}, and @samp{test -x}; some shells base test results strictly on the
18281 current user id compared to file owner and mode, as if by
18282 @code{stat(2)}; while other shells base test results on whether the
18283 current user has the given right, even if that right is only granted by
18284 an ACL, as if by @code{faccessat(2)}.  Furthermore, there is a classic
18285 time of check to time of use race between any use of @command{test}
18286 followed by operating on the just-checked file.  Therefore, it is a good
18287 idea to write scripts that actually attempt an operation, and are
18288 prepared for the resulting failure if permission is denied, rather than
18289 trying to avoid an operation based solely on whether @command{test}
18290 guessed that it might not be permitted.
18292 @item @command{test} (strings)
18293 @c ---------------------------
18294 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
18295 not null, but this usage is not portable to traditional platforms like
18296 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
18297 @samp{-n}.  However, it @emph{is} portable to test if a variable is set
18298 to a non-empty value, by using @samp{test $@{var+y@}}, since all known
18299 implementations properly distinguish between no arguments and a
18300 known-safe string of @samp{y}.
18302 Posix also says that @samp{test ! "@var{string}"},
18303 @samp{test -n "@var{string}"} and
18304 @samp{test -z "@var{string}"} work with any string, but many
18305 shells (such as Solaris, AIX 3.2, UNICOS 10.0.0.6,
18306 Digital Unix 4, etc.)@: get confused if
18307 @var{string} looks like an operator:
18309 @example
18310 $ @kbd{test -n =}
18311 test: argument expected
18312 $ @kbd{test ! -n}
18313 test: argument expected
18314 $ @kbd{test -z ")"; echo $?}
18316 @end example
18318 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
18319 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
18320 strings, but in practice this is not true for troublesome strings that
18321 look like operators or parentheses, or that begin with @samp{-}.
18323 It is best to protect such strings with a leading @samp{X}, e.g.,
18324 @samp{test "X@var{string}" != X} rather than @samp{test -n
18325 "@var{string}"} or @samp{test ! "@var{string}"}.
18327 It is common to find variations of the following idiom:
18329 @example
18330 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
18331   @var{action}
18332 @end example
18334 @noindent
18335 to take an action when a token matches a given pattern.  Such constructs
18336 should be avoided by using:
18338 @example
18339 case $ac_feature in
18340   *[!-a-zA-Z0-9_]*) @var{action};;
18341 esac
18342 @end example
18344 If the pattern is a complicated regular expression that cannot be
18345 expressed as a shell pattern, use something like this instead:
18347 @example
18348 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
18349   @var{action}
18350 @end example
18352 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
18353 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
18354 @samp{@var{foo}} contains backslashes.
18357 @anchor{trap}
18358 @item @command{trap}
18359 @c -----------------
18360 @prindex @command{trap}
18361 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
18362 trap 0, i.e., have the @command{trap} run when the script ends (either via an
18363 explicit @command{exit}, or the end of the script).  The trap for 0 should be
18364 installed outside of a shell function, or AIX 5.3 @command{/bin/sh}
18365 will invoke the trap at the end of this function.
18367 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
18368 specified signals to their default values, but many common shells (e.g.,
18369 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
18370 ``command'' named @command{-} when the specified conditions arise.
18371 Posix 2008 also added a requirement to support @samp{trap 1 2 13 15} to
18372 reset traps, as this is supported by a larger set of shells, but there
18373 are still shells like @command{dash} that mistakenly try to execute
18374 @command{1} instead of resetting the traps.  Therefore, there is no
18375 portable workaround, except for @samp{trap - 0}, for which
18376 @samp{trap '' 0} is a portable substitute.
18378 Although Posix is not absolutely clear on this point, it is widely
18379 admitted that when entering the trap @samp{$?} should be set to the exit
18380 status of the last command run before the trap.  The ambiguity can be
18381 summarized as: ``when the trap is launched by an @command{exit}, what is
18382 the @emph{last} command run: that before @command{exit}, or
18383 @command{exit} itself?''
18385 Bash considers @command{exit} to be the last command, while Zsh and
18386 Solaris @command{/bin/sh} consider that when the trap is run it is
18387 @emph{still} in the @command{exit}, hence it is the previous exit status
18388 that the trap receives:
18390 @example
18391 $ @kbd{cat trap.sh}
18392 trap 'echo $?' 0
18393 (exit 42); exit 0
18394 $ @kbd{zsh trap.sh}
18396 $ @kbd{bash trap.sh}
18398 @end example
18400 The portable solution is then simple: when you want to @samp{exit 42},
18401 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
18402 set the exit status to 42 for Zsh, and the second to trigger the trap
18403 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
18404 @code{AS_EXIT}.
18406 The shell in FreeBSD 4.0 has the following bug: @samp{$?} is
18407 reset to 0 by empty lines if the code is inside @command{trap}.
18409 @example
18410 $ @kbd{trap 'false}
18412 echo $?' 0
18413 $ @kbd{exit}
18415 @end example
18417 @noindent
18418 Fortunately, this bug only affects @command{trap}.
18420 Several shells fail to execute an exit trap that is defined inside a
18421 subshell, when the last command of that subshell is not a builtin.  A
18422 workaround is to use @samp{exit $?} as the shell builtin.
18424 @example
18425 $ @kbd{bash -c '(trap "echo hi" 0; /bin/true)'}
18427 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true)'}
18428 $ @kbd{/bin/sh -c '(trap "echo hi" 0; /bin/true; exit $?)'}
18430 @end example
18432 @noindent
18433 Likewise, older implementations of @command{bash} failed to preserve
18434 @samp{$?} across an exit trap consisting of a single cleanup command.
18436 @example
18437 $ @kbd{bash -c 'trap "/bin/true" 0; exit 2'; echo $?}
18439 $ @kbd{bash-2.05b -c 'trap "/bin/true" 0; exit 2'; echo $?}
18441 $ @kbd{bash-2.05b -c 'trap ":; /bin/true" 0; exit 2'; echo $?}
18443 @end example
18445 Be aware that a trap can be called from any number of places in your
18446 script, and therefore the trap handler should not make assumptions about
18447 shell state.  For some examples, if your script temporarily modifies
18448 @env{IFS}, then the trap should include an initialization back to its
18449 typical value of space-tab-newline (autoconf does this for generated
18450 @file{configure} files).  Likewise, if your script changes the current
18451 working directory at some point after the trap is installed, then your
18452 trap cannot assume which directory it is in, and should begin by
18453 changing directories to an absolute path if that is important to the
18454 cleanup efforts (autotest does this for generated @file{testsuite}
18455 files).
18457 @item @command{true}
18458 @c -----------------
18459 @prindex @command{true}
18460 @c Info cannot handle `:' in index entries.
18461 @c @prindex @command{:}
18462 Don't worry: as far as we know @command{true} is portable.
18463 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
18464 portable shell community tends to prefer using @command{:}.  This has a
18465 funny side effect: when asked whether @command{false} is more portable
18466 than @command{true} Alexandre Oliva answered:
18468 @quotation
18469 In a sense, yes, because if it doesn't exist, the shell will produce an
18470 exit status of failure, which is correct for @command{false}, but not
18471 for @command{true}.
18472 @end quotation
18474 Remember that even though @samp{:} ignores its arguments, it still takes
18475 time to compute those arguments.  It is a good idea to use double quotes
18476 around any arguments to @samp{:} to avoid time spent in field splitting
18477 and file name expansion.
18480 @anchor{unset}
18481 @item @command{unset}
18482 @c ------------------
18483 @prindex @command{unset}
18484 In some nonconforming shells (e.g., Solaris 10 @command{/bin/ksh} and
18485 @command{/usr/xpg4/bin/sh}, NetBSD 5.99.43 sh, or Bash 2.05a),
18486 @code{unset FOO} fails when @code{FOO} is not set.  This can interfere
18487 with @code{set -e} operation.  You can use
18489 @smallexample
18490 FOO=; unset FOO
18491 @end smallexample
18493 @noindent
18494 if you are not sure that @code{FOO} is set.
18496 A few ancient shells lack @command{unset} entirely.  For some variables
18497 such as @code{PS1}, you can use a neutralizing value instead:
18499 @smallexample
18500 PS1='$ '
18501 @end smallexample
18503 Usually, shells that do not support @command{unset} need less effort to
18504 make the environment sane, so for example is not a problem if you cannot
18505 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
18506 @code{unset MAIL} and @code{unset MAILPATH} in some cases and dumps core.
18507 So, you should do something like
18509 @smallexample
18510 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
18511 @end smallexample
18513 @noindent
18514 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
18515 @ref{export, , Limitations of Builtins}, for
18516 the case of environment variables.
18518 @item @command{wait}
18519 @c -----------------
18520 @prindex @command{wait}
18521 The exit status of @command{wait} is not always reliable.
18522 @end table
18524 @node Limitations of Usual Tools
18525 @section Limitations of Usual Tools
18526 @cindex Limitations of usual tools
18528 The small set of tools you can expect to find on any machine can still
18529 include some limitations you should be aware of.
18531 @comment Between this list and the list of builtins above, we should
18532 @comment mention all the tools in GNU Coding Standards ``Utilities in
18533 @comment Makefiles''.
18535 @c This table includes things like `@command{expr} (|)', so we can't
18536 @c use @table @command.
18537 @table @asis
18538 @anchor{awk}
18539 @item @command{awk}
18540 @c ----------------
18541 @prindex @command{awk}
18542 Don't leave white space before the opening parenthesis in a user function call.
18543 Posix does not allow this and GNU Awk rejects it:
18545 @example
18546 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18547         BEGIN @{ die () @}'}
18548 gawk: cmd. line:2:         BEGIN @{ die () @}
18549 gawk: cmd. line:2:                      ^ parse error
18550 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
18551         BEGIN @{ die() @}'}
18552 Aaaaarg!
18553 @end example
18555 Posix says that if a program contains only @samp{BEGIN} actions, and
18556 contains no instances of @code{getline}, then the program merely
18557 executes the actions without reading input.  However, traditional Awk
18558 implementations (such as Solaris 10 @command{awk}) read and discard
18559 input in this case.  Portable scripts can redirect input from
18560 @file{/dev/null} to work around the problem.  For example:
18562 @example
18563 awk 'BEGIN @{print "hello world"@}' </dev/null
18564 @end example
18566 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
18567 @samp{$1}) retain their value from the last record read, if no
18568 intervening @samp{getline} occurred.  However, some implementations
18569 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
18570 @samp{awk}) reset these variables.  A workaround is to use an
18571 intermediate variable prior to the @samp{END} block.  For example:
18573 @example
18574 $ @kbd{cat end.awk}
18575 @{ tmp = $1 @}
18576 END @{ print "a", $1, $NF, "b", tmp @}
18577 $ @kbd{echo 1 | awk -f end.awk}
18578 a   b 1
18579 $ @kbd{echo 1 | gawk -f end.awk}
18580 a 1 1 b 1
18581 @end example
18583 If you want your program to be deterministic, don't depend on @code{for}
18584 on arrays:
18586 @example
18587 $ @kbd{cat for.awk}
18588 END @{
18589   arr["foo"] = 1
18590   arr["bar"] = 1
18591   for (i in arr)
18592     print i
18594 $ @kbd{gawk -f for.awk </dev/null}
18597 $ @kbd{nawk -f for.awk </dev/null}
18600 @end example
18602 Some Awk implementations, such as HP-UX 11.0's native one,
18603 mishandle anchors:
18605 @example
18606 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
18607 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
18609 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
18610 xfoo
18611 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
18613 @end example
18615 @noindent
18616 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
18617 or use a simple test to reject such implementations.
18619 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
18620 after @code{%u}:
18622 @example
18623 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
18624 0 0
18625 @end example
18627 AIX version 5.2 has an arbitrary limit of 399 on the
18628 length of regular expressions and literal strings in an Awk program.
18630 Traditional Awk implementations derived from Unix version 7, such as
18631 Solaris @command{/bin/awk}, have many limitations and do not
18632 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
18633 Programs}) finds you an Awk that doesn't have these problems, but if
18634 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
18635 address them.  For more detailed descriptions, see @ref{Language
18636 History, , @command{awk} language history, gawk, GNU Awk User's Guide}.
18638 Traditional Awk does not support multidimensional arrays or user-defined
18639 functions.
18641 Traditional Awk does not support the @option{-v} option.  You can use
18642 assignments after the program instead, e.g., @code{$AWK '@{print v
18643 $1@}' v=x}; however, don't forget that such assignments are not
18644 evaluated until they are encountered (e.g., after any @code{BEGIN}
18645 action).
18647 Traditional Awk does not support the keywords @code{delete} or @code{do}.
18649 Traditional Awk does not support the expressions
18650 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
18651 or @code{@var{a}^=@var{b}}.
18653 Traditional Awk does not support the predefined @code{CONVFMT} or
18654 @code{ENVIRON} variables.
18656 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
18657 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
18658 @code{sqrt}, and @code{substr}.
18660 Traditional Awk @code{getline} is not at all compatible with Posix;
18661 avoid it.
18663 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
18664 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
18666 In code portable to both traditional and modern Awk, @code{FS} must be a
18667 string containing just one ordinary character, and similarly for the
18668 field-separator argument to @code{split}.
18670 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
18671 implementations, like Tru64's, split the input even if you don't refer
18672 to any field in the script, to circumvent this problem, set @samp{FS}
18673 to an unusual character and use @code{split}.
18675 Traditional Awk has a limit of at most 99 bytes in a number formatted by
18676 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
18677 dumps core.
18679 The original version of Awk had a limit of at most 99 bytes per
18680 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
18681 per run of non-special characters in a @code{printf} format, but these
18682 bugs have been fixed on all practical hosts that we know of.
18684 HP-UX 11.00 and IRIX 6.5 Awk require that input files have a line length
18685 of at most 3070 bytes.
18687 @item @command{basename}
18688 @c ---------------------
18689 @prindex @command{basename}
18690 Not all hosts have a working @command{basename}.
18691 You can use @command{expr} instead.
18693 @c AS_BASENAME is to be replaced by a better API.
18694 @ignore
18695 Not all hosts have a working @command{basename}, and you should instead
18696 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
18697 @command{expr} if you need to strip a suffix.  For example:
18699 @example
18700 a=`basename "$aname"`       # This is not portable.
18701 a=`AS_BASENAME(["$aname"])` # This is more portable.
18703 # This is not portable.
18704 c=`basename "$cname" .c`
18706 # This is more portable.
18707 c=`AS_BASENAME(["$cname"])`
18708 case $c in
18709 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
18710 esac
18711 @end example
18712 @end ignore
18715 @item @command{cat}
18716 @c ----------------
18717 @prindex @command{cat}
18718 Don't rely on any option.
18721 @item @command{cc}
18722 @c ---------------
18723 @prindex @command{cc}
18724 The command @samp{cc -c foo.c} traditionally produces an object file
18725 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
18726 with @option{-o} to specify a different object file name, but
18727 Posix does not require this combination and a few compilers
18728 lack support for it.  @xref{C Compiler}, for how GNU Make
18729 tests for this feature with @code{AC_PROG_CC_C_O}.
18731 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
18732 (such as CDS on Reliant Unix) leave a @file{foo.o}.
18734 HP-UX @command{cc} doesn't accept @file{.S} files to preprocess and
18735 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
18736 nothing.
18738 The default executable, produced by @samp{cc foo.c}, can be
18740 @itemize
18741 @item @file{a.out} -- usual Posix convention.
18742 @item @file{b.out} -- i960 compilers (including @command{gcc}).
18743 @item @file{a.exe} -- DJGPP port of @command{gcc}.
18744 @item @file{a_out.exe} -- GNV @command{cc} wrapper for DEC C on OpenVMS.
18745 @item @file{foo.exe} -- various MS-DOS compilers.
18746 @end itemize
18748 The C compiler's traditional name is @command{cc}, but other names like
18749 @command{gcc} are common.  Posix 1003.1-2001 and 1003.1-2008 specify the
18750 name @command{c99}, but older Posix editions specified
18751 @command{c89}, future POSIX standards will likely specify
18752 @command{c11}, and anyway these standard names are rarely used in
18753 practice.  Typically the C compiler is invoked from makefiles that use
18754 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
18755 compiler name.
18757 @item @command{chgrp}
18758 @itemx @command{chown}
18759 @c -------------------
18760 @prindex @command{chgrp}
18761 @prindex @command{chown}
18762 It is not portable to change a file's group to a group that the owner
18763 does not belong to.
18765 @item @command{chmod}
18766 @c ------------------
18767 @prindex @command{chmod}
18768 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
18769 instead, for two reasons.  First, plain @option{-w} does not necessarily
18770 make the file unwritable, since it does not affect mode bits that
18771 correspond to bits in the file mode creation mask.  Second,
18772 Posix says that the @option{-w} might be interpreted as an
18773 implementation-specific option, not as a mode; Posix suggests
18774 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
18775 @samp{--} does not work on some older hosts.
18778 @item @command{cmp}
18779 @c ----------------
18780 @prindex @command{cmp}
18781 @command{cmp} performs a raw data comparison of two files, while
18782 @command{diff} compares two text files.  Therefore, if you might compare
18783 DOS files, even if only checking whether two files are different, use
18784 @command{diff} to avoid spurious differences due to differences of
18785 newline encoding.
18788 @item @command{cp}
18789 @c ---------------
18790 @prindex @command{cp}
18791 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
18792 obsolescent and its behavior on special files is implementation-defined.
18793 Use @option{-R} instead.  On GNU hosts the two options
18794 are equivalent, but on Solaris hosts (for example) @code{cp -r}
18795 reads from pipes instead of replicating them.  AIX 5.3 @code{cp -R} may
18796 corrupt its own memory with some directory hierarchies and error out or
18797 dump core:
18799 @example
18800 @kbd{mkdir -p 12345678/12345678/12345678/12345678}
18801 @kbd{touch 12345678/12345678/x}
18802 @kbd{cp -R 12345678 t}
18803 cp: 0653-440 12345678/12345678/: name too long.
18804 @end example
18806 Some @command{cp} implementations (e.g., BSD/OS 4.2) do not allow
18807 trailing slashes at the end of nonexistent destination directories.  To
18808 avoid this problem, omit the trailing slashes.  For example, use
18809 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
18810 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
18812 The @option{-f} option is portable nowadays.
18814 @cindex timestamp resolution
18815 Traditionally, file timestamps had 1-second resolution, and @samp{cp
18816 -p} copied the timestamps exactly.  However, many modern file systems
18817 have timestamps with 1-nanosecond resolution.  Unfortunately, some older
18818 @samp{cp -p} implementations truncate timestamps when copying files,
18819 which can cause the destination file to appear to be older than the
18820 source.  The exact amount of truncation depends on the resolution of
18821 the system calls that @command{cp} uses.  Traditionally this was
18822 @code{utime}, which has 1-second resolution.  Less-ancient @command{cp}
18823 implementations such as GNU Core Utilities 5.0.91 (2003) use
18824 @code{utimes}, which has 1-microsecond resolution.  Modern
18825 implementations such as GNU Core Utilities 6.12 (2008) can set timestamps to
18826 the full nanosecond resolution, using the modern system calls
18827 @code{futimens} and @code{utimensat} when they are available.  As of
18828 2011, though, many platforms do not yet fully support these new system
18829 calls.
18831 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
18832 ownerships.  But whether it actually does copy ownerships or not is a
18833 system dependent policy decision implemented by the kernel.  If the
18834 kernel allows it then it happens.  If the kernel does not allow it then
18835 it does not happen.  It is not something @command{cp} itself has control
18836 over.
18838 In Unix System V any user can chown files to any other user, and System
18839 V also has a non-sticky @file{/tmp}.  That probably derives from the
18840 heritage of System V in a business environment without hostile users.
18841 BSD changed this
18842 to be a more secure model where only root can @command{chown} files and
18843 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
18844 of BSD in a campus environment.
18846 GNU/Linux and Solaris by default follow BSD, but
18847 can be configured to allow a System V style @command{chown}.  On the
18848 other hand, HP-UX follows System V, but can
18849 be configured to use the modern security model and disallow
18850 @command{chown}.  Since it is an administrator-configurable parameter
18851 you can't use the name of the kernel as an indicator of the behavior.
18855 @item @command{date}
18856 @c -----------------
18857 @prindex @command{date}
18858 Some versions of @command{date} do not recognize special @samp{%} directives,
18859 and unfortunately, instead of complaining, they just pass them through,
18860 and exit with success:
18862 @example
18863 $ @kbd{uname -a}
18864 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
18865 $ @kbd{date "+%s"}
18867 @end example
18870 @item @command{diff}
18871 @c -----------------
18872 @prindex @command{diff}
18873 Option @option{-u} is nonportable.
18875 Some implementations, such as Tru64's, fail when comparing to
18876 @file{/dev/null}.  Use an empty file instead.
18879 @item @command{dirname}
18880 @c --------------------
18881 @prindex @command{dirname}
18882 Not all hosts have a working @command{dirname}, and you should instead
18883 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
18885 @example
18886 dir=`dirname "$file"`       # This is not portable.
18887 dir=`AS_DIRNAME(["$file"])` # This is more portable.
18888 @end example
18891 @item @command{egrep}
18892 @c ------------------
18893 @prindex @command{egrep}
18894 Posix 1003.1-2001 no longer requires @command{egrep},
18895 but many hosts do not yet support the Posix
18896 replacement @code{grep -E}.  Also, some traditional implementations do
18897 not work on long input lines.  To work around these problems, invoke
18898 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
18900 Portable extended regular expressions should use @samp{\} only to escape
18901 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
18902 is not portable, even though it typically matches @samp{@}}.
18904 The empty alternative is not portable.  Use @samp{?} instead.  For
18905 instance with Digital Unix v5.0:
18907 @example
18908 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
18909 |foo
18910 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
18911 bar|
18912 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
18914 |bar
18915 @end example
18917 @command{$EGREP} also suffers the limitations of @command{grep}
18918 (@pxref{grep, , Limitations of Usual Tools}).
18920 @item @command{expr}
18921 @c -----------------
18922 @prindex @command{expr}
18923 Not all implementations obey the Posix rule that @samp{--} separates
18924 options from arguments; likewise, not all implementations provide the
18925 extension to Posix that the first argument can be treated as part of a
18926 valid expression rather than an invalid option if it begins with
18927 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
18928 @samp{$var} might be a negative number, to keep @command{expr} from
18929 interpreting it as an option.
18931 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
18932 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
18933 misinterpreting @var{word}.
18935 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
18937 @item @command{expr} (@samp{|})
18938 @prindex @command{expr} (@samp{|})
18939 You can use @samp{|}.  Although Posix does require that @samp{expr
18940 ''} return the empty string, it does not specify the result when you
18941 @samp{|} together the empty string (or zero) with the empty string.  For
18942 example:
18944 @example
18945 expr '' \| ''
18946 @end example
18948 Posix 1003.2-1992 returns the empty string
18949 for this case, but traditional Unix returns @samp{0} (Solaris is
18950 one such example).  In Posix 1003.1-2001, the specification was
18951 changed to match traditional Unix's behavior (which is
18952 bizarre, but it's too late to fix this).  Please note that the same
18953 problem does arise when the empty string results from a computation,
18954 as in:
18956 @example
18957 expr bar : foo \| foo : bar
18958 @end example
18960 @noindent
18961 Avoid this portability problem by avoiding the empty string.
18964 @item @command{expr} (@samp{:})
18965 @c ----------------------------
18966 @prindex @command{expr}
18967 Portable @command{expr} regular expressions should use @samp{\} to
18968 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
18969 For example, alternation, @samp{\|}, is common but Posix does not
18970 require its support, so it should be avoided in portable scripts.
18971 Similarly, @samp{\+} and @samp{\?} should be avoided.
18973 Portable @command{expr} regular expressions should not begin with
18974 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
18975 not needed anyway.
18977 On the other hand, the behavior of the @samp{$} anchor is not portable
18978 on multi-line strings.  Posix is ambiguous whether the anchor applies to
18979 each line, as was done in older versions of the GNU Core Utilities, or
18980 whether it applies only to the end of the overall string, as in
18981 Coreutils 6.0 and most other implementations.
18983 @example
18984 $ @kbd{baz='foo}
18985 > @kbd{bar'}
18986 $ @kbd{expr "X$baz" : 'X\(foo\)$'}
18988 $ @kbd{expr-5.97 "X$baz" : 'X\(foo\)$'}
18990 @end example
18992 The Posix standard is ambiguous as to whether
18993 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
18994 In practice, it outputs the empty string on most platforms, but portable
18995 scripts should not assume this.  For instance, the QNX 4.25 native
18996 @command{expr} returns @samp{0}.
18998 One might think that a way to get a uniform behavior would be to use
18999 the empty string as a default value:
19001 @example
19002 expr a : '\(b\)' \| ''
19003 @end example
19005 @noindent
19006 Unfortunately this behaves exactly as the original expression; see the
19007 @command{expr} (@samp{|}) entry for more information.
19009 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
19010 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
19011 @command{expr} to fail if the matched substring is longer than 120
19012 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
19013 @command{expr} fails.  Nowadays this is of practical importance only for
19014 the rare installer who mistakenly puts @file{/usr/ucb} before
19015 @file{/usr/bin} in @env{PATH}.
19017 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
19018 some cases.  For example, the command
19019 @example
19020 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
19021 @end example
19023 @noindent
19024 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
19025 This particular case can be worked around by substituting @samp{[^--]}
19026 for @samp{[^-]}.
19028 Don't leave, there is some more!
19030 The QNX 4.25 @command{expr}, in addition of preferring @samp{0} to
19031 the empty string, has a funny behavior in its exit status: it's always 1
19032 when parentheses are used!
19034 @example
19035 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
19036 0: 1
19037 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
19038 1: 0
19040 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
19041 1: a
19042 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
19043 1: 0
19044 @end example
19046 @noindent
19047 In practice this can be a big problem if you are ready to catch failures
19048 of @command{expr} programs with some other method (such as using
19049 @command{sed}), since you may get twice the result.  For instance
19051 @example
19052 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
19053 @end example
19055 @noindent
19056 outputs @samp{a} on most hosts, but @samp{aa} on QNX 4.25.  A
19057 simple workaround consists of testing @command{expr} and using a variable
19058 set to @command{expr} or to @command{false} according to the result.
19060 Tru64 @command{expr} incorrectly treats the result as a number, if it
19061 can be interpreted that way:
19063 @example
19064 $ @kbd{expr 00001 : '.*\(...\)'}
19066 @end example
19068 On HP-UX 11, @command{expr} only supports a single
19069 sub-expression.
19071 @example
19072 $ @kbd{expr 'Xfoo' : 'X\(f\(oo\)*\)$'}
19073 expr: More than one '\(' was used.
19074 @end example
19077 @item @command{fgrep}
19078 @c ------------------
19079 @prindex @command{fgrep}
19080 Posix 1003.1-2001 no longer requires @command{fgrep},
19081 but many hosts do not yet support the Posix
19082 replacement @code{grep -F}.  Also, some traditional implementations do
19083 not work on long input lines.  To work around these problems, invoke
19084 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
19086 Tru64/OSF 5.1 @command{fgrep} does not match an empty pattern.
19089 @item @command{find}
19090 @c -----------------
19091 @prindex @command{find}
19092 The option @option{-maxdepth} seems to be GNU specific.
19093 Tru64 v5.1, NetBSD 1.5 and Solaris @command{find}
19094 commands do not understand it.
19096 The replacement of @samp{@{@}} is guaranteed only if the argument is
19097 exactly @emph{@{@}}, not if it's only a part of an argument.  For
19098 instance on DU, and HP-UX 10.20 and HP-UX 11:
19100 @example
19101 $ @kbd{touch foo}
19102 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
19103 @{@}-@{@}
19104 @end example
19106 @noindent
19107 while GNU @command{find} reports @samp{./foo-./foo}.
19110 @anchor{grep}
19111 @item @command{grep}
19112 @c -----------------
19113 @prindex @command{grep}
19114 Portable scripts can rely on the @command{grep} options @option{-c},
19115 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
19116 options.  For example, don't use @option{-w}, as Posix does not require
19117 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
19118 portable scripts should not combine @option{-c} with @option{-l},
19119 as Posix does not allow this.
19121 Some of the options required by Posix are not portable in practice.
19122 Don't use @samp{grep -q} to suppress output, because many @command{grep}
19123 implementations (e.g., Solaris) do not support @option{-q}.
19124 Don't use @samp{grep -s} to suppress output either, because Posix
19125 says @option{-s} does not suppress output, only some error messages;
19126 also, the @option{-s} option of traditional @command{grep} behaved
19127 like @option{-q} does in most modern implementations.  Instead,
19128 redirect the standard output and standard error (in case the file
19129 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
19130 status of @code{grep} to determine whether it found a match.
19132 The QNX4 implementation fails to count lines with @code{grep -c '$'},
19133 but works with @code{grep -c '^'}.  Other alternatives for counting
19134 lines are to use @code{sed -n '$='} or @code{wc -l}.
19136 Some traditional @command{grep} implementations do not work on long
19137 input lines.  On AIX the default @code{grep} silently truncates long
19138 lines on the input before matching.
19140 Also, many implementations do not support multiple regexps
19141 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
19142 or honor only the last pattern (e.g., IRIX 6.5 and NeXT).  To
19143 work around these problems, invoke @code{AC_PROG_GREP} and then use
19144 @code{$GREP}.
19146 Another possible workaround for the multiple @option{-e} problem is to
19147 separate the patterns by newlines, for example:
19149 @example
19150 grep 'foo
19151 bar' in.txt
19152 @end example
19154 @noindent
19155 except that this fails with traditional @command{grep}
19156 implementations and with OpenBSD 3.8 @command{grep}.
19158 Traditional @command{grep} implementations (e.g., Solaris) do not
19159 support the @option{-E} or @option{-F} options.  To work around these
19160 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
19161 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
19162 willing to require support for Posix @command{grep}, your script should
19163 not use both @option{-E} and @option{-F}, since Posix does not allow
19164 this combination.
19166 Portable @command{grep} regular expressions should use @samp{\} only to
19167 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
19168 alternation, @samp{\|}, is common but Posix does not require its
19169 support in basic regular expressions, so it should be avoided in
19170 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
19171 Similarly, the following escape sequences should also be avoided:
19172 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
19173 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
19175 Posix does not specify the behavior of @command{grep} on binary files.
19176 An example where this matters is using BSD @command{grep} to
19177 search text that includes embedded ANSI escape sequences for
19178 colored output to terminals (@samp{\033[m} is the sequence to restore
19179 normal output); the behavior depends on whether input is seekable:
19181 @example
19182 $ @kbd{printf 'esc\033[mape\n' > sample}
19183 $ @kbd{grep . sample}
19184 Binary file sample matches
19185 $ @kbd{cat sample | grep .}
19186 escape
19187 @end example
19190 @item @command{join}
19191 @c -----------------
19192 @prindex @command{join}
19193 Solaris 8 @command{join} has bugs when the second operand is standard
19194 input, and when standard input is a pipe.  For example, the following
19195 shell script causes Solaris 8 @command{join} to loop forever:
19197 @example
19198 cat >file <<'EOF'
19199 1 x
19200 2 y
19202 cat file | join file -
19203 @end example
19205 Use @samp{join - file} instead.
19207 On NetBSD, @command{join -a 1 file1 file2} mistakenly behaves like
19208 @command{join -a 1 -a 2 1 file1 file2}, resulting in a usage warning;
19209 the workaround is to use @command{join -a1 file1 file2} instead.
19211 @item @command{ln}
19212 @c ---------------
19213 @prindex @command{ln}
19214 The @option{-f} option is portable nowadays.
19216 @cindex Symbolic links
19217 Symbolic links are not available on some systems; use @samp{$(LN_S)} as
19218 a portable substitute.
19220 For versions of the DJGPP before 2.04,
19221 @command{ln} emulates symbolic links
19222 to executables by generating a stub that in turn calls the real
19223 program.  This feature also works with nonexistent files like in the
19224 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
19225 which attempts to call @file{file.exe} if run.  But this feature only
19226 works for executables, so @samp{cp -p} is used instead for these
19227 systems.  DJGPP versions 2.04 and later have full support
19228 for symbolic links.
19231 @item @command{ls}
19232 @c ---------------
19233 @prindex @command{ls}
19234 @cindex Listing directories
19235 The portable options are @option{-acdilrtu}.  Current practice is for
19236 @option{-l} to output both owner and group, even though ancient versions
19237 of @command{ls} omitted the group.
19239 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
19240 to standard output if @file{foo} did not exist.  Hence a shell command
19241 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
19242 was equivalent to @samp{sources='*.c not found'} in the absence of
19243 @samp{.c} files.  This is no longer a practical problem, since current
19244 @command{ls} implementations send diagnostics to standard error.
19246 The behavior of @command{ls} on a directory that is being concurrently
19247 modified is not always predictable, because of a data race where cached
19248 information returned by @code{readdir} does not match the current
19249 directory state.  In fact, MacOS 10.5 has an intermittent bug where
19250 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
19251 once if other files were added or removed from the directory immediately
19252 prior to the @command{ls} call.  Since @command{ls} already sorts its
19253 output, the duplicate entries can be avoided by piping the results
19254 through @code{uniq}.
19256 @anchor{mkdir}
19257 @item @command{mkdir}
19258 @c ------------------
19259 @prindex @command{mkdir}
19260 @cindex Making directories
19261 No @command{mkdir} option is portable to older systems.  Instead of
19262 @samp{mkdir -p @var{file-name}}, you should use
19263 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
19264 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
19266 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
19267 go-w -p @var{dir}}, often leads to trouble.  FreeBSD
19268 @command{mkdir} incorrectly attempts to change the permissions of
19269 @var{dir} even if it already exists.  HP-UX 11.23 and
19270 IRIX 6.5 @command{mkdir} often assign the wrong permissions to
19271 any newly-created parents of @var{dir}.
19273 Posix does not clearly specify whether @samp{mkdir -p foo}
19274 should succeed when @file{foo} is a symbolic link to an already-existing
19275 directory.  The GNU Core Utilities 5.1.0 @command{mkdir}
19276 succeeds, but Solaris @command{mkdir} fails.
19278 Traditional @code{mkdir -p} implementations suffer from race conditions.
19279 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
19280 at the same time, both processes might detect that @file{a} is missing,
19281 one might create @file{a}, then the other might try to create @file{a}
19282 and fail with a @code{File exists} diagnostic.  The GNU Core
19283 Utilities (@samp{fileutils} version 4.1), FreeBSD 5.0,
19284 NetBSD 2.0.2, and OpenBSD 2.4 are known to be
19285 race-free when two processes invoke @code{mkdir -p} simultaneously, but
19286 earlier versions are vulnerable.  Solaris @command{mkdir} is still
19287 vulnerable as of Solaris 10, and other traditional Unix systems are
19288 probably vulnerable too.  This possible race is harmful in parallel
19289 builds when several Make rules call @code{mkdir -p} to
19290 construct directories.  You may use
19291 @code{install-sh -d} as a safe replacement, provided this script is
19292 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
19293 OK, but copies from older versions are vulnerable.
19296 @item @command{mkfifo}
19297 @itemx @command{mknod}
19298 @c -------------------
19299 @prindex @command{mkfifo}
19300 @prindex @command{mknod}
19301 The GNU Coding Standards state that @command{mknod} is safe to use on
19302 platforms where it has been tested to exist; but it is generally portable
19303 only for creating named FIFOs, since device numbers are
19304 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
19305 testsuites.  Posix states that behavior is unspecified when opening a
19306 named FIFO for both reading and writing; on at least Cygwin, this
19307 results in failure on any attempt to read or write to that file
19308 descriptor.
19310 @item @command{mktemp}
19311 @c -------------------
19312 @prindex @command{mktemp}
19313 @cindex Creating temporary files
19314 Shell scripts can use temporary files safely with @command{mktemp}, but
19315 it does not exist on all systems.  A portable way to create a safe
19316 temporary file name is to create a temporary directory with mode 700 and
19317 use a file inside this directory.  Both methods prevent attackers from
19318 gaining control, though @command{mktemp} is far less likely to fail
19319 gratuitously under attack.
19321 Here is sample code to create a new temporary directory @samp{$dir} safely:
19323 @example
19324 # Create a temporary directory $dir in $TMPDIR (default /tmp).
19325 # Use mktemp if possible; otherwise fall back on mkdir,
19326 # with $RANDOM to make collisions less likely.
19327 : "$@{TMPDIR:=/tmp@}"
19329   dir=`
19330     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
19331   ` &&
19332   test -d "$dir"
19333 @} || @{
19334   dir=$TMPDIR/foo$$-$RANDOM
19335 @c $$ restore font-lock
19336   (umask 077 && mkdir "$dir")
19337 @} || exit $?
19338 @end example
19341 @item @command{mv}
19342 @c ---------------
19343 @prindex @command{mv}
19344 @cindex Moving open files
19345 The only portable options are @option{-f} and @option{-i}.
19347 Moving individual files between file systems is portable (it was in Unix
19348 version 6),
19349 but it is not always atomic: when doing @samp{mv new existing}, there's
19350 a critical section where neither the old nor the new version of
19351 @file{existing} actually exists.
19353 On some systems moving files from @file{/tmp} can sometimes cause
19354 undesirable (but perfectly valid) warnings, even if you created these
19355 files.  This is because @file{/tmp} belongs to a group that ordinary
19356 users are not members of, and files created in @file{/tmp} inherit
19357 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
19358 a diagnostic without failing:
19360 @smallexample
19361 $ @kbd{touch /tmp/foo}
19362 $ @kbd{mv /tmp/foo .}
19363 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
19364 $ @kbd{echo $?}
19366 $ @kbd{ls foo}
19368 @end smallexample
19370 @noindent
19371 This annoying behavior conforms to Posix, unfortunately.
19373 Moving directories across mount points is not portable, use @command{cp}
19374 and @command{rm}.
19376 DOS variants cannot rename or remove open files, and do not
19377 support commands like @samp{mv foo bar >foo}, even though this is
19378 perfectly portable among Posix hosts.
19381 @item @command{od}
19382 @c ---------------
19383 @prindex @command{od}
19385 In Mac OS X 10.3, @command{od} does not support the
19386 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
19387 @option{-t}, or the XSI option @option{-s}.  The only
19388 supported Posix option is @option{-v}, and the only supported
19389 XSI options are those in @option{-bcdox}.  The BSD
19390 @command{hexdump} program can be used instead.
19392 This problem no longer exists in Mac OS X 10.4.3.
19395 @item @command{rm}
19396 @c ---------------
19397 @prindex @command{rm}
19398 The @option{-f} and @option{-r} options are portable.
19400 It is not portable to invoke @command{rm} without options or operands.
19401 On the other hand, Posix now requires @command{rm -f} to silently
19402 succeed when there are no operands (useful for constructs like
19403 @command{rm -rf $filelist} without first checking if @samp{$filelist}
19404 was empty).  But this was not always portable; at least NetBSD
19405 @command{rm} built before 2008 would fail with a diagnostic.
19407 A file might not be removed even if its parent directory is writable
19408 and searchable.  Many Posix hosts cannot remove a mount point, a named
19409 stream, a working directory, or a last link to a file that is being
19410 executed.
19412 DOS variants cannot rename or remove open files, and do not
19413 support commands like @samp{rm foo >foo}, even though this is
19414 perfectly portable among Posix hosts.
19416 @item @command{rmdir}
19417 @c ------------------
19418 @prindex @command{rmdir}
19419 Just as with @command{rm}, some platforms refuse to remove a working
19420 directory.
19422 @anchor{sed}
19423 @item @command{sed}
19424 @c ----------------
19425 @prindex @command{sed}
19426 Patterns should not include the separator (unless escaped), even as part
19427 of a character class.  In conformance with Posix, the Cray
19428 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s%[^/]*$%%}.
19429 Even when escaped, patterns should not include separators that are also
19430 used as @command{sed} metacharacters.  For example, GNU sed 4.0.9 rejects
19431 @samp{s,x\@{1\,\@},,}, while sed 4.1 strips the backslash before the comma
19432 before evaluating the basic regular expression.
19434 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
19435 not require support for empty patterns, and Unicos 9 @command{sed} rejects
19436 them.
19438 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
19440 Sed scripts should not use branch labels longer than 7 characters and
19441 should not contain comments; AIX 5.3 @command{sed} rejects indented comments.
19442 HP-UX sed has a limit of 99 commands (not counting @samp{:} commands) and
19443 48 labels, which cannot be circumvented by using more than one script
19444 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
19445 Solaris @command{/usr/ucb/sed} rejects usages that exceed a limit of
19446 about 6000 bytes for the internal representation of commands.
19448 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
19449 NetBSD 1.4.2's, incorrectly try to interpret the second
19450 @samp{;} as a command:
19452 @example
19453 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
19454 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
19455 @end example
19457 Some @command{sed} implementations have a buffer limited to 4000 bytes,
19458 and this limits the size of input lines, output lines, and internal
19459 buffers that can be processed portably.  Likewise,
19460 not all @command{sed} implementations can handle embedded @code{NUL} or
19461 a missing trailing newline.
19463 Remember that ranges within a bracket expression of a regular expression
19464 are only well-defined in the @samp{C} (or @samp{POSIX}) locale.
19465 Meanwhile, support for character classes like @samp{[[:upper:]]} is not
19466 yet universal, so if you cannot guarantee the setting of @env{LC_ALL},
19467 it is better to spell out a range @samp{[ABCDEFGHIJKLMNOPQRSTUVWXYZ]}
19468 than to rely on @samp{[A-Z]}.
19470 Additionally, Posix states that regular expressions are only
19471 well-defined on characters.  Unfortunately, there exist platforms such
19472 as MacOS X 10.5 where not all 8-bit byte values are valid characters,
19473 even though that platform has a single-byte @samp{C} locale.  And Posix
19474 allows the existence of a multi-byte @samp{C} locale, although that does
19475 not yet appear to be a common implementation.  At any rate, it means
19476 that not all bytes will be matched by the regular expression @samp{.}:
19478 @example
19479 $ @kbd{printf '\200\n' | LC_ALL=C sed -n /./p | wc -l}
19481 $ @kbd{printf '\200\n' | LC_ALL=en_US.ISO8859-1 sed -n /./p | wc -l}
19483 @end example
19485 Portable @command{sed} regular expressions should use @samp{\} only to escape
19486 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
19487 alternation, @samp{\|}, is common but Posix does not require its
19488 support, so it should be avoided in portable scripts.  Solaris
19489 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
19490 deletes only lines that contain the literal string @samp{a|b}.
19491 Similarly, @samp{\+} and @samp{\?} should be avoided.
19493 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
19495 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
19496 quite portable to current hosts, but was not supported by some ancient
19497 @command{sed} implementations like SVR3.
19499 Some @command{sed} implementations, e.g., Solaris, restrict the special
19500 role of the asterisk @samp{*} to one-character regular expressions and
19501 back-references, and the special role of interval expressions
19502 @samp{\@{@var{m}\@}}, @samp{\@{@var{m},\@}}, or @samp{\@{@var{m},@var{n}\@}}
19503 to one-character regular expressions.  This may lead to unexpected behavior:
19505 @example
19506 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
19507 x2x4
19508 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
19510 @end example
19512 The @option{-e} option is mostly portable.
19513 However, its argument
19514 cannot start with @samp{a}, @samp{c}, or @samp{i},
19515 as this runs afoul of a Tru64 5.1 bug.
19516 Also, its argument cannot be empty, as this fails on AIX 5.3.
19517 Some people prefer to use @samp{-e}:
19519 @example
19520 sed -e '@var{command-1}' \
19521     -e '@var{command-2}'
19522 @end example
19524 @noindent
19525 as opposed to the equivalent:
19527 @example
19528 sed '
19529   @var{command-1}
19530   @var{command-2}
19532 @end example
19534 @noindent
19535 The following usage is sometimes equivalent:
19537 @example
19538 sed '@var{command-1};@var{command-2}'
19539 @end example
19541 but Posix says that this use of a semicolon has undefined effect if
19542 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
19543 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
19544 should use semicolon only with simple scripts that do not use these
19545 verbs.
19547 Posix up to the 2008 revision requires the argument of the @option{-e}
19548 option to be a syntactically complete script.  GNU @command{sed} allows
19549 to pass multiple script fragments, each as argument of a separate
19550 @option{-e} option, that are then combined, with newlines between the
19551 fragments, and a future Posix revision may allow this as well.  This
19552 approach is not portable with script fragments ending in backslash; for
19553 example, the @command{sed} programs on Solaris 10, HP-UX 11, and AIX
19554 don't allow splitting in this case:
19556 @example
19557 $ @kbd{echo a | sed -n -e 'i\}
19558 @kbd{0'}
19560 $ @kbd{echo a | sed -n -e 'i\' -e 0}
19561 Unrecognized command: 0
19562 @end example
19564 @noindent
19565 In practice, however, this technique of joining fragments
19566 through @option{-e} works for multiple @command{sed} functions within
19567 @samp{@{} and @samp{@}}, even if that is not specified by Posix:
19569 @example
19570 @c The quote around the closing brace silences interactive zsh.
19571 $ @kbd{echo a | sed -n -e '/a/@{' -e s/a/b/ -e p -e '@}'}
19573 @end example
19575 Commands inside @{ @} brackets are further restricted.  Posix 2008 says that
19576 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
19577 each command must be followed immediately by a newline, without any
19578 intervening blanks or semicolons.  The closing bracket must be alone on
19579 a line, other than white space preceding or following it.  However, a
19580 future version of Posix may standardize the use of addresses within brackets.
19582 Contrary to yet another urban legend, you may portably use @samp{&} in
19583 the replacement part of the @code{s} command to mean ``what was
19584 matched''.  All descendants of Unix version 7 @command{sed}
19585 (at least; we
19586 don't have first hand experience with older @command{sed} implementations) have
19587 supported it.
19589 Posix requires that you must not have any white space between
19590 @samp{!} and the following command.  It is OK to have blanks between
19591 the address and the @samp{!}.  For instance, on Solaris:
19593 @example
19594 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
19595 @error{}Unrecognized command: /bar/ ! p
19596 $ @kbd{echo "foo" | sed -n '/bar/! p'}
19597 @error{}Unrecognized command: /bar/! p
19598 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
19600 @end example
19602 Posix also says that you should not combine @samp{!} and @samp{;}.  If
19603 you use @samp{!}, it is best to put it on a command that is delimited by
19604 newlines rather than @samp{;}.
19606 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
19607 @samp{w} commands be followed by exactly one space before their argument.
19608 On the other hand, no white space is allowed between @samp{:} and the
19609 subsequent label name.
19611 If a sed script is specified on the command line and ends in an
19612 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
19613 should be followed by a newline.  Otherwise some @command{sed}
19614 implementations (e.g., OpenBSD 3.9) do not append a newline to the
19615 inserted text.
19617 Many @command{sed} implementations (e.g., MacOS X 10.4,
19618 OpenBSD 3.9, Solaris 10
19619 @command{/usr/ucb/sed}) strip leading white space from the text of
19620 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
19621 work around this incompatibility with Posix:
19623 @example
19624 $ @kbd{echo flushleft | sed 'a\}
19625 > @kbd{   indented}
19626 > @kbd{'}
19627 flushleft
19628 indented
19629 $ @kbd{echo foo | sed 'a\}
19630 > @kbd{\   indented}
19631 > @kbd{'}
19632 flushleft
19633    indented
19634 @end example
19636 Posix requires that with an empty regular expression, the last non-empty
19637 regular expression from either an address specification or substitution
19638 command is applied.  However, busybox 1.6.1 complains when using a
19639 substitution command with a replacement containing a back-reference to
19640 an empty regular expression; the workaround is repeating the regular
19641 expression.
19643 @example
19644 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
19645 sed: No previous regexp.
19646 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
19648 @end example
19651 @item @command{sed} (@samp{t})
19652 @c ---------------------------
19653 @prindex @command{sed} (@samp{t})
19654 Some old systems have @command{sed} that ``forget'' to reset their
19655 @samp{t} flag when starting a new cycle.  For instance on MIPS
19656 RISC/OS, and on IRIX 5.3, if you run the following @command{sed}
19657 script (the line numbers are not actual part of the texts):
19659 @example
19660 s/keep me/kept/g  # a
19661 t end             # b
19662 s/.*/deleted/g    # c
19663 :end              # d
19664 @end example
19666 @noindent
19669 @example
19670 delete me         # 1
19671 delete me         # 2
19672 keep me           # 3
19673 delete me         # 4
19674 @end example
19676 @noindent
19677 you get
19679 @example
19680 deleted
19681 delete me
19682 kept
19683 deleted
19684 @end example
19686 @noindent
19687 instead of
19689 @example
19690 deleted
19691 deleted
19692 kept
19693 deleted
19694 @end example
19696 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
19697 flag, and the output is produced.  When processing
19698 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
19699 fails to match, but @command{sed} is not supposed to clear the @samp{t}
19700 flag when a substitution fails.  Command (b) sees that the flag is set,
19701 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
19702 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
19703 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
19704 Finally, since the flag is clear, line 4 is processed properly.
19706 There are two things one should remember about @samp{t} in @command{sed}.
19707 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
19708 succeeded, not only the immediately preceding substitution.  Therefore,
19709 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
19710 line, to reset the @samp{t} flag where needed.
19712 Secondly, you cannot rely on @command{sed} to clear the flag at each new
19713 cycle.
19715 One portable implementation of the script above is:
19717 @example
19718 t clear
19719 :clear
19720 s/keep me/kept/g
19721 t end
19722 s/.*/deleted/g
19723 :end
19724 @end example
19726 @item @command{sleep}
19727 @c ------------------
19728 @prindex @command{sleep}
19729 Using @command{sleep} is generally portable.  However, remember that
19730 adding a @command{sleep} to work around timestamp issues, with a minimum
19731 granularity of one second, doesn't scale well for parallel builds on
19732 modern machines with sub-second process completion.
19734 @item @command{sort}
19735 @c -----------------
19736 @prindex @command{sort}
19737 Remember that sort order is influenced by the current locale.  Inside
19738 @file{configure}, the C locale is in effect, but in Makefile snippets,
19739 you may need to specify @code{LC_ALL=C sort}.
19741 @item @command{tar}
19742 @c ----------------
19743 @prindex @command{tar}
19744 There are multiple file formats for @command{tar}; if you use Automake,
19745 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
19746 level of portability to use.
19748 @anchor{touch}
19749 @item @command{touch}
19750 @c ------------------
19751 @prindex @command{touch}
19752 @cindex timestamp resolution
19753 If you specify the desired timestamp (e.g., with the @option{-r}
19754 option), older @command{touch} implementations use the @code{utime} or
19755 @code{utimes} system call, which can result in the same kind of
19756 timestamp truncation problems that @samp{cp -p} has.
19758 On ancient BSD systems, @command{touch} or any command that
19759 results in an empty file does not update the timestamps, so use a
19760 command like @command{echo} as a workaround.
19761 Also,
19762 GNU @command{touch} 3.16r (and presumably all before that)
19763 fails to work on SunOS 4.1.3 when the empty file is on an
19764 NFS-mounted 4.2 volume.
19765 However, these problems are no longer of practical concern.
19767 @item @command{tr}
19768 @c ---------------
19769 @prindex @command{tr}
19770 @cindex carriage return, deleting
19771 @cindex newline, deleting
19772 @cindex deleting carriage return
19773 Not all versions of @command{tr} handle all backslash character escapes.
19774 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
19775 Solaris contains more modern @command{tr} in other locations.
19776 Using octal escapes is more portable for carriage returns, since
19777 @samp{\015} is the same for both ASCII and EBCDIC, and since use of
19778 literal carriage returns in scripts causes a number of other problems.
19779 But for other characters, like newline, using octal escapes ties the
19780 operation to ASCII, so it is better to use literal characters.
19782 @example
19783 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
19785 light
19786 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
19787 moonlight
19788 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
19789 moonlight
19790 $ @kbd{nl='}
19791 @kbd{'; @{ echo moon; echo light; @} | /usr/ucb/tr -d "$nl" ; echo}
19792 moonlight
19793 @end example
19795 Not all versions of @command{tr} recognize direct ranges of characters: at
19796 least Solaris @command{/usr/bin/tr} still fails to do so.  But you can
19797 use @command{/usr/xpg4/bin/tr} instead, or add brackets (which in Posix
19798 transliterate to themselves).
19800 @example
19801 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr a-z A-Z}
19802 HAZy FAntAZy
19803 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/bin/tr '[a-z]' '[A-Z]'}
19804 HAZY FANTAZY
19805 $ @kbd{echo "Hazy Fantazy" | LC_ALL=C /usr/xpg4/bin/tr a-z A-Z}
19806 HAZY FANTAZY
19807 @end example
19809 When providing two arguments, be sure the second string is at least as
19810 long as the first.
19812 @example
19813 $ @kbd{echo abc | /usr/xpg4/bin/tr bc d}
19815 $ @kbd{echo abc | coreutils/tr bc d}
19817 @end example
19819 Posix requires @command{tr} to operate on binary files.  But at least
19820 Solaris @command{/usr/ucb/tr} and @command{/usr/bin/tr} silently discard
19821 @code{NUL} in the input prior to doing any translation.  When using
19822 @command{tr} to process a binary file that may contain @code{NUL} bytes,
19823 it is necessary to use @command{/usr/xpg4/bin/tr} instead, or
19824 @command{/usr/xpg6/bin/tr} if that is available.
19826 @example
19827 $ @kbd{printf 'a\0b' | /usr/ucb/tr x x | od -An -tx1}
19828  61 62
19829 $ @kbd{printf 'a\0b' | /usr/bin/tr x x | od -An -tx1}
19830  61 62
19831 $ @kbd{printf 'a\0b' | /usr/xpg4/bin/tr x x | od -An -tx1}
19832  61 00 62
19833 @end example
19835 Solaris @command{/usr/ucb/tr} additionally fails to handle @samp{\0} as the
19836 octal escape for @code{NUL}.
19838 @example
19839 $ @kbd{printf 'abc' | /usr/ucb/tr 'bc' '\0d' | od -An -tx1}
19840  61 62 63
19841 $ @kbd{printf 'abc' | /usr/bin/tr 'bc' '\0d' | od -An -tx1}
19842  61 00 64
19843 $ @kbd{printf 'abc' | /usr/xpg4/bin/tr 'bc' '\0d' | od -An -tx1}
19844  61 00 64
19845 @end example
19847 @end table
19850 @node Portable Make
19851 @chapter Portable Make Programming
19852 @prindex @command{make}
19853 @cindex Limitations of @command{make}
19855 Writing portable makefiles is an art.  Since a makefile's commands are
19856 executed by the shell, you must consider the shell portability issues
19857 already mentioned.  However, other issues are specific to @command{make}
19858 itself.
19860 @menu
19861 * $< in Ordinary Make Rules::   $< in ordinary rules
19862 * Failure in Make Rules::       Failing portably in rules
19863 * Special Chars in Names::      Special Characters in Macro Names
19864 * Backslash-Newline-Empty::     Empty lines after backslash-newline
19865 * Backslash-Newline Comments::  Spanning comments across line boundaries
19866 * Long Lines in Makefiles::     Line length limitations
19867 * Macros and Submakes::         @code{make macro=value} and submakes
19868 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
19869 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
19870 * Parallel Make::               Parallel @command{make} quirks
19871 * Comments in Make Rules::      Other problems with Make comments
19872 * Newlines in Make Rules::      Using literal newlines in rules
19873 * Comments in Make Macros::     Other problems with Make comments in macros
19874 * Trailing whitespace in Make Macros::  Macro substitution problems
19875 * Command-line Macros and whitespace::  Whitespace trimming of values
19876 * obj/ and Make::               Don't name a subdirectory @file{obj}
19877 * make -k Status::              Exit status of @samp{make -k}
19878 * VPATH and Make::              @code{VPATH} woes
19879 * Single Suffix Rules::         Single suffix rules and separated dependencies
19880 * Timestamps and Make::         Subsecond timestamp resolution
19881 @end menu
19883 @node $< in Ordinary Make Rules
19884 @section @code{$<} in Ordinary Make Rules
19886 Posix says that the @samp{$<} construct in makefiles can be
19887 used only in inference rules and in the @samp{.DEFAULT} rule; its
19888 meaning in ordinary rules is unspecified.  Solaris @command{make}
19889 for instance replaces it with the empty string.  OpenBSD (3.0 and
19890 later) @command{make} diagnoses these uses and errors out.
19892 @node Failure in Make Rules
19893 @section Failure in Make Rules
19895 Posix 2008 requires that @command{make} must invoke each command with
19896 the equivalent of a @samp{sh -e -c} subshell, which causes the
19897 subshell to exit immediately if a subsidiary simple-command fails,
19898 although not all @command{make} implementations have historically
19899 followed this rule.  For
19900 example, the command @samp{touch T; rm -f U} may attempt to
19901 remove @file{U} even if the @command{touch} fails, although this is not
19902 permitted with Posix make.  One way to work around failures in simple
19903 commands is to reword them so that they always succeed, e.g., @samp{touch
19904 T || :; rm -f U}.
19905 However, even this approach can run into common bugs in BSD
19906 implementations of the @option{-e} option of @command{sh} and
19907 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
19908 are worried
19909 about porting to buggy BSD shells it may be simpler to migrate
19910 complicated @command{make} actions into separate scripts.
19912 @node Special Chars in Names
19913 @section Special Characters in Make Macro Names
19915 Posix limits macro names to nonempty strings containing only
19916 ASCII letters and digits, @samp{.}, and @samp{_}.  Many
19917 @command{make} implementations allow a wider variety of characters, but
19918 portable makefiles should avoid them.  It is portable to start a name
19919 with a special character, e.g., @samp{$(.FOO)}.
19921 Some ancient @command{make} implementations don't support leading
19922 underscores in macro names.  An example is NEWS-OS 4.2R.
19924 @example
19925 $ @kbd{cat Makefile}
19926 _am_include = #
19927 _am_quote =
19928 all:; @@echo this is test
19929 $ @kbd{make}
19930 Make: Must be a separator on rules line 2.  Stop.
19931 $ @kbd{cat Makefile2}
19932 am_include = #
19933 am_quote =
19934 all:; @@echo this is test
19935 $ @kbd{make -f Makefile2}
19936 this is test
19937 @end example
19939 @noindent
19940 However, this problem is no longer of practical concern.
19942 @node Backslash-Newline-Empty
19943 @section Backslash-Newline Before Empty Lines
19945 A bug in Bash 2.03 can cause problems if a Make rule contains a
19946 backslash-newline followed by line that expands to nothing.
19947 For example, on Solaris 8:
19949 @example
19950 SHELL = /bin/bash
19951 EMPTY =
19952 foo:
19953         touch foo \
19954         $(EMPTY)
19955 @end example
19957 @noindent
19958 executes
19960 @example
19961 /bin/bash -c 'touch foo \
19963 @end example
19965 @noindent
19966 which fails with a syntax error, due to the Bash bug.  To avoid this
19967 problem, avoid nullable macros in the last line of a multiline command.
19969 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
19970 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
19971 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
19972 On some versions of HP-UX, @command{make} reads multiple newlines
19973 following a backslash, continuing to the next non-empty line.  For
19974 example,
19976 @example
19977 FOO = one \
19979 BAR = two
19981 test:
19982         : FOO is "$(FOO)"
19983         : BAR is "$(BAR)"
19984 @end example
19986 @noindent
19987 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
19988 sensibly let a backslash continue only to the immediately following
19989 line.
19991 @node Backslash-Newline Comments
19992 @section Backslash-Newline in Make Comments
19994 According to Posix, Make comments start with @code{#}
19995 and continue until an unescaped newline is reached.
19997 @example
19998 $ @kbd{cat Makefile}
19999 # A = foo \
20000       bar \
20001       baz
20003 all:
20004         @@echo ok
20005 $ @kbd{make}   # GNU make
20007 @end example
20009 @noindent
20010 However this is not always the case.  Some implementations
20011 discard everything from @code{#} through the end of the line, ignoring any
20012 trailing backslash.
20014 @example
20015 $ @kbd{pmake}  # BSD make
20016 "Makefile", line 3: Need an operator
20017 Fatal errors encountered -- cannot continue
20018 @end example
20020 @noindent
20021 Therefore, if you want to comment out a multi-line definition, prefix each
20022 line with @code{#}, not only the first.
20024 @example
20025 # A = foo \
20026 #     bar \
20027 #     baz
20028 @end example
20030 @node Long Lines in Makefiles
20031 @section Long Lines in Makefiles
20033 Tru64 5.1's @command{make} has been reported to crash when given a
20034 makefile with lines longer than around 20 kB.  Earlier versions are
20035 reported to exit with @code{Line too long} diagnostics.
20037 @node Macros and Submakes
20038 @section @code{make macro=value} and Submakes
20040 A command-line variable definition such as @code{foo=bar} overrides any
20041 definition of @code{foo} in a makefile.  Some @command{make}
20042 implementations (such as GNU @command{make}) propagate this
20043 override to subsidiary invocations of @command{make}.  Some other
20044 implementations do not pass the substitution along to submakes.
20046 @example
20047 $ @kbd{cat Makefile}
20048 foo = foo
20049 one:
20050         @@echo $(foo)
20051         $(MAKE) two
20052 two:
20053         @@echo $(foo)
20054 $ @kbd{make foo=bar}            # GNU make 3.79.1
20056 make two
20057 make[1]: Entering directory `/home/adl'
20059 make[1]: Leaving directory `/home/adl'
20060 $ @kbd{pmake foo=bar}           # BSD make
20062 pmake two
20064 @end example
20066 You have a few possibilities if you do want the @code{foo=bar} override
20067 to propagate to submakes.  One is to use the @option{-e}
20068 option, which causes all environment variables to have precedence over
20069 the makefile macro definitions, and declare foo as an environment
20070 variable:
20072 @example
20073 $ @kbd{env foo=bar make -e}
20074 @end example
20076 The @option{-e} option is propagated to submakes automatically,
20077 and since the environment is inherited between @command{make}
20078 invocations, the @code{foo} macro is overridden in
20079 submakes as expected.
20081 This syntax (@code{foo=bar make -e}) is portable only when used
20082 outside of a makefile, for instance from a script or from the
20083 command line.  When run inside a @command{make} rule, GNU
20084 @command{make} 3.80 and prior versions forget to propagate the
20085 @option{-e} option to submakes.
20087 Moreover, using @option{-e} could have unexpected side effects if your
20088 environment contains some other macros usually defined by the
20089 makefile.  (See also the note about @code{make -e} and @code{SHELL}
20090 below.)
20092 If you can foresee all macros that a user might want to override, then
20093 you can propagate them to submakes manually, from your makefile:
20095 @example
20096 foo = foo
20097 one:
20098         @@echo $(foo)
20099         $(MAKE) foo=$(foo) two
20100 two:
20101         @@echo $(foo)
20102 @end example
20104 Another way to propagate a variable to submakes in a portable way is to
20105 expand an extra variable in every invocation of @samp{$(MAKE)} within
20106 your makefile:
20108 @example
20109 foo = foo
20110 one:
20111         @@echo $(foo)
20112         $(MAKE) $(SUBMAKEFLAGS) two
20113 two:
20114         @@echo $(foo)
20115 @end example
20117 Users must be aware that this technique is in use to take advantage of
20118 it, e.g.@: with @code{make foo=bar SUBMAKEFLAGS='foo=bar'}, but it
20119 allows any macro to be overridden.  Makefiles generated by
20120 @command{automake} use this technique, expanding @code{$(AM_MAKEFLAGS)}
20121 on the command lines of submakes (@pxref{Subdirectories, , Automake,
20122 automake, GNU Automake}).
20124 @node The Make Macro MAKEFLAGS
20125 @section The Make Macro MAKEFLAGS
20126 @cindex @code{MAKEFLAGS} and @command{make}
20127 @cindex @command{make} and @code{MAKEFLAGS}
20129 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
20130 current and recursive invocations of make, but allows implementations
20131 several formats for the variable.  It is tricky to parse
20132 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
20133 or @option{-k} for continued execution are in effect.  For example, you
20134 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
20135 contains single-letter options, since in the Cygwin version of
20136 GNU @command{make} it is either @option{--unix} or
20137 @option{--win32} with the second word containing single-letter options.
20139 @example
20140 $ @kbd{cat Makefile}
20141 all:
20142         @@echo MAKEFLAGS = $(MAKEFLAGS)
20143 $ @kbd{make}
20144 MAKEFLAGS = --unix
20145 $ @kbd{make -k}
20146 MAKEFLAGS = --unix -k
20147 @end example
20149 @node The Make Macro SHELL
20150 @section The Make Macro @code{SHELL}
20151 @cindex @code{SHELL} and @command{make}
20152 @cindex @command{make} and @code{SHELL}
20154 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
20155 macro to spawn shell processes and execute Make rules.  This
20156 is a builtin macro supplied by @command{make}, but it can be modified
20157 by a makefile or by a command-line argument.
20159 Not all @command{make} implementations define this @code{SHELL} macro.
20160 Tru64
20161 @command{make} is an example; this implementation always uses
20162 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
20163 your makefiles.  If you use Autoconf, do
20165 @example
20166 SHELL = @@SHELL@@
20167 @end example
20169 @noindent
20170 If you use Automake, this is done for you.
20172 Do not force @code{SHELL = /bin/sh} because that is not correct
20173 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
20174 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
20175 Additionally, DJGPP lacks @code{/bin/sh}, and when its
20176 GNU @command{make} port sees such a setting it enters a
20177 special emulation mode where features like pipes and redirections are
20178 emulated on top of DOS's @command{command.com}.  Unfortunately this
20179 emulation is incomplete; for instance it does not handle command
20180 substitutions.  Using @code{@@SHELL@@} means that your makefile will
20181 benefit from the same improved shell, such as @command{bash} or
20182 @command{ksh}, that was discovered during @command{configure}, so that
20183 you aren't fighting two different sets of shell bugs between the two
20184 contexts.
20186 Posix-compliant @command{make} should never acquire the value of
20187 $(SHELL) from the environment, even when @code{make -e} is used
20188 (otherwise, think about what would happen to your rules if
20189 @code{SHELL=/bin/tcsh}).
20191 However not all @command{make} implementations have this exception.
20192 For instance it's not surprising that Tru64 @command{make} doesn't
20193 protect @code{SHELL}, since it doesn't use it.
20195 @example
20196 $ @kbd{cat Makefile}
20197 SHELL = /bin/sh
20198 FOO = foo
20199 all:
20200         @@echo $(SHELL)
20201         @@echo $(FOO)
20202 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
20203 /bin/tcsh
20205 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
20206 /bin/sh
20208 @end example
20210 Conversely, @command{make} is not supposed to export any changes to the
20211 macro @code{SHELL} to child processes.  Again, many implementations
20212 break this rule:
20214 @example
20215 $ @kbd{cat Makefile}
20216 all:
20217         @@echo $(SHELL)
20218         @@printenv SHELL
20219 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
20220 /bin/ksh
20221 /bin/ksh
20222 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
20223 /bin/ksh
20225 @end example
20227 @node Parallel Make
20228 @section Parallel Make
20229 @cindex Parallel @command{make}
20231 Support for parallel execution in @command{make} implementation varies.
20232 Generally, using GNU make is your best bet.
20234 When NetBSD or FreeBSD @command{make} are run in parallel mode, they will
20235 reuse the same shell for multiple commands within one recipe.  This can
20236 have various unexpected consequences.  For example, changes of directories
20237 or variables persist between recipes, so that:
20239 @example
20240 all:
20241         @@var=value; cd /; pwd; echo $$var; echo $$$$
20242         @@pwd; echo $$var; echo $$$$
20243 @end example
20245 @noindent
20246 may output the following with @code{make -j1}, at least on NetBSD up to
20247 5.1 and FreeBSD up to 8.2:
20249 @example
20251 value
20252 32235
20254 value
20255 32235
20256 @end example
20258 @noindent
20259 while without @option{-j1}, or with @option{-B}, the output looks less
20260 surprising:
20262 @example
20264 value
20265 32238
20266 /tmp
20268 32239
20269 @end example
20271 @noindent
20272 Another consequence is that, if one command in a recipe uses @code{exit 0}
20273 to indicate a successful exit, the shell will be gone and the remaining
20274 commands of this recipe will not be executed.
20276 The BSD @command{make} implementations, when run in parallel mode,
20277 will also pass the @command{Makefile} recipes to the shell through
20278 its standard input, thus making it unusable from the recipes:
20280 @example
20281 $ @kbd{cat Makefile}
20282 read:
20283         @@read line; echo LINE: $$line
20284 @c $$ @c restore font-lock
20285 $ @kbd{echo foo | make read}
20286 LINE: foo
20287 $ @kbd{echo foo | make -j1 read} # NetBSD 5.1 and FreeBSD 8.2
20288 LINE:
20289 @end example
20291 @noindent
20292 Moreover, when FreeBSD @command{make} (up at least to 8.2) is run in
20293 parallel mode, it implements the @code{@@} and @code{-} ``recipe
20294 modifiers'' by dynamically modifying the active shell flags.  This
20295 behavior has the effects of potentially clobbering the exit status
20296 of recipes silenced with the @code{@@} modifier if they also unset
20297 the @option{errexit} shell flag, and of mangling the output in
20298 unexpected ways:
20300 @example
20301 $ @kbd{cat Makefile}
20303         @@echo $$-; set +e; false
20305         -echo $$-; false; echo set -
20306 $ @kbd{make a; echo status: $?}
20307 ehBc
20308 *** Error code 1
20309 status: 1
20310 $ @kbd{make -j1 a; echo status: $?}
20312 status: 0
20313 $ @kbd{make b}
20314 echo $-; echo set -
20316 set -
20317 $ @kbd{make -j1 b}
20318 echo $-; echo hvB
20319 @end example
20321 @noindent
20322 You can avoid all these issues by using the @option{-B} option to enable
20323 compatibility semantics.  However, that will effectively also disable
20324 all parallelism as that will cause prerequisites to be updated in the
20325 order they are listed in a rule.
20327 Some make implementations (among them, FreeBSD @command{make}, NetBSD
20328 @command{make}, and Solaris @command{dmake}), when invoked with a
20329 @option{-j@var{N}} option, connect the standard output and standard
20330 error of all their child processes to pipes or temporary regular
20331 files.  This can lead to subtly different semantics in the behavior
20332 of the spawned processes.  For example, even if the @command{make}
20333 standard output is connected to a tty, the recipe command will not be:
20335 @example
20336 $ @kbd{cat Makefile}
20337 all:
20338         @@test -t 1 && echo "Is a tty" || echo "Is not a tty"
20339 $ @kbd{make -j 2} # FreeBSD 8.2 make
20340 Is not a tty
20341 $ @kbd{make -j 2} # NetBSD 5.1 make
20342 --- all ---
20343 Is not a tty
20344 $ @kbd{dmake -j 2} # Solaris 10 dmake
20345 @var{hostname} --> 1 job
20346 @var{hostname} --> Job output
20347 Is not a tty
20348 @end example
20350 @noindent
20351 On the other hand:
20353 @example
20354 $ @kbd{make -j 2} # GNU make, Heirloom make
20355 Is a tty
20356 @end example
20358 @noindent
20359 The above examples also show additional status output produced in parallel
20360 mode for targets being updated by Solaris @command{dmake} and NetBSD
20361 @command{make} (but @emph{not} by FreeBSD @command{make}).
20363 Furthermore, parallel runs of those @command{make} implementations will
20364 route standard error from commands that they spawn into their own
20365 standard output, and may remove leading whitespace from output lines.
20368 @node Comments in Make Rules
20369 @section Comments in Make Rules
20370 @cindex Comments in @file{Makefile} rules
20371 @cindex @file{Makefile} rules and comments
20373 Never put comments in a rule.
20375 Some @command{make} treat anything starting with a tab as a command for
20376 the current rule, even if the tab is immediately followed by a @code{#}.
20377 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
20378 makefile runs @code{# foo} through the shell.
20380 @example
20381 all:
20382         # foo
20383 @end example
20385 As a workaround, you can use the @command{:} no-op command with a string
20386 argument that gets ignored:
20388 @example
20389 all:
20390         : "foo"
20391 @end example
20393 Conversely, if you want to use the @samp{#} character in some command,
20394 you can only do so by expanding it inside a rule (@pxref{Comments in
20395 Make Macros}).  So for example, if @samp{COMMENT_CHAR} is substituted by
20396 @command{config.status} as @samp{#}, then the following substitutes
20397 @samp{@@COMMENT_CHAR@@} in a generated header:
20399 @example
20400 foo.h: foo.h.in
20401         sed -e 's|@@''COMMENT_CHAR''@@|@@COMMENT_CHAR@@|g' \
20402             $(srcdir)/foo.h.in > $@@
20403 @end example
20405 The funny shell quoting avoids a substitution at @command{config.status}
20406 run time of the left-hand side of the @command{sed} @samp{s} command.
20408 @node Newlines in Make Rules
20409 @section Newlines in Make Rules
20410 @cindex Newlines in @file{Makefile} rules
20411 @cindex @file{Makefile} rules and newlines
20413 In shell scripts, newlines can be used inside string literals.  But in
20414 the shell statements of @file{Makefile} rules, this is not possible:
20415 A newline not preceded by a backslash is a separator between shell
20416 statements.  Whereas a newline that is preceded by a backslash becomes
20417 part of the shell statement according to POSIX, but gets replaced,
20418 together with the backslash that precedes it, by a space in GNU
20419 @command{make} 3.80 and older.  So, how can a newline be used in a string
20420 literal?
20422 The trick is to set up a shell variable that contains a newline:
20424 @example
20425 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"
20426 @end example
20428 For example, in order to create a multiline @samp{sed} expression that
20429 inserts a blank line after every line of a file, this code can be used:
20431 @example
20432 nlinit=`echo 'nl="'; echo '"'`; eval "$$nlinit"; \
20433 sed -e "s/\$$/\\$$@{nl@}/" < input > output
20434 @end example
20436 @node Comments in Make Macros
20437 @section Comments in Make Macros
20438 @cindex Comments in @file{Makefile} macros
20439 @cindex @file{Makefile} macros and comments
20441 Avoid putting comments in macro values as far as possible.  Posix
20442 specifies that the text starting from the @samp{#} sign until the end of
20443 the line is to be ignored, which has the unfortunate effect of
20444 disallowing them even within quotes.  Thus, the following might lead to
20445 a syntax error at compile time:
20447 @example
20448 CPPFLAGS = "-DCOMMENT_CHAR='#'"
20449 @end example
20451 @noindent
20452 as @samp{CPPFLAGS} may be expanded to @samp{"-DCOMMENT_CHAR='}.
20454 Most @command{make} implementations disregard this and treat single and
20455 double quotes specially here.  Also, GNU @command{make} lets you put
20456 @samp{#} into a macro value by escaping it with a backslash, i.e.,
20457 @samp{\#}.  However, neither of these usages are portable.
20458 @xref{Comments in Make Rules}, for a portable alternative.
20460 Even without quoting involved, comments can have surprising effects,
20461 because the whitespace before them is part of the variable value:
20463 @example
20464 foo = bar # trailing comment
20465 print: ; @@echo "$(foo)."
20466 @end example
20468 @noindent
20469 prints @samp{bar .}, which is usually not intended, and can expose
20470 @command{make} bugs as described below.
20472 @node Trailing whitespace in Make Macros
20473 @section Trailing whitespace in Make Macros
20474 @cindex whitespace in @file{Makefile} macros
20475 @cindex @file{Makefile} macros and whitespace
20477 GNU @command{make} 3.80 mistreats trailing whitespace in macro
20478 substitutions and appends another spurious suffix:
20480 @example
20481 empty =
20482 foo = bar $(empty)
20483 print: ; @@echo $(foo:=.test)
20484 @end example
20486 @noindent
20487 prints @samp{bar.test .test}.
20489 BSD and Solaris @command{make} implementations do not honor trailing
20490 whitespace in macro definitions as Posix requires:
20492 @example
20493 foo = bar # Note the space after "bar".
20494 print: ; @@echo $(foo)t
20495 @end example
20497 @noindent
20498 prints @samp{bart} instead of @samp{bar t}.  To work around this, you
20499 can use a helper macro as in the previous example.
20502 @node Command-line Macros and whitespace
20503 @section Command-line Macros and whitespace
20504 @cindex whitespace in command-line macros
20505 @cindex command-line, macros set on
20506 @cindex environment, macros set from
20508 Some @command{make} implementations may strip trailing whitespace off
20509 of macros set on the command line in addition to leading whitespace.
20510 Further, some may strip leading whitespace off of macros set from
20511 environment variables:
20513 @example
20514 $ @kbd{echo 'print: ; @@echo "x$(foo)x$(bar)x"' |
20515   foo=' f f ' make -f - bar=' b b '}
20516 x f f xb b x  # AIX, BSD, GNU make
20517 xf f xb b x   # HP-UX, IRIX, Tru64/OSF make
20518 x f f xb bx   # Solaris make
20519 @end example
20522 @node obj/ and Make
20523 @section The @file{obj/} Subdirectory and Make
20524 @cindex @file{obj/}, subdirectory
20525 @cindex BSD @command{make} and @file{obj/}
20527 Never name one of your subdirectories @file{obj/} if you don't like
20528 surprises.
20530 If an @file{obj/} directory exists, BSD @command{make} enters it
20531 before reading the makefile.  Hence the makefile in the
20532 current directory is not read.
20534 @example
20535 $ @kbd{cat Makefile}
20536 all:
20537         echo Hello
20538 $ @kbd{cat obj/Makefile}
20539 all:
20540         echo World
20541 $ @kbd{make}      # GNU make
20542 echo Hello
20543 Hello
20544 $ @kbd{pmake}     # BSD make
20545 echo World
20546 World
20547 @end example
20549 @node make -k Status
20550 @section Exit Status of @code{make -k}
20551 @cindex @code{make -k}
20553 Do not rely on the exit status of @code{make -k}.  Some implementations
20554 reflect whether they encountered an error in their exit status; other
20555 implementations always succeed.
20557 @example
20558 $ @kbd{cat Makefile}
20559 all:
20560         false
20561 $ @kbd{make -k; echo exit status: $?}    # GNU make
20562 false
20563 make: *** [all] Error 1
20564 exit status: 2
20565 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
20566 false
20567 *** Error code 1 (continuing)
20568 exit status: 0
20569 @end example
20571 @node VPATH and Make
20572 @section @code{VPATH} and Make
20573 @cindex @code{VPATH}
20575 Posix does not specify the semantics of @code{VPATH}.  Typically,
20576 @command{make} supports @code{VPATH}, but its implementation is not
20577 consistent.
20579 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
20580 portable to recent-enough popular implementations of @command{make}, but
20581 to keep the resulting makefiles portable, a package's makefile
20582 prototypes must take the following issues into account.  These issues
20583 are complicated and are often poorly understood, and installers who use
20584 @code{VPATH} should expect to find many bugs in this area.  If you use
20585 @code{VPATH}, the simplest way to avoid these portability bugs is to
20586 stick with GNU @command{make}, since it is the most
20587 commonly-used @command{make} among Autoconf users.
20589 Here are some known issues with some @code{VPATH}
20590 implementations.
20592 @menu
20593 * Variables listed in VPATH::   @code{VPATH} must be literal on ancient hosts
20594 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
20595 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
20596 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
20597 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
20598 * Make Target Lookup::          More details about @code{VPATH} lookup
20599 @end menu
20601 @node Variables listed in VPATH
20602 @subsection Variables listed in @code{VPATH}
20603 @cindex @code{VPATH} and variables
20604 @cindex variables and @code{VPATH}
20606 Do not set @code{VPATH} to the value of another variable, for example
20607 @samp{VPATH = $(srcdir)}, because some ancient versions of
20608 @command{make} do not do variable substitutions on the value of
20609 @code{VPATH}.  For example, use this
20611 @example
20612 srcdir = @@srcdir@@
20613 VPATH = @@srcdir@@
20614 @end example
20616 @noindent
20617 rather than @samp{VPATH = $(srcdir)}.  Note that with GNU
20618 Automake, there is no need to set this yourself.
20620 @node VPATH and Double-colon
20621 @subsection @code{VPATH} and Double-colon Rules
20622 @cindex @code{VPATH} and double-colon rules
20623 @cindex double-colon rules and @code{VPATH}
20625 With ancient versions of Sun @command{make},
20626 any assignment to @code{VPATH} causes @command{make} to execute only
20627 the first set of double-colon rules.
20628 However, this problem is no longer of practical concern.
20630 @node $< in Explicit Rules
20631 @subsection @code{$<} Not Supported in Explicit Rules
20632 @cindex explicit rules, @code{$<}, and @code{VPATH}
20633 @cindex @code{$<}, explicit rules, and @code{VPATH}
20634 @cindex @code{VPATH}, explicit rules, and @code{$<}
20636 Using @code{$<} in explicit rules is not portable.
20637 The prerequisite file must be named explicitly in the rule.  If you want
20638 to find the prerequisite via a @code{VPATH} search, you have to code the
20639 whole thing manually.  @xref{Build Directories}.
20641 @node Automatic Rule Rewriting
20642 @subsection Automatic Rule Rewriting
20643 @cindex @code{VPATH} and automatic rule rewriting
20644 @cindex automatic rule rewriting and @code{VPATH}
20646 Some @command{make} implementations, such as Solaris and Tru64,
20647 search for prerequisites in @code{VPATH} and
20648 then rewrite each occurrence as a plain word in the rule.
20649 For instance:
20651 @example
20652 # This isn't portable to GNU make.
20653 VPATH = ../pkg/src
20654 f.c: if.c
20655         cp if.c f.c
20656 @end example
20658 @noindent
20659 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
20660 found in @file{../pkg/src}.
20662 However, this rule leads to real problems in practice.  For example, if
20663 the source directory contains an ordinary file named @file{test} that is
20664 used in a dependency, Solaris @command{make} rewrites commands like
20665 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
20666 @dots{}}, which is typically undesirable.  In fact, @command{make} is
20667 completely unaware of shell syntax used in the rules, so the VPATH
20668 rewrite can potentially apply to @emph{any} whitespace-separated word
20669 in a rule, including shell variables, functions, and keywords.
20671 @example
20672 $ @kbd{mkdir build}
20673 $ @kbd{cd build}
20674 $ @kbd{cat > Makefile <<'END'}
20675 VPATH = ..
20676 all: arg func for echo
20677         func () @{ for arg in "$$@@"; do echo $$arg; done; @}; \
20678         func "hello world"
20680 $ @kbd{touch ../arg ../func ../for ../echo}
20681 $ @kbd{make}
20682 ../func () @{ ../for ../arg in "$@@"; do ../echo $arg; done; @}; \
20683 ../func "hello world"
20684 sh: syntax error at line 1: `do' unexpected
20685 *** Error code 2
20686 @end example
20688 @noindent
20689 To avoid this problem, portable makefiles should never mention a source
20690 file or dependency whose name is that of a shell keyword like @file{for}
20691 or @file{until}, a shell command like @command{cat} or @command{gcc} or
20692 @command{test}, or a shell function or variable used in the corresponding
20693 @command{Makefile} recipe.
20695 Because of these problems GNU @command{make} and many other @command{make}
20696 implementations do not rewrite commands, so portable makefiles should
20697 search @code{VPATH} manually.  It is tempting to write this:
20699 @smallexample
20700 # This isn't portable to Solaris make.
20701 VPATH = ../pkg/src
20702 f.c: if.c
20703         cp `test -f if.c || echo $(VPATH)/`if.c f.c
20704 @end smallexample
20706 @noindent
20707 However, the ``prerequisite rewriting'' still applies here.  So if
20708 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
20709 execute
20711 @smallexample
20712 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
20713 @end smallexample
20715 @noindent
20716 which reduces to
20718 @example
20719 cp if.c f.c
20720 @end example
20722 @noindent
20723 and thus fails.  Oops.
20725 A simple workaround, and good practice anyway, is to use @samp{$?} and
20726 @samp{$@@} when possible:
20728 @smallexample
20729 VPATH = ../pkg/src
20730 f.c: if.c
20731         cp $? $@@
20732 @end smallexample
20734 @noindent
20735 but this does not generalize well to commands with multiple
20736 prerequisites.  A more general workaround is to rewrite the rule so that
20737 the prerequisite @file{if.c} never appears as a plain word.  For
20738 example, these three rules would be safe, assuming @file{if.c} is in
20739 @file{../pkg/src} and the other files are in the working directory:
20741 @smallexample
20742 VPATH = ../pkg/src
20743 f.c: if.c f1.c
20744         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
20745 g.c: if.c g1.c
20746         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
20747 h.c: if.c h1.c
20748         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
20749 @end smallexample
20751 Things get worse when your prerequisites are in a macro.
20753 @example
20754 VPATH = ../pkg/src
20755 HEADERS = f.h g.h h.h
20756 install-HEADERS: $(HEADERS)
20757         for i in $(HEADERS); do \
20758           $(INSTALL) -m 644 \
20759             `test -f $$i || echo $(VPATH)/`$$i \
20760             $(DESTDIR)$(includedir)/$$i; \
20761 @c $$ restore font-lock
20762         done
20763 @end example
20765 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
20766 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
20767 where @code{f.h} and @code{g.h} are plain words and are hence
20768 subject to @code{VPATH} adjustments.
20770 If the three files are in @file{../pkg/src}, the rule is run as:
20772 @example
20773 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
20774   install -m 644 \
20775      `test -f $i || echo ../pkg/src/`$i \
20776      /usr/local/include/$i; \
20777 done
20778 @end example
20780 where the two first @command{install} calls fail.  For instance,
20781 consider the @code{f.h} installation:
20783 @example
20784 install -m 644 \
20785   `test -f ../pkg/src/f.h || \
20786     echo ../pkg/src/ \
20787   `../pkg/src/f.h \
20788   /usr/local/include/../pkg/src/f.h;
20789 @end example
20791 @noindent
20792 It reduces to:
20794 @example
20795 install -m 644 \
20796   ../pkg/src/f.h \
20797   /usr/local/include/../pkg/src/f.h;
20798 @end example
20800 Note that the manual @code{VPATH} search did not cause any problems here;
20801 however this command installs @file{f.h} in an incorrect directory.
20803 Trying to quote @code{$(HEADERS)} in some way, as we did for
20804 @code{foo.c} a few makefiles ago, does not help:
20806 @example
20807 install-HEADERS: $(HEADERS)
20808         headers='$(HEADERS)'; \
20809         for i in $$headers; do \
20810           $(INSTALL) -m 644 \
20811             `test -f $$i || echo $(VPATH)/`$$i \
20812             $(DESTDIR)$(includedir)/$$i; \
20813         done
20814 @end example
20816 Now, @code{headers='$(HEADERS)'} macro-expands to:
20818 @example
20819 headers='f.h g.h h.h'
20820 @end example
20822 @noindent
20823 but @code{g.h} is still a plain word.  (As an aside, the idiom
20824 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
20825 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
20826 syntax error on @code{for i in;}.)
20828 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
20830 @example
20831 VPATH = ../pkg/src
20832 HEADERS = f.h g.h h.h
20833 install-HEADERS: $(HEADERS)
20834         headers='$(HEADERS)'; \
20835         for i in $$headers; do \
20836           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
20837           $(INSTALL) -m 644 \
20838             `test -f $$i || echo $(VPATH)/`$$i \
20839             $(DESTDIR)$(includedir)/$$i; \
20840 @c $$ restore font-lock
20841         done
20842 @end example
20844 Automake does something similar.  However the above hack works only if
20845 the files listed in @code{HEADERS} are in the current directory or a
20846 subdirectory; they should not be in an enclosing directory.  If we had
20847 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
20848 build with Tru64 @command{make}.  The reason is that not only does
20849 Tru64 @command{make} rewrite dependencies, but it also simplifies
20850 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
20851 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
20852 a leading @file{../pkg/src/} component.
20854 The following example makes the behavior of Tru64 @command{make}
20855 more apparent.
20857 @example
20858 $ @kbd{cat Makefile}
20859 VPATH = sub
20860 all: ../foo
20861         echo ../foo
20862 $ @kbd{ls}
20863 Makefile foo
20864 $ @kbd{make}
20865 echo foo
20867 @end example
20869 @noindent
20870 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
20871 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
20872 directory does not even exist, this just means that the simplification
20873 occurred before the file was checked for.)
20875 For the record here is how SunOS 4 @command{make} behaves on this
20876 example.
20878 @smallexample
20879 $ @kbd{make}
20880 make: Fatal error: Don't know how to make target `../foo'
20881 $ @kbd{mkdir sub}
20882 $ @kbd{make}
20883 echo sub/../foo
20884 sub/../foo
20885 @end smallexample
20888 @node Tru64 Directory Magic
20889 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
20890 @cindex @code{VPATH} and prerequisite directories
20891 @cindex prerequisite directories and @code{VPATH}
20893 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
20894 @command{make} creates it in the current directory.
20896 @example
20897 $ @kbd{mkdir -p foo/bar build}
20898 $ @kbd{cd build}
20899 $ @kbd{cat >Makefile <<END
20900 VPATH = ..
20901 all: foo/bar
20902 END}
20903 $ @kbd{make}
20904 mkdir foo
20905 mkdir foo/bar
20906 @end example
20908 This can yield unexpected results if a rule uses a manual @code{VPATH}
20909 search as presented before.
20911 @example
20912 VPATH = ..
20913 all : foo/bar
20914         command `test -d foo/bar || echo ../`foo/bar
20915 @end example
20917 The above @command{command} is run on the empty @file{foo/bar}
20918 directory that was created in the current directory.
20920 @node Make Target Lookup
20921 @subsection Make Target Lookup
20922 @cindex @code{VPATH}, resolving target pathnames
20924 GNU @command{make} uses a complex algorithm to decide when it
20925 should use files found via a @code{VPATH} search.  @xref{Search
20926 Algorithm, , How Directory Searches are Performed, make, The GNU Make
20927 Manual}.
20929 If a target needs to be rebuilt, GNU @command{make} discards the
20930 file name found during the @code{VPATH} search for this target, and
20931 builds the file locally using the file name given in the makefile.
20932 If a target does not need to be rebuilt, GNU @command{make} uses the
20933 file name found during the @code{VPATH} search.
20935 Other @command{make} implementations, like NetBSD @command{make}, are
20936 easier to describe: the file name found during the @code{VPATH} search
20937 is used whether the target needs to be rebuilt or not.  Therefore
20938 new files are created locally, but existing files are updated at their
20939 @code{VPATH} location.
20941 OpenBSD and FreeBSD @command{make}, however,
20942 never perform a
20943 @code{VPATH} search for a dependency that has an explicit rule.
20944 This is extremely annoying.
20946 When attempting a @code{VPATH} build for an autoconfiscated package
20947 (e.g., @code{mkdir build && cd build && ../configure}), this means
20949 @command{make} builds everything locally in the @file{build}
20950 directory, while BSD @command{make} builds new files locally and
20951 updates existing files in the source directory.
20953 @example
20954 $ @kbd{cat Makefile}
20955 VPATH = ..
20956 all: foo.x bar.x
20957 foo.x bar.x: newer.x
20958         @@echo Building $@@
20959 $ @kbd{touch ../bar.x}
20960 $ @kbd{touch ../newer.x}
20961 $ @kbd{make}        # GNU make
20962 Building foo.x
20963 Building bar.x
20964 $ @kbd{pmake}       # NetBSD make
20965 Building foo.x
20966 Building ../bar.x
20967 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20968 Building foo.x
20969 Building bar.x
20970 $ @kbd{tmake}       # Tru64 make
20971 Building foo.x
20972 Building bar.x
20973 $ @kbd{touch ../bar.x}
20974 $ @kbd{make}        # GNU make
20975 Building foo.x
20976 $ @kbd{pmake}       # NetBSD make
20977 Building foo.x
20978 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
20979 Building foo.x
20980 Building bar.x
20981 $ @kbd{tmake}       # Tru64 make
20982 Building foo.x
20983 Building bar.x
20984 @end example
20986 Note how NetBSD @command{make} updates @file{../bar.x} in its
20987 VPATH location, and how FreeBSD, OpenBSD, and Tru64
20988 @command{make} always
20989 update @file{bar.x}, even when @file{../bar.x} is up to date.
20991 Another point worth mentioning is that once GNU @command{make} has
20992 decided to ignore a @code{VPATH} file name (e.g., it ignored
20993 @file{../bar.x} in the above example) it continues to ignore it when
20994 the target occurs as a prerequisite of another rule.
20996 The following example shows that GNU @command{make} does not look up
20997 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
20998 because it ignored the @code{VPATH} result of @file{bar.x} while running
20999 the @code{bar.x: newer.x} rule.
21001 @example
21002 $ @kbd{cat Makefile}
21003 VPATH = ..
21004 all: bar.y
21005 bar.x: newer.x
21006         @@echo Building $@@
21007 .SUFFIXES: .x .y
21008 .x.y:
21009         cp $< $@@
21010 $ @kbd{touch ../bar.x}
21011 $ @kbd{touch ../newer.x}
21012 $ @kbd{make}        # GNU make
21013 Building bar.x
21014 cp bar.x bar.y
21015 cp: cannot stat `bar.x': No such file or directory
21016 make: *** [bar.y] Error 1
21017 $ @kbd{pmake}       # NetBSD make
21018 Building ../bar.x
21019 cp ../bar.x bar.y
21020 $ @kbd{rm bar.y}
21021 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21022 echo Building bar.x
21023 cp bar.x bar.y
21024 cp: cannot stat `bar.x': No such file or directory
21025 *** Error code 1
21026 $ @kbd{tmake}       # Tru64 make
21027 Building bar.x
21028 cp: bar.x: No such file or directory
21029 *** Exit 1
21030 @end example
21032 Note that if you drop away the command from the @code{bar.x: newer.x}
21033 rule, GNU @command{make} magically starts to work: it
21034 knows that @code{bar.x} hasn't been updated, therefore it doesn't
21035 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
21036 uses.  Tru64 also works, but FreeBSD and OpenBSD
21037 still don't.
21039 @example
21040 $ @kbd{cat Makefile}
21041 VPATH = ..
21042 all: bar.y
21043 bar.x: newer.x
21044 .SUFFIXES: .x .y
21045 .x.y:
21046         cp $< $@@
21047 $ @kbd{touch ../bar.x}
21048 $ @kbd{touch ../newer.x}
21049 $ @kbd{make}        # GNU make
21050 cp ../bar.x bar.y
21051 $ @kbd{rm bar.y}
21052 $ @kbd{pmake}       # NetBSD make
21053 cp ../bar.x bar.y
21054 $ @kbd{rm bar.y}
21055 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
21056 cp bar.x bar.y
21057 cp: cannot stat `bar.x': No such file or directory
21058 *** Error code 1
21059 $ @kbd{tmake}       # Tru64 make
21060 cp ../bar.x bar.y
21061 @end example
21063 It seems the sole solution that would please every @command{make}
21064 implementation is to never rely on @code{VPATH} searches for targets.
21065 In other words, @code{VPATH} should be reserved to unbuilt sources.
21068 @node Single Suffix Rules
21069 @section Single Suffix Rules and Separated Dependencies
21070 @cindex Single Suffix Inference Rule
21071 @cindex Rule, Single Suffix Inference
21072 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
21073 (@samp{.from.to:}), but which @emph{destination} suffix is empty
21074 (@samp{.from:}).
21076 @cindex Separated Dependencies
21077 @dfn{Separated dependencies} simply refers to listing the prerequisite
21078 of a target, without defining a rule.  Usually one can list on the one
21079 hand side, the rules, and on the other hand side, the dependencies.
21081 Solaris @command{make} does not support separated dependencies for
21082 targets defined by single suffix rules:
21084 @example
21085 $ @kbd{cat Makefile}
21086 .SUFFIXES: .in
21087 foo: foo.in
21088 .in:
21089         cp $< $@@
21090 $ @kbd{touch foo.in}
21091 $ @kbd{make}
21092 $ @kbd{ls}
21093 Makefile  foo.in
21094 @end example
21096 @noindent
21097 while GNU Make does:
21099 @example
21100 $ @kbd{gmake}
21101 cp foo.in foo
21102 $ @kbd{ls}
21103 Makefile  foo       foo.in
21104 @end example
21106 Note it works without the @samp{foo: foo.in} dependency.
21108 @example
21109 $ @kbd{cat Makefile}
21110 .SUFFIXES: .in
21111 .in:
21112         cp $< $@@
21113 $ @kbd{make foo}
21114 cp foo.in foo
21115 @end example
21117 @noindent
21118 and it works with double suffix inference rules:
21120 @example
21121 $ @kbd{cat Makefile}
21122 foo.out: foo.in
21123 .SUFFIXES: .in .out
21124 .in.out:
21125         cp $< $@@
21126 $ @kbd{make}
21127 cp foo.in foo.out
21128 @end example
21130 As a result, in such a case, you have to write target rules.
21132 @node Timestamps and Make
21133 @section Timestamp Resolution and Make
21134 @cindex timestamp resolution
21135 Traditionally, file timestamps had 1-second resolution, and
21136 @command{make} used those timestamps to determine whether one file was
21137 newer than the other.  However, many modern file systems have
21138 timestamps with 1-nanosecond resolution.  Some @command{make}
21139 implementations look at the entire timestamp; others ignore the
21140 fractional part, which can lead to incorrect results.  Normally this
21141 is not a problem, but in some extreme cases you may need to use tricks
21142 like @samp{sleep 1} to work around timestamp truncation bugs.
21144 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
21145 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
21146 Tools}).  Hence you should be wary of rules like this:
21148 @example
21149 dest: src
21150         cp -p src dest
21151 @end example
21153 as @file{dest} often appears to be older than @file{src} after the
21154 timestamp is truncated, and this can cause @command{make} to do
21155 needless rework the next time it is invoked.  To work around this
21156 problem, you can use a timestamp file, e.g.:
21158 @example
21159 dest-stamp: src
21160         cp -p src dest
21161         date >dest-stamp
21162 @end example
21164 Apart from timestamp resolution, there are also differences in handling
21165 equal timestamps.  HP-UX @command{make} updates targets if it has the
21166 same time stamp as one of its prerequisites, in violation of Posix rules.
21168 This can cause spurious rebuilds for repeated runs of @command{make}.
21169 This in turn can cause @command{make} to fail if it tries to rebuild
21170 generated files in a possibly read-only source tree with tools not
21171 present on the end-user machine.  Use GNU @command{make} instead.
21175 @c ======================================== Portable C and C++ Programming
21177 @node Portable C and C++
21178 @chapter Portable C and C++ Programming
21179 @cindex Portable C and C++ programming
21181 C and C++ programs often use low-level features of the underlying
21182 system, and therefore are often more difficult to make portable to other
21183 platforms.
21185 Several standards have been developed to help make your programs more
21186 portable.  If you write programs with these standards in mind, you can
21187 have greater confidence that your programs work on a wide variety
21188 of systems.
21189 @ifhtml
21190 @uref{http://@/gcc.gnu.org/@/onlinedocs/@/gcc/@/Standards.html, Language
21191 Standards Supported by GCC}
21192 @end ifhtml
21193 @ifnothtml
21194 @xref{Standards, , Language Standards Supported by
21195 GCC, gcc, Using the GNU Compiler Collection
21196 (GCC)},
21197 @end ifnothtml
21198 for a list of C-related standards.  Many programs also assume the
21199 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
21201 Some old code is written to be portable to K&R C, which predates any C
21202 standard.  K&R C compilers are no longer of practical interest, though,
21203 and the rest of section assumes at least C89, the first C standard.
21205 Program portability is a huge topic, and this section can only briefly
21206 introduce common pitfalls.  @xref{System Portability, , Portability
21207 between System Types, standards, The GNU Coding Standards}, for
21208 more information.
21210 @menu
21211 * Varieties of Unportability::  How to make your programs unportable
21212 * Integer Overflow::            When integers get too large
21213 * Preprocessor Arithmetic::     @code{#if} expression problems
21214 * Null Pointers::               Properties of null pointers
21215 * Buffer Overruns::             Subscript errors and the like
21216 * Volatile Objects::            @code{volatile} and signals
21217 * Floating Point Portability::  Portable floating-point arithmetic
21218 * Exiting Portably::            Exiting and the exit status
21219 @end menu
21221 @node Varieties of Unportability
21222 @section Varieties of Unportability
21223 @cindex portability
21225 Autoconf tests and ordinary programs often need to test what is allowed
21226 on a system, and therefore they may need to deliberately exceed the
21227 boundaries of what the standards allow, if only to see whether an
21228 optional feature is present.  When you write such a program, you should
21229 keep in mind the difference between constraints, unspecified behavior,
21230 and undefined behavior.
21232 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
21233 example constraint is that C programs must not declare a bit-field with
21234 negative width.  Tests can therefore reliably assume that programs with
21235 negative-width bit-fields are rejected by a compiler that conforms
21236 to the standard.
21238 @dfn{Unspecified behavior} is valid behavior, where the standard allows
21239 multiple possibilities.  For example, the order of evaluation of
21240 function arguments is unspecified.  Some unspecified behavior is
21241 @dfn{implementation-defined}, i.e., documented by the implementation,
21242 but since Autoconf tests cannot read the documentation they cannot
21243 distinguish between implementation-defined and other unspecified
21244 behavior.  It is common for Autoconf tests to probe implementations to
21245 determine otherwise-unspecified behavior.
21247 @dfn{Undefined behavior} is invalid behavior, where the standard allows
21248 the implementation to do anything it pleases.  For example,
21249 dereferencing a null pointer leads to undefined behavior.  If possible,
21250 test programs should avoid undefined behavior, since a program with
21251 undefined behavior might succeed on a test that should fail.
21253 The above rules apply to programs that are intended to conform to the
21254 standard.  However, strictly-conforming programs are quite rare, since
21255 the standards are so limiting.  A major goal of Autoconf is to support
21256 programs that use implementation features not described by the standard,
21257 and it is fairly common for test programs to violate the above rules, if
21258 the programs work well enough in practice.
21260 @node Integer Overflow
21261 @section Integer Overflow
21262 @cindex integer overflow
21263 @cindex overflow, signed integer
21264 @cindex signed integer overflow
21265 @cindex wraparound arithmetic
21267 In practice many portable C programs assume that signed integer overflow wraps
21268 around reliably using two's complement arithmetic.  Yet the C standard
21269 says that program behavior is undefined on overflow, and in a few cases
21270 C programs do not work on some modern implementations because their
21271 overflows do not wrap around as their authors expected.  Conversely, in
21272 signed integer remainder, the C standard requires overflow
21273 behavior that is commonly not implemented.
21275 @menu
21276 * Integer Overflow Basics::     Why integer overflow is a problem
21277 * Signed Overflow Examples::    Examples of code assuming wraparound
21278 * Optimization and Wraparound::  Optimizations that break uses of wraparound
21279 * Signed Overflow Advice::      Practical advice for signed overflow issues
21280 * Signed Integer Division::     @code{INT_MIN / -1} and @code{INT_MIN % -1}
21281 @end menu
21283 @node Integer Overflow Basics
21284 @subsection Basics of Integer Overflow
21285 @cindex integer overflow
21286 @cindex overflow, signed integer
21287 @cindex signed integer overflow
21288 @cindex wraparound arithmetic
21290 In languages like C, unsigned integer overflow reliably wraps around;
21291 e.g., @code{UINT_MAX + 1} yields zero.
21292 This is guaranteed by the C standard and is
21293 portable in practice, unless you specify aggressive,
21294 nonstandard optimization options
21295 suitable only for special applications.
21297 In contrast, the C standard says that signed integer overflow leads to
21298 undefined behavior where a program can do anything, including dumping
21299 core or overrunning a buffer.  The misbehavior can even precede the
21300 overflow.  Such an overflow can occur during addition, subtraction,
21301 multiplication, division, and left shift.
21303 Despite this requirement of the standard, many C programs and Autoconf
21304 tests assume that signed integer overflow silently wraps around modulo a
21305 power of two, using two's complement arithmetic, so long as you cast the
21306 resulting value to a signed integer type or store it into a signed
21307 integer variable.  If you use conservative optimization flags, such
21308 programs are generally portable to the vast majority of modern
21309 platforms, with a few exceptions discussed later.
21311 For historical reasons the C standard also allows implementations with
21312 ones' complement or signed magnitude arithmetic, but it is safe to
21313 assume two's complement nowadays.
21315 Also, overflow can occur when converting an out-of-range value to a
21316 signed integer type.  Here a standard implementation must define what
21317 happens, but this might include raising an exception.  In practice all
21318 known implementations support silent wraparound in this case, so you need
21319 not worry about other possibilities.
21321 @node Signed Overflow Examples
21322 @subsection Examples of Code Assuming Wraparound Overflow
21323 @cindex integer overflow
21324 @cindex overflow, signed integer
21325 @cindex signed integer overflow
21326 @cindex wraparound arithmetic
21328 There has long been a tension between what the C standard requires for
21329 signed integer overflow, and what C programs commonly assume.  The
21330 standard allows aggressive optimizations based on assumptions that
21331 overflow never occurs, but many practical C programs rely on overflow
21332 wrapping around.  These programs do not conform to the standard, but
21333 they commonly work in practice because compiler writers are
21334 understandably reluctant to implement optimizations that would break
21335 many programs, unless perhaps a user specifies aggressive optimization.
21337 The C Standard says that if a program has signed integer overflow its
21338 behavior is undefined, and the undefined behavior can even precede the
21339 overflow.  To take an extreme example:
21341 @c Inspired by Robert Dewar's example in
21342 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
21343 @example
21344 if (password == expected_password)
21345   allow_superuser_privileges ();
21346 else if (counter++ == INT_MAX)
21347   abort ();
21348 else
21349   printf ("%d password mismatches\n", counter);
21350 @end example
21352 @noindent
21353 If the @code{int} variable @code{counter} equals @code{INT_MAX},
21354 @code{counter++} must overflow and the behavior is undefined, so the C
21355 standard allows the compiler to optimize away the test against
21356 @code{INT_MAX} and the @code{abort} call.
21357 Worse, if an earlier bug in the program lets the compiler deduce that
21358 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
21359 the C standard allows the compiler to optimize away the password test
21360 and generate code that allows superuser privileges unconditionally.
21362 Despite this requirement by the standard, it has long been common for C
21363 code to assume wraparound arithmetic after signed overflow, and all
21364 known practical C implementations support some C idioms that assume
21365 wraparound signed arithmetic, even if the idioms do not conform
21366 strictly to the standard.  If your code looks like the following
21367 examples it will almost surely work with real-world compilers.
21369 Here is an example derived from the 7th Edition Unix implementation of
21370 @code{atoi} (1979-01-10):
21372 @example
21373 char *p;
21374 int f, n;
21375 @dots{}
21376 while (*p >= '0' && *p <= '9')
21377   n = n * 10 + *p++ - '0';
21378 return (f ? -n : n);
21379 @end example
21381 @noindent
21382 Even if the input string is in range, on most modern machines this has
21383 signed overflow when computing the most negative integer (the @code{-n}
21384 overflows) or a value near an extreme integer (the first @code{+}
21385 overflows).
21387 Here is another example, derived from the 7th Edition implementation of
21388 @code{rand} (1979-01-10).  Here the programmer expects both
21389 multiplication and addition to wrap on overflow:
21391 @example
21392 static long int randx = 1;
21393 @dots{}
21394 randx = randx * 1103515245 + 12345;
21395 return (randx >> 16) & 077777;
21396 @end example
21398 In the following example, derived from the GNU C Library 2.5
21399 implementation of @code{mktime} (2006-09-09), the code assumes
21400 wraparound arithmetic in @code{+} to detect signed overflow:
21402 @example
21403 time_t t, t1, t2;
21404 int sec_requested, sec_adjustment;
21405 @dots{}
21406 t1 = t + sec_requested;
21407 t2 = t1 + sec_adjustment;
21408 if (((t1 < t) != (sec_requested < 0))
21409     | ((t2 < t1) != (sec_adjustment < 0)))
21410   return -1;
21411 @end example
21413 If your code looks like these examples, it is probably safe even though
21414 it does not strictly conform to the C standard.  This might lead one to
21415 believe that one can generally assume wraparound on overflow, but that
21416 is not always true, as can be seen in the next section.
21418 @node Optimization and Wraparound
21419 @subsection Optimizations That Break Wraparound Arithmetic
21420 @cindex loop induction
21422 Compilers sometimes generate code that is incompatible with wraparound
21423 integer arithmetic.  A simple example is an algebraic simplification: a
21424 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
21425 because it assumes that @code{i * 2000} does not overflow.  The
21426 translation is not equivalent to the original when overflow occurs:
21427 e.g., in the typical case of 32-bit signed two's complement wraparound
21428 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
21429 the original expression returns @minus{}2147483 but the optimized
21430 version returns the mathematically correct value 2147484.
21432 More subtly, loop induction optimizations often exploit the undefined
21433 behavior of signed overflow.  Consider the following contrived function
21434 @code{sumc}:
21436 @example
21438 sumc (int lo, int hi)
21440   int sum = 0;
21441   int i;
21442   for (i = lo; i <= hi; i++)
21443     sum ^= i * 53;
21444   return sum;
21446 @end example
21448 @noindent
21449 To avoid multiplying by 53 each time through the loop, an optimizing
21450 compiler might internally transform @code{sumc} to the equivalent of the
21451 following:
21453 @example
21455 transformed_sumc (int lo, int hi)
21457   int sum = 0;
21458   int hic = hi * 53;
21459   int ic;
21460   for (ic = lo * 53; ic <= hic; ic += 53)
21461     sum ^= ic;
21462   return sum;
21464 @end example
21466 @noindent
21467 This transformation is allowed by the C standard, but it is invalid for
21468 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
21469 overflow in computing expressions like @code{hi * 53} can cause the
21470 expression @code{i <= hi} to yield a different value from the
21471 transformed expression @code{ic <= hic}.
21473 For this reason, compilers that use loop induction and similar
21474 techniques often do not support reliable wraparound arithmetic when a
21475 loop induction variable like @code{ic} is involved.  Since loop
21476 induction variables are generated by the compiler, and are not visible
21477 in the source code, it is not always trivial to say whether the problem
21478 affects your code.
21480 Hardly any code actually depends on wraparound arithmetic in cases like
21481 these, so in practice these loop induction optimizations are almost
21482 always useful.  However, edge cases in this area can cause problems.
21483 For example:
21485 @example
21486 int j;
21487 for (j = 1; 0 < j; j *= 2)
21488   test (j);
21489 @end example
21491 @noindent
21492 Here, the loop attempts to iterate through all powers of 2 that
21493 @code{int} can represent, but the C standard allows a compiler to
21494 optimize away the comparison and generate an infinite loop,
21495 under the argument that behavior is undefined on overflow.  As of this
21496 writing this optimization is not done by any production version of
21497 GCC with @option{-O2}, but it might be performed by other
21498 compilers, or by more aggressive GCC optimization options,
21499 and the GCC developers have not decided whether it will
21500 continue to work with GCC and @option{-O2}.
21502 @node Signed Overflow Advice
21503 @subsection Practical Advice for Signed Overflow Issues
21504 @cindex integer overflow
21505 @cindex overflow, signed integer
21506 @cindex signed integer overflow
21507 @cindex wraparound arithmetic
21509 Ideally the safest approach is to avoid signed integer overflow
21510 entirely.  For example, instead of multiplying two signed integers, you
21511 can convert them to unsigned integers, multiply the unsigned values,
21512 then test whether the result is in signed range.
21514 Rewriting code in this way will be inconvenient, though, particularly if
21515 the signed values might be negative.  Also, it may hurt
21516 performance.  Using unsigned arithmetic to check for overflow is
21517 particularly painful to do portably and efficiently when dealing with an
21518 integer type like @code{uid_t} whose width and signedness vary from
21519 platform to platform.
21521 Furthermore, many C applications pervasively assume wraparound behavior
21522 and typically it is not easy to find and remove all these assumptions.
21523 Hence it is often useful to maintain nonstandard code that assumes
21524 wraparound on overflow, instead of rewriting the code.  The rest of this
21525 section attempts to give practical advice for this situation.
21527 If your code wants to detect signed integer overflow in @code{sum = a +
21528 b}, it is generally safe to use an expression like @code{(sum < a) != (b
21529 < 0)}.
21531 If your code uses a signed loop index, make sure that the index cannot
21532 overflow, along with all signed expressions derived from the index.
21533 Here is a contrived example of problematic code with two instances of
21534 overflow.
21536 @example
21537 for (i = INT_MAX - 10; i <= INT_MAX; i++)
21538   if (i + 1 < 0)
21539     @{
21540       report_overflow ();
21541       break;
21542     @}
21543 @end example
21545 @noindent
21546 Because of the two overflows, a compiler might optimize away or
21547 transform the two comparisons in a way that is incompatible with the
21548 wraparound assumption.
21550 If your code uses an expression like @code{(i * 2000) / 1000} and you
21551 actually want the multiplication to wrap around on overflow, use
21552 unsigned arithmetic
21553 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
21555 If your code assumes wraparound behavior and you want to insulate it
21556 against any GCC optimizations that would fail to support that
21557 behavior, you should use GCC's @option{-fwrapv} option, which
21558 causes signed overflow to wrap around reliably (except for division and
21559 remainder, as discussed in the next section).
21561 If you need to port to platforms where signed integer overflow does not
21562 reliably wrap around (e.g., due to hardware overflow checking, or to
21563 highly aggressive optimizations), you should consider debugging with
21564 GCC's @option{-ftrapv} option, which causes signed overflow to
21565 raise an exception.
21567 @node Signed Integer Division
21568 @subsection Signed Integer Division and Integer Overflow
21569 @cindex division, integer
21571 Overflow in signed
21572 integer division is not always harmless: for example, on CPUs of the
21573 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
21574 which by default terminates the program.  Worse, taking the remainder
21575 of these two values typically yields the same signal on these CPUs,
21576 even though the C standard requires @code{INT_MIN % -1} to yield zero
21577 because the expression does not overflow.
21579 @node Preprocessor Arithmetic
21580 @section Preprocessor Arithmetic
21581 @cindex preprocessor arithmetic
21583 In C99 and later, preprocessor arithmetic, used for @code{#if}
21584 expressions, must
21585 be evaluated as if all signed values are of type @code{intmax_t} and all
21586 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
21587 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
21588 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
21589 @code{long long int}.  Also, some older preprocessors mishandle
21590 constants ending in @code{LL}.  To work around these problems, you can
21591 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
21592 @code{configure}-time rather than at @code{#if}-time.
21594 @node Null Pointers
21595 @section Properties of Null Pointers
21596 @cindex null pointers
21598 Most modern hosts reliably fail when you attempt to dereference a null
21599 pointer.
21601 On almost all modern hosts, null pointers use an all-bits-zero internal
21602 representation, so you can reliably use @code{memset} with 0 to set all
21603 the pointers in an array to null values.
21605 If @code{p} is a null pointer to an object type, the C expression
21606 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
21607 the standard says that it has undefined behavior.
21609 @node Buffer Overruns
21610 @section Buffer Overruns and Subscript Errors
21611 @cindex buffer overruns
21613 Buffer overruns and subscript errors are the most common dangerous
21614 errors in C programs.  They result in undefined behavior because storing
21615 outside an array typically modifies storage that is used by some other
21616 object, and most modern systems lack runtime checks to catch these
21617 errors.  Programs should not rely on buffer overruns being caught.
21619 There is one exception to the usual rule that a portable program cannot
21620 address outside an array.  In C, it is valid to compute the address just
21621 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
21622 so long as you do not dereference the resulting pointer.  But it is not
21623 valid to compute the address just before an object, e.g., @code{&a[-1]};
21624 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
21625 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
21626 reliable in general, and it is usually easy enough to avoid the
21627 potential portability problem, e.g., by allocating an extra unused array
21628 element at the start or end.
21630 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
21632 users might also consider using the @option{-fmudflap} option to catch
21633 overruns.
21635 Buffer overruns are usually caused by off-by-one errors, but there are
21636 more subtle ways to get them.
21638 Using @code{int} values to index into an array or compute array sizes
21639 causes problems on typical 64-bit hosts where an array index might
21640 be @math{2^{31}} or larger.  Index values of type @code{size_t} avoid this
21641 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
21642 are signed, and are wide enough in practice.
21644 If you add or multiply two numbers to calculate an array size, e.g.,
21645 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
21646 multiplication overflows.
21648 Many implementations of the @code{alloca} function silently misbehave
21649 and can generate buffer overflows if given sizes that are too large.
21650 The size limits are implementation dependent, but are at least 4000
21651 bytes on all platforms that we know about.
21653 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
21654 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
21655 portable code should not use them unless the inputs are known to be
21656 within certain limits.  The time-related functions can overflow their
21657 buffers if given timestamps out of range (e.g., a year less than -999
21658 or greater than 9999).  Time-related buffer overflows cannot happen with
21659 recent-enough versions of the GNU C library, but are possible
21660 with other
21661 implementations.  The @code{gets} function is the worst, since it almost
21662 invariably overflows its buffer when presented with an input line larger
21663 than the buffer.
21665 @node Volatile Objects
21666 @section Volatile Objects
21667 @cindex volatile objects
21669 The keyword @code{volatile} is often misunderstood in portable code.
21670 Its use inhibits some memory-access optimizations, but programmers often
21671 wish that it had a different meaning than it actually does.
21673 @code{volatile} was designed for code that accesses special objects like
21674 memory-mapped device registers whose contents spontaneously change.
21675 Such code is inherently low-level, and it is difficult to specify
21676 portably what @code{volatile} means in these cases.  The C standard
21677 says, ``What constitutes an access to an object that has
21678 volatile-qualified type is implementation-defined,'' so in theory each
21679 implementation is supposed to fill in the gap by documenting what
21680 @code{volatile} means for that implementation.  In practice, though,
21681 this documentation is usually absent or incomplete.
21683 One area of confusion is the distinction between objects defined with
21684 volatile types, and volatile lvalues.  From the C standard's point of
21685 view, an object defined with a volatile type has externally visible
21686 behavior.  You can think of such objects as having little oscilloscope
21687 probes attached to them, so that the user can observe some properties of
21688 accesses to them, just as the user can observe data written to output
21689 files.  However, the standard does not make it clear whether users can
21690 observe accesses by volatile lvalues to ordinary objects.  For example:
21692 @example
21693 /* Declare and access a volatile object.
21694    Accesses to X are "visible" to users.  */
21695 static int volatile x;
21696 x = 1;
21698 /* Access two ordinary objects via a volatile lvalue.
21699    It's not clear whether accesses to *P are "visible".  */
21700 int y;
21701 int *z = malloc (sizeof (int));
21702 int volatile *p;
21703 p = &y;
21704 *p = 1;
21705 p = z;
21706 *p = 1;
21707 @end example
21709 Programmers often wish that @code{volatile} meant ``Perform the memory
21710 access here and now, without merging several memory accesses, without
21711 changing the memory word size, and without reordering.''  But the C
21712 standard does not require this.  For objects defined with a volatile
21713 type, accesses must be done before the next sequence point; but
21714 otherwise merging, reordering, and word-size change is allowed.  Worse,
21715 it is not clear from the standard whether volatile lvalues provide more
21716 guarantees in general than nonvolatile lvalues, if the underlying
21717 objects are ordinary.
21719 Even when accessing objects defined with a volatile type,
21720 the C standard allows only
21721 extremely limited signal handlers: in C99 the behavior is undefined if a signal
21722 handler reads any nonlocal object, or writes to any nonlocal object
21723 whose type is not @code{sig_atomic_t volatile}, or calls any standard
21724 library function other than @code{abort}, @code{signal}, and
21725 @code{_Exit}.  Hence C compilers need not worry about a signal handler
21726 disturbing ordinary computation.  C11 and Posix allow some additional
21727 behavior in a portable signal handler, but are still quite restrictive.
21729 Some C implementations allow memory-access optimizations within each
21730 translation unit, such that actual behavior agrees with the behavior
21731 required by the standard only when calling a function in some other
21732 translation unit, and a signal handler acts like it was called from a
21733 different translation unit.  The C99 standard hints that in these
21734 implementations, objects referred to by signal handlers ``would require
21735 explicit specification of @code{volatile} storage, as well as other
21736 implementation-defined restrictions.''  But unfortunately even for this
21737 special case these other restrictions are often not documented well.
21738 This area was significantly changed in C11, and eventually implementations
21739 will probably head in the C11 direction, but this will take some time.
21740 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
21741 GNU Compiler Collection (GCC)}, for some
21742 restrictions imposed by GCC.  @xref{Defining Handlers, ,
21743 Defining Signal Handlers, libc, The GNU C Library}, for some
21744 restrictions imposed by the GNU C library.  Restrictions
21745 differ on other platforms.
21747 If possible, it is best to use a signal handler that fits within the
21748 limits imposed by the C and Posix standards.
21750 If this is not practical, you can try the following rules of thumb.  A
21751 signal handler should access only volatile lvalues, preferably lvalues
21752 that refer to objects defined with a volatile type, and should not
21753 assume that the accessed objects have an internally consistent state
21754 if they are larger than a machine word.  Furthermore, installers
21755 should employ compilers and compiler options that are commonly used
21756 for building operating system kernels, because kernels often need more
21757 from @code{volatile} than the C Standard requires, and installers who
21758 compile an application in a similar environment can sometimes benefit
21759 from the extra constraints imposed by kernels on compilers.
21760 Admittedly we are handwaving somewhat here, as there are few
21761 guarantees in this area; the rules of thumb may help to fix some bugs
21762 but there is a good chance that they will not fix them all.
21764 For @code{volatile}, C++ has the same problems that C does.
21765 Multithreaded applications have even more problems with @code{volatile},
21766 but they are beyond the scope of this section.
21768 The bottom line is that using @code{volatile} typically hurts
21769 performance but should not hurt correctness.  In some cases its use
21770 does help correctness, but these cases are often so poorly understood
21771 that all too often adding @code{volatile} to a data structure merely
21772 alleviates some symptoms of a bug while not fixing the bug in general.
21774 @node Floating Point Portability
21775 @section Floating Point Portability
21776 @cindex floating point
21778 Almost all modern systems use IEEE-754 floating point, and it is safe to
21779 assume IEEE-754 in most portable code these days.  For more information,
21780 please see David Goldberg's classic paper
21781 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
21782 Scientist Should Know About Floating-Point Arithmetic}.
21784 @node Exiting Portably
21785 @section Exiting Portably
21786 @cindex exiting portably
21788 A C or C++ program can exit with status @var{N} by returning
21789 @var{N} from the @code{main} function.  Portable programs are supposed
21790 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
21791 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
21792 fail by exiting with status 1, and test programs that assume Posix can
21793 fail by exiting with status values from 1 through 255.  Programs on
21794 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
21795 status when @code{main} returned nonzero, but ancient systems like these
21796 are no longer of practical concern.
21798 A program can also exit with status @var{N} by passing @var{N} to the
21799 @code{exit} function, and a program can fail by calling the @code{abort}
21800 function.  If a program is specialized to just some platforms, it can fail
21801 by calling functions specific to those platforms, e.g., @code{_exit}
21802 (Posix).  However, like other functions, an exit
21803 function should be declared, typically by including a header.  For
21804 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
21805 either directly or via the default includes (@pxref{Default Includes}).
21807 A program can fail due to undefined behavior such as dereferencing a null
21808 pointer, but this is not recommended as undefined behavior allows an
21809 implementation to do whatever it pleases and this includes exiting
21810 successfully.
21813 @c ================================================== Manual Configuration
21815 @node Manual Configuration
21816 @chapter Manual Configuration
21818 A few kinds of features can't be guessed automatically by running test
21819 programs.  For example, the details of the object-file format, or
21820 special options that need to be passed to the compiler or linker.  You
21821 can check for such features using ad-hoc means, such as having
21822 @command{configure} check the output of the @code{uname} program, or
21823 looking for libraries that are unique to particular systems.  However,
21824 Autoconf provides a uniform method for handling unguessable features.
21826 @menu
21827 * Specifying Target Triplets::  Specifying target triplets
21828 * Canonicalizing::              Getting the canonical system type
21829 * Using System Type::           What to do with the system type
21830 @end menu
21832 @node Specifying Target Triplets
21833 @section Specifying target triplets
21834 @cindex System type
21835 @cindex Target triplet
21836 @c This node used to be named Specifying Names.  The @anchor allows old
21837 @c links to still work.
21838 @anchor{Specifying Names}
21840 Autoconf-generated
21841 @command{configure} scripts can make decisions based on a canonical name
21842 for the system type, or @dfn{target triplet}, which has the form:
21843 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
21844 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
21846 @command{configure} can usually guess the canonical name for the type of
21847 system it's running on.  To do so it runs a script called
21848 @command{config.guess}, which infers the name using the @code{uname}
21849 command or symbols predefined by the C preprocessor.
21851 Alternately, the user can specify the system type with command line
21852 arguments to @command{configure} (@pxref{System Type}.  Doing so is
21853 necessary when
21854 cross-compiling.  In the most complex case of cross-compiling, three
21855 system types are involved.  The options to specify them are:
21857 @table @option
21858 @item --build=@var{build-type}
21859 the type of system on which the package is being configured and
21860 compiled.  It defaults to the result of running @command{config.guess}.
21861 Specifying a @var{build-type} that differs from @var{host-type} enables
21862 cross-compilation mode.
21864 @item --host=@var{host-type}
21865 the type of system on which the package runs.  By default it is the
21866 same as the build machine.  Specifying a @var{host-type} that differs
21867 from @var{build-type}, when @var{build-type} was also explicitly
21868 specified, enables cross-compilation mode.
21870 @item --target=@var{target-type}
21871 the type of system for which any compiler tools in the package
21872 produce code (rarely needed).  By default, it is the same as host.
21873 @end table
21875 If you mean to override the result of @command{config.guess}, use
21876 @option{--build}, not @option{--host}, since the latter enables
21877 cross-compilation.  For historical reasons,
21878 whenever you specify @option{--host},
21879 be sure to specify @option{--build} too; this will be fixed in the
21880 future.  So, to enter cross-compilation mode, use a command like this
21882 @example
21883 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21884 @end example
21886 @noindent
21887 Note that if you do not specify @option{--host}, @command{configure}
21888 fails if it can't run the code generated by the specified compiler.  For
21889 example, configuring as follows fails:
21891 @example
21892 ./configure CC=m68k-coff-gcc
21893 @end example
21895 When cross-compiling, @command{configure} will warn about any tools
21896 (compilers, linkers, assemblers) whose name is not prefixed with the
21897 host type.  This is an aid to users performing cross-compilation.
21898 Continuing the example above, if a cross-compiler named @command{cc} is
21899 used with a native @command{pkg-config}, then libraries found by
21900 @command{pkg-config} will likely cause subtle build failures; but using
21901 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
21902 avoids any confusion.  Avoiding the warning is as simple as creating the
21903 correct symlinks naming the cross tools.
21905 @cindex @command{config.sub}
21906 @command{configure} recognizes short aliases for many system types; for
21907 example, @samp{decstation} can be used instead of
21908 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
21909 @command{config.sub} to canonicalize system type aliases.
21911 This section deliberately omits the description of the obsolete
21912 interface; see @ref{Hosts and Cross-Compilation}.
21915 @node Canonicalizing
21916 @section Getting the Canonical System Type
21917 @cindex System type
21918 @cindex Canonical system type
21920 The following macros make the system type available to @command{configure}
21921 scripts.
21923 @ovindex build_alias
21924 @ovindex host_alias
21925 @ovindex target_alias
21927 The variables @samp{build_alias}, @samp{host_alias}, and
21928 @samp{target_alias} are always exactly the arguments of @option{--build},
21929 @option{--host}, and @option{--target}; in particular, they are left empty
21930 if the user did not use them, even if the corresponding
21931 @code{AC_CANONICAL} macro was run.  Any configure script may use these
21932 variables anywhere.  These are the variables that should be used when in
21933 interaction with the user.
21935 If you need to recognize some special environments based on their system
21936 type, run the following macros to get canonical system names.  These
21937 variables are not set before the macro call.
21939 If you use these macros, you must distribute @command{config.guess} and
21940 @command{config.sub} along with your source code.  @xref{Output}, for
21941 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
21942 to control in which directory @command{configure} looks for those scripts.
21945 @defmac AC_CANONICAL_BUILD
21946 @acindex{CANONICAL_BUILD}
21947 @ovindex build
21948 @ovindex build_cpu
21949 @ovindex build_vendor
21950 @ovindex build_os
21951 Compute the canonical build-system type variable, @code{build}, and its
21952 three individual parts @code{build_cpu}, @code{build_vendor}, and
21953 @code{build_os}.
21955 If @option{--build} was specified, then @code{build} is the
21956 canonicalization of @code{build_alias} by @command{config.sub},
21957 otherwise it is determined by the shell script @command{config.guess}.
21958 @end defmac
21960 @defmac AC_CANONICAL_HOST
21961 @acindex{CANONICAL_HOST}
21962 @ovindex host
21963 @ovindex host_cpu
21964 @ovindex host_vendor
21965 @ovindex host_os
21966 Compute the canonical host-system type variable, @code{host}, and its
21967 three individual parts @code{host_cpu}, @code{host_vendor}, and
21968 @code{host_os}.
21970 If @option{--host} was specified, then @code{host} is the
21971 canonicalization of @code{host_alias} by @command{config.sub},
21972 otherwise it defaults to @code{build}.
21973 @end defmac
21975 @defmac AC_CANONICAL_TARGET
21976 @acindex{CANONICAL_TARGET}
21977 @ovindex target
21978 @ovindex target_cpu
21979 @ovindex target_vendor
21980 @ovindex target_os
21981 Compute the canonical target-system type variable, @code{target}, and its
21982 three individual parts @code{target_cpu}, @code{target_vendor}, and
21983 @code{target_os}.
21985 If @option{--target} was specified, then @code{target} is the
21986 canonicalization of @code{target_alias} by @command{config.sub},
21987 otherwise it defaults to @code{host}.
21988 @end defmac
21990 Note that there can be artifacts due to the backward compatibility
21991 code.  @xref{Hosts and Cross-Compilation}, for more.
21993 @node Using System Type
21994 @section Using the System Type
21996 In @file{configure.ac} the system type is generally used by one or more
21997 @code{case} statements to select system-specifics.  Shell wildcards can
21998 be used to match a group of system types.
22000 For example, an extra assembler code object file could be chosen, giving
22001 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
22002 following would be used in a makefile to add the object to a
22003 program or library.
22005 @example
22006 AS_CASE([$host],
22007   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
22008   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
22009   [CYCLE_OBJ=""]
22011 AC_SUBST([CYCLE_OBJ])
22012 @end example
22014 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
22015 to select variant source files, for example optimized code for some
22016 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
22017 so some runtime capability checks may be necessary too.
22019 @example
22020 case $host in
22021   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
22022   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
22023   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
22024 esac
22025 @end example
22027 The host system type can also be used to find cross-compilation tools
22028 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
22030 The above examples all show @samp{$host}, since this is where the code
22031 is going to run.  Only rarely is it necessary to test @samp{$build}
22032 (which is where the build is being done).
22034 Whenever you're tempted to use @samp{$host} it's worth considering
22035 whether some sort of probe would be better.  New system types come along
22036 periodically or previously missing features are added.  Well-written
22037 probes can adapt themselves to such things, but hard-coded lists of
22038 names can't.  Here are some guidelines,
22040 @itemize @bullet
22041 @item
22042 Availability of libraries and library functions should always be checked
22043 by probing.
22044 @item
22045 Variant behavior of system calls is best identified with runtime tests
22046 if possible, but bug workarounds or obscure difficulties might have to
22047 be driven from @samp{$host}.
22048 @item
22049 Assembler code is inevitably highly CPU-specific and is best selected
22050 according to @samp{$host_cpu}.
22051 @item
22052 Assembler variations like underscore prefix on globals or ELF versus
22053 COFF type directives are however best determined by probing, perhaps
22054 even examining the compiler output.
22055 @end itemize
22057 @samp{$target} is for use by a package creating a compiler or similar.
22058 For ordinary packages it's meaningless and should not be used.  It
22059 indicates what the created compiler should generate code for, if it can
22060 cross-compile.  @samp{$target} generally selects various hard-coded CPU
22061 and system conventions, since usually the compiler or tools under
22062 construction themselves determine how the target works.
22065 @c ===================================================== Site Configuration.
22067 @node Site Configuration
22068 @chapter Site Configuration
22070 @command{configure} scripts support several kinds of local configuration
22071 decisions.  There are ways for users to specify where external software
22072 packages are, include or exclude optional features, install programs
22073 under modified names, and set default values for @command{configure}
22074 options.
22076 @menu
22077 * Help Formatting::             Customizing @samp{configure --help}
22078 * External Software::           Working with other optional software
22079 * Package Options::             Selecting optional features
22080 * Pretty Help Strings::         Formatting help string
22081 * Option Checking::             Controlling checking of @command{configure} options
22082 * Site Details::                Configuring site details
22083 * Transforming Names::          Changing program names when installing
22084 * Site Defaults::               Giving @command{configure} local defaults
22085 @end menu
22087 @node Help Formatting
22088 @section Controlling Help Output
22090 Users consult @samp{configure --help} to learn of configuration
22091 decisions specific to your package.  By default, @command{configure}
22092 breaks this output into sections for each type of option; within each
22093 section, help strings appear in the order @file{configure.ac} defines
22094 them:
22096 @example
22097 Optional Features:
22098   @dots{}
22099   --enable-bar            include bar
22101 Optional Packages:
22102   @dots{}
22103   --with-foo              use foo
22104 @end example
22106 @defmac AC_PRESERVE_HELP_ORDER
22107 @acindex{PRESERVE_HELP_ORDER}
22109 Request an alternate @option{--help} format, in which options of all
22110 types appear together, in the order defined.  Call this macro before any
22111 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
22113 @example
22114 Optional Features and Packages:
22115   @dots{}
22116   --enable-bar            include bar
22117   --with-foo              use foo
22118 @end example
22120 @end defmac
22122 @node External Software
22123 @section Working With External Software
22124 @cindex External software
22126 Some packages require, or can optionally use, other software packages
22127 that are already installed.  The user can give @command{configure}
22128 command line options to specify which such external software to use.
22129 The options have one of these forms:
22131 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22132 @c awful.
22133 @example
22134 --with-@var{package}@r{[}=@var{arg}@r{]}
22135 --without-@var{package}
22136 @end example
22138 For example, @option{--with-gnu-ld} means work with the GNU linker
22139 instead of some other linker.  @option{--with-x} means work with The X
22140 Window System.
22142 The user can give an argument by following the package name with
22143 @samp{=} and the argument.  Giving an argument of @samp{no} is for
22144 packages that are used by default; it says to @emph{not} use the
22145 package.  An argument that is neither @samp{yes} nor @samp{no} could
22146 include a name or number of a version of the other package, to specify
22147 more precisely which other package this program is supposed to work
22148 with.  If no argument is given, it defaults to @samp{yes}.
22149 @option{--without-@var{package}} is equivalent to
22150 @option{--with-@var{package}=no}.
22152 Normally @command{configure} scripts complain about
22153 @option{--with-@var{package}} options that they do not support.
22154 @xref{Option Checking}, for details, and for how to override the
22155 defaults.
22157 For each external software package that may be used, @file{configure.ac}
22158 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
22159 user asked to use it.  Whether each package is used or not by default,
22160 and which arguments are valid, is up to you.
22162 @anchor{AC_ARG_WITH}
22163 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
22164   @ovar{action-if-given}, @ovar{action-if-not-given})
22165 @acindex{ARG_WITH}
22166 If the user gave @command{configure} the option @option{--with-@var{package}}
22167 or @option{--without-@var{package}}, run shell commands
22168 @var{action-if-given}.  If neither option was given, run shell commands
22169 @var{action-if-not-given}.  The name @var{package} indicates another
22170 software package that this program should work with.  It should consist
22171 only of alphanumeric characters, dashes, plus signs, and dots.
22173 The option's argument is available to the shell commands
22174 @var{action-if-given} in the shell variable @code{withval}, which is
22175 actually just the value of the shell variable named
22176 @code{with_@var{package}}, with any non-alphanumeric characters in
22177 @var{package} changed into @samp{_}.  You may use that variable instead,
22178 if you wish.
22180 Note that @var{action-if-not-given} is not expanded until the point that
22181 @code{AC_ARG_WITH} was expanded.  If you need the value of
22182 @code{with_@var{package}} set to a default value by the time argument
22183 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22184 diversion (@pxref{m4_divert_text}) (if done as an argument to
22185 @code{AC_ARG_WITH}, also provide non-diverted text to avoid a shell
22186 syntax error).
22188 The argument @var{help-string} is a description of the option that
22189 looks like this:
22190 @example
22191   --with-readline         support fancy command line editing
22192 @end example
22194 @noindent
22195 @var{help-string} may be more than one line long, if more detail is
22196 needed.  Just make sure the columns line up in @samp{configure
22197 --help}.  Avoid tabs in the help string.  The easiest way to provide the
22198 proper leading whitespace is to format your @var{help-string} with the macro
22199 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22201 The following example shows how to use the @code{AC_ARG_WITH} macro in
22202 a common situation.  You want to let the user decide whether to enable
22203 support for an external library (e.g., the readline library); if the user
22204 specified neither @option{--with-readline} nor @option{--without-readline},
22205 you want to enable support for readline only if the library is available
22206 on the system.
22208 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22209 @example
22210 AC_ARG_WITH([readline],
22211   [AS_HELP_STRING([--with-readline],
22212     [support fancy command line editing @@<:@@default=check@@:>@@])],
22213   [],
22214   [: m4_divert_text([DEFAULTS], [with_readline=check])])
22216 LIBREADLINE=
22217 AS_IF([test "x$with_readline" != xno],
22218   [AC_CHECK_LIB([readline], [main],
22219     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22220      AC_DEFINE([HAVE_LIBREADLINE], [1],
22221                [Define if you have libreadline])
22222     ],
22223     [if test "x$with_readline" != xcheck; then
22224        AC_MSG_FAILURE(
22225          [--with-readline was given, but test for readline failed])
22226      fi
22227     ], -lncurses)])
22228 @end example
22230 The next example shows how to use @code{AC_ARG_WITH} to give the user the
22231 possibility to enable support for the readline library, in case it is still
22232 experimental and not well tested, and is therefore disabled by default.
22234 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22235 @example
22236 AC_ARG_WITH([readline],
22237   [AS_HELP_STRING([--with-readline],
22238     [enable experimental support for readline])],
22239   [],
22240   [with_readline=no])
22242 LIBREADLINE=
22243 AS_IF([test "x$with_readline" != xno],
22244   [AC_CHECK_LIB([readline], [main],
22245     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22246      AC_DEFINE([HAVE_LIBREADLINE], [1],
22247                [Define if you have libreadline])
22248     ],
22249     [AC_MSG_FAILURE(
22250        [--with-readline was given, but test for readline failed])],
22251     [-lncurses])])
22252 @end example
22254 The last example shows how to use @code{AC_ARG_WITH} to give the user the
22255 possibility to disable support for the readline library, given that it is
22256 an important feature and that it should be enabled by default.
22258 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
22259 @example
22260 AC_ARG_WITH([readline],
22261   [AS_HELP_STRING([--without-readline],
22262     [disable support for readline])],
22263   [],
22264   [with_readline=yes])
22266 LIBREADLINE=
22267 AS_IF([test "x$with_readline" != xno],
22268   [AC_CHECK_LIB([readline], [main],
22269     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
22270      AC_DEFINE([HAVE_LIBREADLINE], [1],
22271                [Define if you have libreadline])
22272     ],
22273     [AC_MSG_FAILURE(
22274        [readline test failed (--without-readline to disable)])],
22275     [-lncurses])])
22276 @end example
22278 These three examples can be easily adapted to the case where
22279 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
22280 @ref{Package Options}).
22281 @end defmac
22283 @node Package Options
22284 @section Choosing Package Options
22285 @cindex Package options
22286 @cindex Options, package
22288 If a software package has optional compile-time features, the user can
22289 give @command{configure} command line options to specify whether to
22290 compile them.  The options have one of these forms:
22292 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
22293 @c awful.
22294 @example
22295 --enable-@var{feature}@r{[}=@var{arg}@r{]}
22296 --disable-@var{feature}
22297 @end example
22299 These options allow users to choose which optional features to build and
22300 install.  @option{--enable-@var{feature}} options should never make a
22301 feature behave differently or cause one feature to replace another.
22302 They should only cause parts of the program to be built rather than left
22303 out.
22305 The user can give an argument by following the feature name with
22306 @samp{=} and the argument.  Giving an argument of @samp{no} requests
22307 that the feature @emph{not} be made available.  A feature with an
22308 argument looks like @option{--enable-debug=stabs}.  If no argument is
22309 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
22310 equivalent to @option{--enable-@var{feature}=no}.
22312 Normally @command{configure} scripts complain about
22313 @option{--enable-@var{package}} options that they do not support.
22314 @xref{Option Checking}, for details, and for how to override the
22315 defaults.
22317 For each optional feature, @file{configure.ac} should call
22318 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
22319 to include it.  Whether each feature is included or not by default, and
22320 which arguments are valid, is up to you.
22322 @anchor{AC_ARG_ENABLE}
22323 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
22324   @ovar{action-if-given}, @ovar{action-if-not-given})
22325 @acindex{ARG_ENABLE}
22326 If the user gave @command{configure} the option
22327 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
22328 shell commands @var{action-if-given}.  If neither option was given, run
22329 shell commands @var{action-if-not-given}.  The name @var{feature}
22330 indicates an optional user-level facility.  It should consist only of
22331 alphanumeric characters, dashes, plus signs, and dots.
22333 The option's argument is available to the shell commands
22334 @var{action-if-given} in the shell variable @code{enableval}, which is
22335 actually just the value of the shell variable named
22336 @code{enable_@var{feature}}, with any non-alphanumeric characters in
22337 @var{feature} changed into @samp{_}.  You may use that variable instead,
22338 if you wish.  The @var{help-string} argument is like that of
22339 @code{AC_ARG_WITH} (@pxref{External Software}).
22341 Note that @var{action-if-not-given} is not expanded until the point that
22342 @code{AC_ARG_ENABLE} was expanded.  If you need the value of
22343 @code{enable_@var{feature}} set to a default value by the time argument
22344 parsing is completed, use @code{m4_divert_text} to the @code{DEFAULTS}
22345 diversion (@pxref{m4_divert_text}) (if done as an argument to
22346 @code{AC_ARG_ENABLE}, also provide non-diverted text to avoid a shell
22347 syntax error).
22349 You should format your @var{help-string} with the macro
22350 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
22352 See the examples suggested with the definition of @code{AC_ARG_WITH}
22353 (@pxref{External Software}) to get an idea of possible applications of
22354 @code{AC_ARG_ENABLE}.
22355 @end defmac
22357 @node Pretty Help Strings
22358 @section Making Your Help Strings Look Pretty
22359 @cindex Help strings
22361 Properly formatting the @samp{help strings} which are used in
22362 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
22363 (@pxref{Package Options}) can be challenging.  Specifically, you want
22364 your own @samp{help strings} to line up in the appropriate columns of
22365 @samp{configure --help} just like the standard Autoconf @samp{help
22366 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
22368 @anchor{AS_HELP_STRING}
22369 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
22370   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
22371 @asindex{HELP_STRING}
22373 Expands into a help string that looks pretty when the user executes
22374 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
22375 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
22376 Options}).  The following example makes this clearer.
22378 @example
22379 AC_ARG_WITH([foo],
22380   [AS_HELP_STRING([--with-foo],
22381      [use foo (default is no)])],
22382   [use_foo=$withval],
22383   [use_foo=no])
22384 @end example
22386 Then the last few lines of @samp{configure --help} appear like
22387 this:
22389 @example
22390 --enable and --with options recognized:
22391   --with-foo              use foo (default is no)
22392 @end example
22394 Macro expansion is performed on the first argument.  However, the second
22395 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
22396 list of text to be reformatted, and is not subject to macro expansion.
22397 Since it is not expanded, it should not be double quoted.
22398 @xref{Autoconf Language}, for a more detailed explanation.
22400 The @code{AS_HELP_STRING} macro is particularly helpful when the
22401 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
22402 arguments, as shown in the following example.  Be aware that
22403 @var{left-hand-side} may not expand to unbalanced quotes,
22404 although quadrigraphs can be used.
22406 @example
22407 AC_DEFUN([MY_ARG_WITH],
22408   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
22409      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
22410                      [use $1 (default is $2)])],
22411      [use_[]$1=$withval],
22412      [use_[]$1=$2])])
22413 MY_ARG_WITH([a_b], [no])
22414 @end example
22415 @noindent
22416 Here, the last few lines of @samp{configure --help} will include:
22418 @example
22419 --enable and --with options recognized:
22420   --with-a-b              use a_b (default is no)
22421 @end example
22423 The parameters @var{indent-column} and @var{wrap-column} were introduced
22424 in Autoconf 2.62.  Generally, they should not be specified; they exist
22425 for fine-tuning of the wrapping.
22426 @example
22427 AS_HELP_STRING([--option], [description of option])
22428 @result{}  --option                description of option
22429 AS_HELP_STRING([--option], [description of option], [15], [30])
22430 @result{}  --option     description of
22431 @result{}               option
22432 @end example
22433 @end defmac
22436 @node Option Checking
22437 @section Controlling Checking of @command{configure} Options
22438 @cindex Options, Package
22440 The @command{configure} script checks its command-line options against a
22441 list of known options, like @option{--help} or @option{--config-cache}.
22442 An unknown option ordinarily indicates a mistake by the user and
22443 @command{configure} halts with an error.  However, by default unknown
22444 @option{--with-@var{package}} and @option{--enable-@var{feature}}
22445 options elicit only a warning, to support configuring entire source
22446 trees.
22448 Source trees often contain multiple packages with a top-level
22449 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
22450 (@pxref{Subdirectories}).  Because the packages generally support
22451 different @option{--with-@var{package}} and
22452 @option{--enable-@var{feature}} options, the GNU Coding
22453 Standards say they must accept unrecognized options without halting.
22454 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
22455 automatically disables the warnings.
22457 This default behavior may be modified in two ways.  First, the installer
22458 can invoke @code{configure --disable-option-checking} to disable
22459 these warnings, or invoke @code{configure --enable-option-checking=fatal}
22460 options to turn them into fatal errors, respectively.  Second, the
22461 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
22463 @defmac AC_DISABLE_OPTION_CHECKING
22464 @acindex{DISABLE_OPTION_CHECKING}
22466 By default, disable warnings related to any unrecognized
22467 @option{--with-@var{package}} or @option{--enable-@var{feature}}
22468 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
22470 The installer can override this behavior by passing
22471 @option{--enable-option-checking} (enable warnings) or
22472 @option{--enable-option-checking=fatal} (enable errors) to
22473 @command{configure}.
22474 @end defmac
22477 @node Site Details
22478 @section Configuring Site Details
22479 @cindex Site details
22481 Some software packages require complex site-specific information.  Some
22482 examples are host names to use for certain services, company names, and
22483 email addresses to contact.  Since some configuration scripts generated
22484 by Metaconfig ask for such information interactively, people sometimes
22485 wonder how to get that information in Autoconf-generated configuration
22486 scripts, which aren't interactive.
22488 Such site configuration information should be put in a file that is
22489 edited @emph{only by users}, not by programs.  The location of the file
22490 can either be based on the @code{prefix} variable, or be a standard
22491 location such as the user's home directory.  It could even be specified
22492 by an environment variable.  The programs should examine that file at
22493 runtime, rather than at compile time.  Runtime configuration is more
22494 convenient for users and makes the configuration process simpler than
22495 getting the information while configuring.  @xref{Directory Variables, ,
22496 Variables for Installation Directories, standards, The GNU Coding
22497 Standards}, for more information on where to put data files.
22499 @node Transforming Names
22500 @section Transforming Program Names When Installing
22501 @cindex Transforming program names
22502 @cindex Program names, transforming
22504 Autoconf supports changing the names of programs when installing them.
22505 In order to use these transformations, @file{configure.ac} must call the
22506 macro @code{AC_ARG_PROGRAM}.
22508 @defmac AC_ARG_PROGRAM
22509 @acindex{ARG_PROGRAM}
22510 @ovindex program_transform_name
22511 Place in output variable @code{program_transform_name} a sequence of
22512 @code{sed} commands for changing the names of installed programs.
22514 If any of the options described below are given to @command{configure},
22515 program names are transformed accordingly.  Otherwise, if
22516 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
22517 is given, the target type followed by a dash is used as a prefix.
22518 Otherwise, no program name transformation is done.
22519 @end defmac
22521 @menu
22522 * Transformation Options::      @command{configure} options to transform names
22523 * Transformation Examples::     Sample uses of transforming names
22524 * Transformation Rules::        Makefile uses of transforming names
22525 @end menu
22527 @node Transformation Options
22528 @subsection Transformation Options
22530 You can specify name transformations by giving @command{configure} these
22531 command line options:
22533 @table @option
22534 @item --program-prefix=@var{prefix}
22535 prepend @var{prefix} to the names;
22537 @item --program-suffix=@var{suffix}
22538 append @var{suffix} to the names;
22540 @item --program-transform-name=@var{expression}
22541 perform @code{sed} substitution @var{expression} on the names.
22542 @end table
22544 @node Transformation Examples
22545 @subsection Transformation Examples
22547 These transformations are useful with programs that can be part of a
22548 cross-compilation development environment.  For example, a
22549 cross-assembler running on a Sun 4 configured with
22550 @option{--target=i960-vxworks} is normally installed as
22551 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
22552 with a native Sun 4 assembler.
22554 You can force a program name to begin with @file{g}, if you don't want
22555 GNU programs installed on your system to shadow other programs with
22556 the same name.  For example, if you configure GNU @code{diff} with
22557 @option{--program-prefix=g}, then when you run @samp{make install} it is
22558 installed as @file{/usr/local/bin/gdiff}.
22560 As a more sophisticated example, you could use
22562 @example
22563 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
22564 @end example
22565 @noindent
22567 to prepend @samp{g} to most of the program names in a source tree,
22568 excepting those like @code{gdb} that already have one and those like
22569 @code{less} and @code{lesskey} that aren't GNU programs.  (That is
22570 assuming that you have a source tree containing those programs that is
22571 set up to use this feature.)
22573 One way to install multiple versions of some programs simultaneously is
22574 to append a version number to the name of one or both.  For example, if
22575 you want to keep Autoconf version 1 around for awhile, you can configure
22576 Autoconf version 2 using @option{--program-suffix=2} to install the
22577 programs as @file{/usr/local/bin/autoconf2},
22578 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
22579 that only the binaries are renamed, therefore you'd have problems with
22580 the library files which might overlap.
22582 @node Transformation Rules
22583 @subsection Transformation Rules
22585 Here is how to use the variable @code{program_transform_name} in a
22586 @file{Makefile.in}:
22588 @example
22589 PROGRAMS = cp ls rm
22590 transform = @@program_transform_name@@
22591 install:
22592         for p in $(PROGRAMS); do \
22593           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
22594                                               sed '$(transform)'`; \
22595         done
22597 uninstall:
22598         for p in $(PROGRAMS); do \
22599           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
22600 @c $$ restore font-lock
22601         done
22602 @end example
22604 It is guaranteed that @code{program_transform_name} is never empty, and
22605 that there are no useless separators.  Therefore you may safely embed
22606 @code{program_transform_name} within a sed program using @samp{;}:
22608 @example
22609 transform = @@program_transform_name@@
22610 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
22611 @end example
22613 Whether to do the transformations on documentation files (Texinfo or
22614 @code{man}) is a tricky question; there seems to be no perfect answer,
22615 due to the several reasons for name transforming.  Documentation is not
22616 usually particular to a specific architecture, and Texinfo files do not
22617 conflict with system documentation.  But they might conflict with
22618 earlier versions of the same files, and @code{man} pages sometimes do
22619 conflict with system documentation.  As a compromise, it is probably
22620 best to do name transformations on @code{man} pages but not on Texinfo
22621 manuals.
22623 @node Site Defaults
22624 @section Setting Site Defaults
22625 @cindex Site defaults
22626 @cindex config.site
22628 Autoconf-generated @command{configure} scripts allow your site to provide
22629 default values for some configuration values.  You do this by creating
22630 site- and system-wide initialization files.
22632 @evindex CONFIG_SITE
22633 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
22634 uses its value as the name of a shell script to read; it is recommended
22635 that this be an absolute file name.  Otherwise, it
22636 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
22637 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
22638 settings in machine-specific files override those in machine-independent
22639 ones in case of conflict.
22641 Site files can be arbitrary shell scripts, but only certain kinds of
22642 code are really appropriate to be in them.  Because @command{configure}
22643 reads any cache file after it has read any site files, a site file can
22644 define a default cache file to be shared between all Autoconf-generated
22645 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
22646 you set a default cache file in a site file, it is a good idea to also
22647 set the output variable @code{CC} in that site file, because the cache
22648 file is only valid for a particular compiler, but many systems have
22649 several available.
22651 You can examine or override the value set by a command line option to
22652 @command{configure} in a site file; options set shell variables that have
22653 the same names as the options, with any dashes turned into underscores.
22654 The exceptions are that @option{--without-} and @option{--disable-} options
22655 are like giving the corresponding @option{--with-} or @option{--enable-}
22656 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
22657 sets the variable @code{cache_file} to the value @samp{localcache};
22658 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
22659 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
22660 variable @code{prefix} to the value @samp{/usr}; etc.
22662 Site files are also good places to set default values for other output
22663 variables, such as @code{CFLAGS}, if you need to give them non-default
22664 values: anything you would normally do, repetitively, on the command
22665 line.  If you use non-default values for @var{prefix} or
22666 @var{exec_prefix} (wherever you locate the site file), you can set them
22667 in the site file if you specify it with the @code{CONFIG_SITE}
22668 environment variable.
22670 You can set some cache values in the site file itself.  Doing this is
22671 useful if you are cross-compiling, where it is impossible to check features
22672 that require running a test program.  You could ``prime the cache'' by
22673 setting those values correctly for that system in
22674 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
22675 variables you need to set, see the documentation of the respective
22676 Autoconf macro.  If the variables or their semantics are undocumented,
22677 you may need to look for shell variables with @samp{_cv_} in their names
22678 in the affected @command{configure} scripts, or in the Autoconf M4
22679 source code for those macros; but in that case, their name or semantics
22680 may change in a future Autoconf version.
22682 The cache file is careful to not override any variables set in the site
22683 files.  Similarly, you should not override command-line options in the
22684 site files.  Your code should check that variables such as @code{prefix}
22685 and @code{cache_file} have their default values (as set near the top of
22686 @command{configure}) before changing them.
22688 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
22689 command @samp{configure --prefix=/usr/share/local/gnu} would read this
22690 file (if @code{CONFIG_SITE} is not set to a different file).
22692 @example
22693 # /usr/share/local/gnu/share/config.site for configure
22695 # Change some defaults.
22696 test "$prefix" = NONE && prefix=/usr/share/local/gnu
22697 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
22698 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22699 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22700 test "$runstatedir" = '$@{localstatedir@}/run' && runstatedir=/run
22702 # Give Autoconf 2.x generated configure scripts a shared default
22703 # cache file for feature test results, architecture-specific.
22704 if test "$cache_file" = /dev/null; then
22705   cache_file="$prefix/var/config.cache"
22706   # A cache file is only valid for one C compiler.
22707   CC=gcc
22709 @end example
22711 @c Leave this use of "File system" rendered as one word, but
22712 @c slightly obfuscated so as not to trigger the syntax-check prohibition.
22713 @cindex File@/system Hierarchy Standard
22714 @cindex FHS
22716 Another use of @file{config.site} is for priming the directory variables
22717 @c "File system", but slightly obfuscated, as above.
22718 in a manner consistent with the File@/system Hierarchy Standard
22719 (FHS).  Once the following file is installed at
22720 @file{/usr/share/config.site}, a user can execute simply
22721 @code{./configure --prefix=/usr} to get all the directories chosen in
22722 the locations recommended by FHS.
22724 @example
22725 # /usr/share/config.site for FHS defaults when installing below /usr,
22726 # and the respective settings were not changed on the command line.
22727 if test "$prefix" = /usr; then
22728   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
22729   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
22730   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
22732 @end example
22734 @cindex @file{lib64}
22735 @cindex 64-bit libraries
22736 Likewise, on platforms where 64-bit libraries are built by default, then
22737 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
22738 it is appropriate to install @file{/usr/local/@/share/config.site}:
22740 @example
22741 # /usr/local/share/config.site for platforms that prefer
22742 # the directory /usr/local/lib64 over /usr/local/lib.
22743 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
22744 @end example
22747 @c ============================================== Running configure Scripts.
22749 @node Running configure Scripts
22750 @chapter Running @command{configure} Scripts
22751 @cindex @command{configure}
22753 Below are instructions on how to configure a package that uses a
22754 @command{configure} script, suitable for inclusion as an @file{INSTALL}
22755 file in the package.  A plain-text version of @file{INSTALL} which you
22756 may use comes with Autoconf.
22758 @menu
22759 * Basic Installation::          Instructions for typical cases
22760 * Compilers and Options::       Selecting compilers and optimization
22761 * Multiple Architectures::      Compiling for multiple architectures at once
22762 * Installation Names::          Installing in different directories
22763 * Optional Features::           Selecting optional features
22764 * Particular Systems::          Particular systems
22765 * System Type::                 Specifying the system type
22766 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
22767 * Defining Variables::          Specifying the compiler etc.
22768 * configure Invocation::        Changing how @command{configure} runs
22769 @end menu
22771 @set autoconf
22772 @include install.texi
22775 @c ============================================== config.status Invocation
22777 @node config.status Invocation
22778 @chapter config.status Invocation
22779 @cindex @command{config.status}
22781 The @command{configure} script creates a file named @file{config.status},
22782 which actually configures, @dfn{instantiates}, the template files.  It
22783 also records the configuration options that were specified when the
22784 package was last configured in case reconfiguring is needed.
22786 Synopsis:
22787 @example
22788 ./config.status @ovar{option}@dots{} @ovar{tag}@dots{}
22789 @end example
22791 It configures each @var{tag}; if none are specified, all the templates
22792 are instantiated.  A @var{tag} refers to a file or other tag associated
22793 with a configuration action, as specified by an @code{AC_CONFIG_@var{ITEMS}}
22794 macro (@pxref{Configuration Actions}).  The files must be specified
22795 without their dependencies, as in
22797 @example
22798 ./config.status foobar
22799 @end example
22801 @noindent
22804 @example
22805 ./config.status foobar:foo.in:bar.in
22806 @end example
22808 The supported options are:
22810 @table @option
22811 @item --help
22812 @itemx -h
22813 Print a summary of the command line options, the list of the template
22814 files, and exit.
22816 @item --version
22817 @itemx -V
22818 Print the version number of Autoconf and the configuration settings,
22819 and exit.
22821 @item --config
22822 Print the configuration settings in reusable way, quoted for the shell,
22823 and exit.  For example, for a debugging build that otherwise reuses the
22824 configuration from a different build directory @var{build-dir} of a
22825 package in @var{src-dir}, you could use the following:
22827 @example
22828 args=`@var{build-dir}/config.status --config`
22829 eval @var{src-dir}/configure "$args" CFLAGS=-g --srcdir=@var{src-dir}
22830 @end example
22832 @noindent
22833 Note that it may be necessary to override a @option{--srcdir} setting
22834 that was saved in the configuration, if the arguments are used in a
22835 different build directory.
22837 @item --silent
22838 @itemx --quiet
22839 @itemx -q
22840 Do not print progress messages.
22842 @item --debug
22843 @itemx -d
22844 Don't remove the temporary files.
22846 @item --file=@var{file}[:@var{template}]
22847 Require that @var{file} be instantiated as if
22848 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
22849 @var{file} and @var{template} may be @samp{-} in which case the standard
22850 output and/or standard input, respectively, is used.  If a
22851 @var{template} file name is relative, it is first looked for in the build
22852 tree, and then in the source tree.  @xref{Configuration Actions}, for
22853 more details.
22855 This option and the following ones provide one way for separately
22856 distributed packages to share the values computed by @command{configure}.
22857 Doing so can be useful if some of the packages need a superset of the
22858 features that one of them, perhaps a common library, does.  These
22859 options allow a @file{config.status} file to create files other than the
22860 ones that its @file{configure.ac} specifies, so it can be used for a
22861 different package, or for extracting a subset of values.  For example,
22863 @example
22864 echo '@@CC@@' | ./config.status --file=-
22865 @end example
22867 @noindent
22868 provides the value of @code{@@CC@@} on standard output.
22870 @item --header=@var{file}[:@var{template}]
22871 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
22873 @item --recheck
22874 Ask @file{config.status} to update itself and exit (no instantiation).
22875 This option is useful if you change @command{configure}, so that the
22876 results of some tests might be different from the previous run.  The
22877 @option{--recheck} option reruns @command{configure} with the same arguments
22878 you used before, plus the @option{--no-create} option, which prevents
22879 @command{configure} from running @file{config.status} and creating
22880 @file{Makefile} and other files, and the @option{--no-recursion} option,
22881 which prevents @command{configure} from running other @command{configure}
22882 scripts in subdirectories.  (This is so other Make rules can
22883 run @file{config.status} when it changes; @pxref{Automatic Remaking},
22884 for an example).
22885 @end table
22887 @file{config.status} checks several optional environment variables that
22888 can alter its behavior:
22890 @anchor{CONFIG_SHELL}
22891 @defvar CONFIG_SHELL
22892 @evindex CONFIG_SHELL
22893 The shell with which to run @command{configure}.  It must be
22894 Bourne-compatible, and the absolute name of the shell should be passed.
22895 The default is a shell that supports @code{LINENO} if available, and
22896 @file{/bin/sh} otherwise.
22897 @end defvar
22899 @defvar CONFIG_STATUS
22900 @evindex CONFIG_STATUS
22901 The file name to use for the shell script that records the
22902 configuration.  The default is @file{./config.status}.  This variable is
22903 useful when one package uses parts of another and the @command{configure}
22904 scripts shouldn't be merged because they are maintained separately.
22905 @end defvar
22907 You can use @file{./config.status} in your makefiles.  For example, in
22908 the dependencies given above (@pxref{Automatic Remaking}),
22909 @file{config.status} is run twice when @file{configure.ac} has changed.
22910 If that bothers you, you can make each run only regenerate the files for
22911 that rule:
22912 @example
22913 @group
22914 config.h: stamp-h
22915 stamp-h: config.h.in config.status
22916         ./config.status config.h
22917         echo > stamp-h
22919 Makefile: Makefile.in config.status
22920         ./config.status Makefile
22921 @end group
22922 @end example
22924 The calling convention of @file{config.status} has changed; see
22925 @ref{Obsolete config.status Use}, for details.
22928 @c =================================================== Obsolete Constructs
22930 @node Obsolete Constructs
22931 @chapter Obsolete Constructs
22932 @cindex Obsolete constructs
22934 Autoconf changes, and throughout the years some constructs have been
22935 obsoleted.  Most of the changes involve the macros, but in some cases
22936 the tools themselves, or even some concepts, are now considered
22937 obsolete.
22939 You may completely skip this chapter if you are new to Autoconf.  Its
22940 intention is mainly to help maintainers updating their packages by
22941 understanding how to move to more modern constructs.
22943 @menu
22944 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
22945 * acconfig Header::             Additional entries in @file{config.h.in}
22946 * autoupdate Invocation::       Automatic update of @file{configure.ac}
22947 * Obsolete Macros::             Backward compatibility macros
22948 * Autoconf 1::                  Tips for upgrading your files
22949 * Autoconf 2.13::               Some fresher tips
22950 @end menu
22952 @node Obsolete config.status Use
22953 @section Obsolete @file{config.status} Invocation
22955 @file{config.status} now supports arguments to specify the files to
22956 instantiate; see @ref{config.status Invocation}, for more details.
22957 Before, environment variables had to be used.
22959 @defvar CONFIG_COMMANDS
22960 @evindex CONFIG_COMMANDS
22961 The tags of the commands to execute.  The default is the arguments given
22962 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
22963 @file{configure.ac}.
22964 @end defvar
22966 @defvar CONFIG_FILES
22967 @evindex CONFIG_FILES
22968 The files in which to perform @samp{@@@var{variable}@@} substitutions.
22969 The default is the arguments given to @code{AC_OUTPUT} and
22970 @code{AC_CONFIG_FILES} in @file{configure.ac}.
22971 @end defvar
22973 @defvar CONFIG_HEADERS
22974 @evindex CONFIG_HEADERS
22975 The files in which to substitute C @code{#define} statements.  The
22976 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
22977 macro was not called, @file{config.status} ignores this variable.
22978 @end defvar
22980 @defvar CONFIG_LINKS
22981 @evindex CONFIG_LINKS
22982 The symbolic links to establish.  The default is the arguments given to
22983 @code{AC_CONFIG_LINKS}; if that macro was not called,
22984 @file{config.status} ignores this variable.
22985 @end defvar
22987 In @ref{config.status Invocation}, using this old interface, the example
22988 would be:
22990 @example
22991 @group
22992 config.h: stamp-h
22993 stamp-h: config.h.in config.status
22994         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
22995           CONFIG_HEADERS=config.h ./config.status
22996         echo > stamp-h
22998 Makefile: Makefile.in config.status
22999         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
23000           CONFIG_FILES=Makefile ./config.status
23001 @end group
23002 @end example
23004 @noindent
23005 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
23006 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
23007 for @code{CONFIG_COMMANDS}, etc.)
23010 @node acconfig Header
23011 @section @file{acconfig.h}
23013 @cindex @file{acconfig.h}
23014 @cindex @file{config.h.top}
23015 @cindex @file{config.h.bot}
23017 In order to produce @file{config.h.in}, @command{autoheader} needs to
23018 build or to find templates for each symbol.  Modern releases of Autoconf
23019 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
23020 Macros}), but in older releases a file, @file{acconfig.h}, contained the
23021 list of needed templates.  @command{autoheader} copied comments and
23022 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
23023 the current directory, if present.  This file used to be mandatory if
23024 you @code{AC_DEFINE} any additional symbols.
23026 Modern releases of Autoconf also provide @code{AH_TOP} and
23027 @code{AH_BOTTOM} if you need to prepend/append some information to
23028 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
23029 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
23030 @command{autoheader} copies the lines before the line containing
23031 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
23032 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
23033 @command{autoheader} copies the lines after that line to the end of the
23034 file it generates.  Either or both of those strings may be omitted.  An
23035 even older alternate way to produce the same effect in ancient versions
23036 of Autoconf is to create the files @file{@var{file}.top} (typically
23037 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
23038 directory.  If they exist, @command{autoheader} copies them to the
23039 beginning and end, respectively, of its output.
23041 In former versions of Autoconf, the files used in preparing a software
23042 package for distribution were:
23043 @example
23044 @group
23045 configure.ac --.   .------> autoconf* -----> configure
23046                +---+
23047 [aclocal.m4] --+   `---.
23048 [acsite.m4] ---'       |
23049                        +--> [autoheader*] -> [config.h.in]
23050 [acconfig.h] ----.     |
23051                  +-----'
23052 [config.h.top] --+
23053 [config.h.bot] --'
23054 @end group
23055 @end example
23057 Using only the @code{AH_} macros, @file{configure.ac} should be
23058 self-contained, and should not depend upon @file{acconfig.h} etc.
23061 @node autoupdate Invocation
23062 @section Using @command{autoupdate} to Modernize @file{configure.ac}
23063 @cindex @command{autoupdate}
23065 The @command{autoupdate} program updates a @file{configure.ac} file that
23066 calls Autoconf macros by their old names to use the current macro names.
23067 In version 2 of Autoconf, most of the macros were renamed to use a more
23068 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
23069 description of the new scheme.  Although the old names still work
23070 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
23071 new names), you can make your @file{configure.ac} files more readable
23072 and make it easier to use the current Autoconf documentation if you
23073 update them to use the new macro names.
23075 @evindex SIMPLE_BACKUP_SUFFIX
23076 If given no arguments, @command{autoupdate} updates @file{configure.ac},
23077 backing up the original version with the suffix @file{~} (or the value
23078 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
23079 set).  If you give @command{autoupdate} an argument, it reads that file
23080 instead of @file{configure.ac} and writes the updated file to the
23081 standard output.
23083 @noindent
23084 @command{autoupdate} accepts the following options:
23086 @table @option
23087 @item --help
23088 @itemx -h
23089 Print a summary of the command line options and exit.
23091 @item --version
23092 @itemx -V
23093 Print the version number of Autoconf and exit.
23095 @item --verbose
23096 @itemx -v
23097 Report processing steps.
23099 @item --debug
23100 @itemx -d
23101 Don't remove the temporary files.
23103 @item --force
23104 @itemx -f
23105 Force the update even if the file has not changed.  Disregard the cache.
23107 @item --include=@var{dir}
23108 @itemx -I @var{dir}
23109 Also look for input files in @var{dir}.  Multiple invocations accumulate.
23110 Directories are browsed from last to first.
23112 @item --prepend-include=@var{dir}
23113 @itemx -B @var{dir}
23114 Prepend directory @var{dir} to the search path.  This is used to include
23115 the language-specific files before any third-party macros.
23116 @end table
23118 @node Obsolete Macros
23119 @section Obsolete Macros
23121 Several macros are obsoleted in Autoconf, for various reasons (typically
23122 they failed to quote properly, couldn't be extended for more recent
23123 issues, etc.).  They are still supported, but deprecated: their use
23124 should be avoided.
23126 During the jump from Autoconf version 1 to version 2, most of the
23127 macros were renamed to use a more uniform and descriptive naming scheme,
23128 but their signature did not change.  @xref{Macro Names}, for a
23129 description of the new naming scheme.  Below, if there is just the mapping
23130 from old names to new names for these macros, the reader is invited to
23131 refer to the definition of the new macro for the signature and the
23132 description.
23134 @defmac AC_AIX
23135 @acindex{AIX}
23136 @cvindex _ALL_SOURCE
23137 This macro is a platform-specific subset of
23138 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23139 @end defmac
23141 @defmac AC_ALLOCA
23142 @acindex{ALLOCA}
23143 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
23144 @end defmac
23146 @defmac AC_ARG_ARRAY
23147 @acindex{ARG_ARRAY}
23148 Removed because of limited usefulness.
23149 @end defmac
23151 @defmac AC_C_CROSS
23152 @acindex{C_CROSS}
23153 This macro is obsolete; it does nothing.
23154 @end defmac
23156 @defmac AC_C_LONG_DOUBLE
23157 @acindex{C_LONG_DOUBLE}
23158 @cvindex HAVE_LONG_DOUBLE
23159 If the C compiler supports a working @code{long double} type with more
23160 range or precision than the @code{double} type, define
23161 @code{HAVE_LONG_DOUBLE}.
23163 You should use @code{AC_TYPE_LONG_DOUBLE} or
23164 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23165 @end defmac
23167 @defmac AC_CANONICAL_SYSTEM
23168 @acindex{CANONICAL_SYSTEM}
23169 Determine the system type and set output variables to the names of the
23170 canonical system types.  @xref{Canonicalizing}, for details about the
23171 variables this macro sets.
23173 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
23174 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
23175 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
23176 other macros (@pxref{Canonicalizing}).
23177 @end defmac
23179 @defmac AC_CHAR_UNSIGNED
23180 @acindex{CHAR_UNSIGNED}
23181 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
23182 @end defmac
23184 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
23185 @acindex{CHECK_TYPE}
23186 Autoconf, up to 2.13, used to provide this version of
23187 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
23188 it is a member of the @code{CHECK} clan, it does
23189 more than just checking.  Secondly, missing types are defined
23190 using @code{#define}, not @code{typedef}, and this can lead to
23191 problems in the case of pointer types.
23193 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
23194 @ref{Generic Types}, for the description of the current macro.
23196 If the type @var{type} is not defined, define it to be the C (or C++)
23197 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
23199 This macro is equivalent to:
23201 @example
23202 AC_CHECK_TYPE([@var{type}], [],
23203   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
23204      [Define to `@var{default}'
23205       if <sys/types.h> does not define.])])
23206 @end example
23208 In order to keep backward compatibility, the two versions of
23209 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
23211 @enumerate
23212 @item
23213 If there are three or four arguments, the modern version is used.
23215 @item
23216 If the second argument appears to be a C or C++ type, then the
23217 obsolete version is used.  This happens if the argument is a C or C++
23218 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
23219 followed by one of @samp{[(* } and then by a string of zero or more
23220 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
23222 @item
23223 If the second argument is spelled with the alphabet of valid C and C++
23224 types, the user is warned and the modern version is used.
23226 @item
23227 Otherwise, the modern version is used.
23228 @end enumerate
23230 @noindent
23231 You are encouraged either to use a valid builtin type, or to use the
23232 equivalent modern code (see above), or better yet, to use
23233 @code{AC_CHECK_TYPES} together with
23235 @example
23236 #ifndef HAVE_LOFF_T
23237 typedef loff_t off_t;
23238 #endif
23239 @end example
23240 @end defmac
23241 @c end of AC_CHECK_TYPE
23243 @defmac AC_CHECKING (@var{feature-description})
23244 @acindex{CHECKING}
23245 Same as
23247 @example
23248 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
23249 @end example
23251 @noindent
23252 @xref{AC_MSG_NOTICE}.
23253 @end defmac
23255 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
23256   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
23257 @acindex{COMPILE_CHECK}
23258 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
23259 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
23260 addition that it prints @samp{checking for @var{echo-text}} to the
23261 standard output first, if @var{echo-text} is non-empty.  Use
23262 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
23263 messages (@pxref{Printing Messages}).
23264 @end defmac
23266 @defmac AC_CONST
23267 @acindex{CONST}
23268 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
23269 @end defmac
23271 @defmac AC_CROSS_CHECK
23272 @acindex{CROSS_CHECK}
23273 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
23274 @code{:-)}.
23275 @end defmac
23277 @defmac AC_CYGWIN
23278 @acindex{CYGWIN}
23279 @evindex CYGWIN
23280 Check for the Cygwin environment in which case the shell variable
23281 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
23282 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
23283 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
23285 @example
23286 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
23287 case $host_os in
23288   *cygwin* ) CYGWIN=yes;;
23289          * ) CYGWIN=no;;
23290 esac
23291 @end example
23293 Beware that the variable @env{CYGWIN} has a special meaning when
23294 running Cygwin, and should not be changed.  That's yet another reason
23295 not to use this macro.
23296 @end defmac
23298 @defmac AC_DECL_SYS_SIGLIST
23299 @acindex{DECL_SYS_SIGLIST}
23300 @cvindex SYS_SIGLIST_DECLARED
23301 Same as:
23303 @example
23304 AC_CHECK_DECLS([sys_siglist], [], [],
23305 [#include <signal.h>
23306 /* NetBSD declares sys_siglist in unistd.h.  */
23307 #ifdef HAVE_UNISTD_H
23308 # include <unistd.h>
23309 #endif
23311 @end example
23313 @noindent
23314 @xref{AC_CHECK_DECLS}.
23315 @end defmac
23317 @defmac AC_DECL_YYTEXT
23318 @acindex{DECL_YYTEXT}
23319 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
23320 @end defmac
23322 @defmac AC_DIR_HEADER
23323 @acindex{DIR_HEADER}
23324 @cvindex DIRENT
23325 @cvindex SYSNDIR
23326 @cvindex SYSDIR
23327 @cvindex NDIR
23328 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
23329 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
23330 (@pxref{AC_HEADER_DIRENT}),
23331 but defines a different set of C preprocessor macros to indicate which
23332 header file is found:
23334 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
23335 @item Header            @tab Old Symbol     @tab New Symbol
23336 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
23337 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
23338 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
23339 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
23340 @end multitable
23341 @end defmac
23343 @defmac AC_DYNIX_SEQ
23344 @acindex{DYNIX_SEQ}
23345 If on DYNIX/ptx, add @option{-lseq} to output variable
23346 @code{LIBS}.  This macro used to be defined as
23348 @example
23349 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
23350 @end example
23352 @noindent
23353 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
23354 @end defmac
23356 @defmac AC_EXEEXT
23357 @acindex{EXEEXT}
23358 @ovindex EXEEXT
23359 Defined the output variable @code{EXEEXT} based on the output of the
23360 compiler, which is now done automatically.  Typically set to empty
23361 string if Posix and @samp{.exe} if a DOS variant.
23362 @end defmac
23364 @defmac AC_EMXOS2
23365 @acindex{EMXOS2}
23366 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
23367 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
23368 check the nature of the host is using @code{AC_CANONICAL_HOST}
23369 (@pxref{Canonicalizing}).
23370 @end defmac
23372 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
23373   @ovar{action-if-not-given})
23374 @acindex{ENABLE}
23375 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
23376 support providing a help string (@pxref{AC_ARG_ENABLE}).
23377 @end defmac
23379 @defmac AC_ERROR
23380 @acindex{ERROR}
23381 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
23382 @end defmac
23384 @defmac AC_FIND_X
23385 @acindex{FIND_X}
23386 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
23387 @end defmac
23389 @defmac AC_FIND_XTRA
23390 @acindex{FIND_XTRA}
23391 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
23392 @end defmac
23394 @defmac AC_FOREACH
23395 @acindex{FOREACH}
23396 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
23397 @end defmac
23399 @defmac AC_FUNC_CHECK
23400 @acindex{FUNC_CHECK}
23401 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
23402 @end defmac
23404 @anchor{AC_FUNC_SETVBUF_REVERSED}
23405 @defmac AC_FUNC_SETVBUF_REVERSED
23406 @acindex{FUNC_SETVBUF_REVERSED}
23407 @cvindex SETVBUF_REVERSED
23408 @c @fuindex setvbuf
23409 @prindex @code{setvbuf}
23410 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
23411 the buffering type as its second argument and the buffer pointer as the
23412 third, instead of the other way around, and defined
23413 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
23414 were those based on SVR2, which became obsolete in 1987, and the macro
23415 is no longer needed.
23416 @end defmac
23418 @defmac AC_FUNC_WAIT3
23419 @acindex{FUNC_WAIT3}
23420 @cvindex HAVE_WAIT3
23421 @c @fuindex wait3
23422 @prindex @code{wait3}
23423 If @code{wait3} is found and fills in the contents of its third argument
23424 (a @samp{struct rusage *}), which HP-UX does not do, define
23425 @code{HAVE_WAIT3}.
23427 These days portable programs should use @code{waitpid}, not
23428 @code{wait3}, as @code{wait3} has been removed from Posix.
23429 @end defmac
23431 @defmac AC_GCC_TRADITIONAL
23432 @acindex{GCC_TRADITIONAL}
23433 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
23434 @end defmac
23436 @defmac AC_GETGROUPS_T
23437 @acindex{GETGROUPS_T}
23438 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
23439 @end defmac
23441 @defmac AC_GETLOADAVG
23442 @acindex{GETLOADAVG}
23443 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
23444 @end defmac
23446 @defmac AC_GNU_SOURCE
23447 @acindex{GNU_SOURCE}
23448 @cvindex _GNU_SOURCE
23449 This macro is a platform-specific subset of
23450 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23451 @end defmac
23453 @defmac AC_HAVE_FUNCS
23454 @acindex{HAVE_FUNCS}
23455 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
23456 @end defmac
23458 @defmac AC_HAVE_HEADERS
23459 @acindex{HAVE_HEADERS}
23460 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
23461 @end defmac
23463 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
23464   @ovar{action-if-not-found}, @ovar{other-libraries})
23465 @acindex{HAVE_LIBRARY}
23466 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
23467 @var{function} argument of @code{main}.  In addition, @var{library} can
23468 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
23469 all of those cases, the compiler is passed @option{-lfoo}.  However,
23470 @var{library} cannot be a shell variable; it must be a literal name.
23471 @xref{AC_CHECK_LIB}.
23472 @end defmac
23474 @defmac AC_HAVE_POUNDBANG
23475 @acindex{HAVE_POUNDBANG}
23476 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
23477 @end defmac
23479 @defmac AC_HEADER_CHECK
23480 @acindex{HEADER_CHECK}
23481 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
23482 @end defmac
23484 @defmac AC_HEADER_EGREP
23485 @acindex{HEADER_EGREP}
23486 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
23487 @end defmac
23489 @anchor{AC_HEADER_TIME}
23490 @defmac AC_HEADER_TIME
23491 @acindex{HEADER_TIME}
23492 @cvindex TIME_WITH_SYS_TIME
23493 @hdrindex{time.h}
23494 @hdrindex{sys/time.h}
23495 @caindex header_time
23496 This macro used to check whether it was possible to include
23497 @file{time.h} and @file{sys/time.h} in the same source file,
23498 defining @code{TIME_WITH_SYS_TIME} if so.
23500 Nowadays, it is equivalent to @samp{AC_CHECK_HEADERS([sys/time.h])},
23501 although it does still define @code{TIME_WITH_SYS_TIME} for
23502 compatibility's sake.  @file{time.h} is universally present, and the
23503 systems on which @file{sys/time.h} conflicted with @file{time.h} are
23504 obsolete.
23505 @end defmac
23507 @defmac AC_HELP_STRING
23508 @acindex{HELP_STRING}
23509 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
23510 @end defmac
23512 @defmac AC_INIT (@var{unique-file-in-source-dir})
23513 @acindex{INIT}
23514 Formerly @code{AC_INIT} used to have a single argument, and was
23515 equivalent to:
23517 @example
23518 AC_INIT
23519 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
23520 @end example
23521 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
23522 @end defmac
23524 @defmac AC_INLINE
23525 @acindex{INLINE}
23526 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
23527 @end defmac
23529 @defmac AC_INT_16_BITS
23530 @acindex{INT_16_BITS}
23531 @cvindex INT_16_BITS
23532 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
23533 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
23534 @end defmac
23536 @defmac AC_IRIX_SUN
23537 @acindex{IRIX_SUN}
23538 If on IRIX (Silicon Graphics Unix), add @option{-lsun} to output
23539 @code{LIBS}.  If you were using it to get @code{getmntent}, use
23540 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
23541 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
23542 getpwnam)}.  Up to Autoconf 2.13, it used to be
23544 @example
23545 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
23546 @end example
23548 @noindent
23549 now it is defined as
23551 @example
23552 AC_FUNC_GETMNTENT
23553 AC_CHECK_LIB([sun], [getpwnam])
23554 @end example
23556 @noindent
23557 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
23558 @end defmac
23560 @defmac AC_ISC_POSIX
23561 @acindex{ISC_POSIX}
23562 @ovindex LIBS
23563 This macro adds @option{-lcposix} to output variable @code{LIBS} if
23564 necessary for Posix facilities.  Sun dropped support for the obsolete
23565 INTERACTIVE Systems Corporation Unix on 2006-07-23.  New programs
23566 need not use this macro.  It is implemented as
23567 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
23568 @end defmac
23570 @defmac AC_LANG_C
23571 @acindex{LANG_C}
23572 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
23573 @end defmac
23575 @defmac AC_LANG_CPLUSPLUS
23576 @acindex{LANG_CPLUSPLUS}
23577 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
23578 @end defmac
23580 @defmac AC_LANG_FORTRAN77
23581 @acindex{LANG_FORTRAN77}
23582 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
23583 @end defmac
23585 @defmac AC_LANG_RESTORE
23586 @acindex{LANG_RESTORE}
23587 Select the @var{language} that is saved on the top of the stack, as set
23588 by @code{AC_LANG_SAVE}, remove it from the stack, and call
23589 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
23590 preferred way to change languages.
23591 @end defmac
23593 @defmac AC_LANG_SAVE
23594 @acindex{LANG_SAVE}
23595 Remember the current language (as set by @code{AC_LANG}) on a stack.
23596 The current language does not change.  @code{AC_LANG_PUSH} is preferred
23597 (@pxref{AC_LANG_PUSH}).
23598 @end defmac
23600 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
23601 @acindex{LINK_FILES}
23602 This is an obsolete version of @code{AC_CONFIG_LINKS}
23603 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
23605 @example
23606 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
23607               host.h            object.h)
23608 @end example
23610 @noindent
23613 @example
23614 AC_CONFIG_LINKS([host.h:config/$machine.h
23615                 object.h:config/$obj_format.h])
23616 @end example
23617 @end defmac
23619 @defmac AC_LN_S
23620 @acindex{LN_S}
23621 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
23622 @end defmac
23624 @defmac AC_LONG_64_BITS
23625 @acindex{LONG_64_BITS}
23626 @cvindex LONG_64_BITS
23627 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
23628 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
23629 (@pxref{AC_CHECK_SIZEOF}).
23630 @end defmac
23632 @defmac AC_LONG_DOUBLE
23633 @acindex{LONG_DOUBLE}
23634 If the C compiler supports a working @code{long double} type with more
23635 range or precision than the @code{double} type, define
23636 @code{HAVE_LONG_DOUBLE}.
23638 You should use @code{AC_TYPE_LONG_DOUBLE} or
23639 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
23640 @end defmac
23642 @defmac AC_LONG_FILE_NAMES
23643 @acindex{LONG_FILE_NAMES}
23644 Replaced by
23645 @example
23646 AC_SYS_LONG_FILE_NAMES
23647 @end example
23648 @noindent
23649 @xref{AC_SYS_LONG_FILE_NAMES}.
23650 @end defmac
23652 @defmac AC_MAJOR_HEADER
23653 @acindex{MAJOR_HEADER}
23654 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
23655 @end defmac
23657 @defmac AC_MEMORY_H
23658 @acindex{MEMORY_H}
23659 @cvindex NEED_MEMORY_H
23660 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
23661 defined in @file{memory.h}.  Today it is equivalent to
23662 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
23663 your code to get the @code{mem} functions from @file{string.h} instead.
23664 @end defmac
23666 @defmac AC_MINGW32
23667 @acindex{MINGW32}
23668 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
23669 environment and sets @code{MINGW32}.  Don't use this macro, the
23670 dignified means to check the nature of the host is using
23671 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
23672 @end defmac
23674 @defmac AC_MINIX
23675 @acindex{MINIX}
23676 @cvindex _MINIX
23677 @cvindex _POSIX_SOURCE
23678 @cvindex _POSIX_1_SOURCE
23679 This macro is a platform-specific subset of
23680 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
23681 @end defmac
23683 @defmac AC_MINUS_C_MINUS_O
23684 @acindex{MINUS_C_MINUS_O}
23685 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
23686 @end defmac
23688 @defmac AC_MMAP
23689 @acindex{MMAP}
23690 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
23691 @end defmac
23693 @defmac AC_MODE_T
23694 @acindex{MODE_T}
23695 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
23696 @end defmac
23698 @defmac AC_OBJEXT
23699 @acindex{OBJEXT}
23700 @ovindex OBJEXT
23701 Defined the output variable @code{OBJEXT} based on the output of the
23702 compiler, after .c files have been excluded.  Typically set to @samp{o}
23703 if Posix, @samp{obj} if a DOS variant.
23704 Now the compiler checking macros handle
23705 this automatically.
23706 @end defmac
23708 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
23709 @acindex{OBSOLETE}
23710 Make M4 print a message to the standard error output warning that
23711 @var{this-macro-name} is obsolete, and giving the file and line number
23712 where it was called.  @var{this-macro-name} should be the name of the
23713 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
23714 it is printed at the end of the warning message; for example, it can be
23715 a suggestion for what to use instead of @var{this-macro-name}.
23717 For instance
23719 @example
23720 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
23721 @end example
23723 @noindent
23724 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
23725 services to the user (@pxref{AU_DEFUN}).
23726 @end defmac
23728 @defmac AC_OFF_T
23729 @acindex{OFF_T}
23730 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
23731 @end defmac
23733 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
23734 @acindex{OUTPUT}
23735 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
23736 interface is equivalent to:
23738 @example
23739 @group
23740 AC_CONFIG_FILES(@var{file}@dots{})
23741 AC_CONFIG_COMMANDS([default],
23742                    @var{extra-cmds}, @var{init-cmds})
23743 AC_OUTPUT
23744 @end group
23745 @end example
23747 @noindent
23748 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
23749 @end defmac
23751 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
23752 @acindex{OUTPUT_COMMANDS}
23753 Specify additional shell commands to run at the end of
23754 @file{config.status}, and shell commands to initialize any variables
23755 from @command{configure}.  This macro may be called multiple times.  It is
23756 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
23758 Here is an unrealistic example:
23760 @example
23761 fubar=27
23762 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
23763                    [fubar=$fubar])
23764 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
23765                    [echo init bit])
23766 @end example
23768 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
23769 additional key, an important difference is that
23770 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
23771 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
23772 can safely be given macro calls as arguments:
23774 @example
23775 AC_CONFIG_COMMANDS(foo, [my_FOO()])
23776 @end example
23778 @noindent
23779 Conversely, where one level of quoting was enough for literal strings
23780 with @code{AC_OUTPUT_COMMANDS}, you need two with
23781 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
23783 @example
23784 @group
23785 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
23786 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
23787 @end group
23788 @end example
23789 @end defmac
23791 @defmac AC_PID_T
23792 @acindex{PID_T}
23793 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
23794 @end defmac
23796 @defmac AC_PREFIX
23797 @acindex{PREFIX}
23798 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
23799 @end defmac
23801 @defmac AC_PROG_CC_C89
23802 @acindex{PROG_CC_C89}
23803 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23804 @end defmac
23806 @defmac AC_PROG_CC_C99
23807 @acindex{PROG_CC_C99}
23808 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23809 @end defmac
23811 @defmac AC_PROG_CC_STDC
23812 @acindex{PROG_CC_STDC}
23813 Now done by @code{AC_PROG_CC} (@pxref{AC_PROG_CC}).
23814 @end defmac
23816 @defmac AC_PROGRAMS_CHECK
23817 @acindex{PROGRAMS_CHECK}
23818 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
23819 @end defmac
23821 @defmac AC_PROGRAMS_PATH
23822 @acindex{PROGRAMS_PATH}
23823 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
23824 @end defmac
23826 @defmac AC_PROGRAM_CHECK
23827 @acindex{PROGRAM_CHECK}
23828 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
23829 @end defmac
23831 @defmac AC_PROGRAM_EGREP
23832 @acindex{PROGRAM_EGREP}
23833 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
23834 @end defmac
23836 @defmac AC_PROGRAM_PATH
23837 @acindex{PROGRAM_PATH}
23838 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
23839 @end defmac
23841 @defmac AC_REMOTE_TAPE
23842 @acindex{REMOTE_TAPE}
23843 Removed because of limited usefulness.
23844 @end defmac
23846 @defmac AC_RESTARTABLE_SYSCALLS
23847 @acindex{RESTARTABLE_SYSCALLS}
23848 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
23849 these days portable programs should use @code{sigaction} with
23850 @code{SA_RESTART} if they want restartable system calls.  They should
23851 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23852 system call is restartable is a dynamic issue, not a configuration-time
23853 issue.
23854 @end defmac
23856 @defmac AC_RETSIGTYPE
23857 @acindex{RETSIGTYPE}
23858 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
23859 is obsolete when assuming C89 or better.
23860 @end defmac
23862 @defmac AC_RSH
23863 @acindex{RSH}
23864 Removed because of limited usefulness.
23865 @end defmac
23867 @defmac AC_SCO_INTL
23868 @acindex{SCO_INTL}
23869 @ovindex LIBS
23870 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
23871 macro used to do this:
23873 @example
23874 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
23875 @end example
23877 @noindent
23878 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
23879 @end defmac
23881 @defmac AC_SETVBUF_REVERSED
23882 @acindex{SETVBUF_REVERSED}
23883 Replaced by
23884 @example
23885 AC_FUNC_SETVBUF_REVERSED
23886 @end example
23887 @noindent
23888 @xref{AC_FUNC_SETVBUF_REVERSED}.
23889 @end defmac
23891 @defmac AC_SET_MAKE
23892 @acindex{SET_MAKE}
23893 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
23894 @end defmac
23896 @defmac AC_SIZEOF_TYPE
23897 @acindex{SIZEOF_TYPE}
23898 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
23899 @end defmac
23901 @defmac AC_SIZE_T
23902 @acindex{SIZE_T}
23903 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
23904 @end defmac
23906 @defmac AC_STAT_MACROS_BROKEN
23907 @acindex{STAT_MACROS_BROKEN}
23908 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
23909 @end defmac
23911 @defmac AC_STDC_HEADERS
23912 @acindex{STDC_HEADERS}
23913 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}), which
23914 is itself obsolete.  Nowadays it is safe to assume the facilities of C90
23915 exist.
23916 @end defmac
23918 @defmac AC_STRCOLL
23919 @acindex{STRCOLL}
23920 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
23921 @end defmac
23923 @defmac AC_STRUCT_ST_BLKSIZE
23924 @acindex{STRUCT_ST_BLKSIZE}
23925 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
23926 @cvindex HAVE_ST_BLKSIZE
23927 If @code{struct stat} contains an @code{st_blksize} member, define
23928 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
23929 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
23930 the future.  This macro is obsoleted, and should be replaced by
23932 @example
23933 AC_CHECK_MEMBERS([struct stat.st_blksize])
23934 @end example
23935 @noindent
23936 @xref{AC_CHECK_MEMBERS}.
23937 @end defmac
23939 @defmac AC_STRUCT_ST_RDEV
23940 @acindex{STRUCT_ST_RDEV}
23941 @cvindex HAVE_ST_RDEV
23942 @cvindex HAVE_STRUCT_STAT_ST_RDEV
23943 If @code{struct stat} contains an @code{st_rdev} member, define
23944 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
23945 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
23946 in the future.  Actually, even the new macro is obsolete and should be
23947 replaced by:
23948 @example
23949 AC_CHECK_MEMBERS([struct stat.st_rdev])
23950 @end example
23951 @noindent
23952 @xref{AC_CHECK_MEMBERS}.
23953 @end defmac
23955 @defmac AC_ST_BLKSIZE
23956 @acindex{ST_BLKSIZE}
23957 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23958 @end defmac
23960 @defmac AC_ST_BLOCKS
23961 @acindex{ST_BLOCKS}
23962 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
23963 @end defmac
23965 @defmac AC_ST_RDEV
23966 @acindex{ST_RDEV}
23967 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
23968 @end defmac
23970 @defmac AC_SYS_RESTARTABLE_SYSCALLS
23971 @acindex{SYS_RESTARTABLE_SYSCALLS}
23972 @cvindex HAVE_RESTARTABLE_SYSCALLS
23973 If the system automatically restarts a system call that is interrupted
23974 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
23975 not check whether system calls are restarted in general---it checks whether a
23976 signal handler installed with @code{signal} (but not @code{sigaction})
23977 causes system calls to be restarted.  It does not check whether system calls
23978 can be restarted when interrupted by signals that have no handler.
23980 These days portable programs should use @code{sigaction} with
23981 @code{SA_RESTART} if they want restartable system calls.  They should
23982 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
23983 system call is restartable is a dynamic issue, not a configuration-time
23984 issue.
23985 @end defmac
23987 @defmac AC_SYS_SIGLIST_DECLARED
23988 @acindex{SYS_SIGLIST_DECLARED}
23989 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
23990 name is obsolete, as the same functionality is now achieved via
23991 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
23992 @end defmac
23994 @defmac AC_TEST_CPP
23995 @acindex{TEST_CPP}
23996 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
23997 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
23998 @end defmac
24000 @defmac AC_TEST_PROGRAM
24001 @acindex{TEST_PROGRAM}
24002 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
24003 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
24004 @end defmac
24006 @defmac AC_TIMEZONE
24007 @acindex{TIMEZONE}
24008 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
24009 @end defmac
24011 @defmac AC_TIME_WITH_SYS_TIME
24012 @acindex{TIME_WITH_SYS_TIME}
24013 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}), which is
24014 itself obsolete; nowadays one need only do
24015 @samp{AC_CHECK_HEADERS([sys/time.h])}.
24016 @end defmac
24018 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
24019   @ovar{action-if-true}, @ovar{action-if-false})
24020 @acindex{TRY_COMPILE}
24021 Same as:
24023 @example
24024 AC_COMPILE_IFELSE(
24025   [AC_LANG_PROGRAM([[@var{includes}]],
24026      [[@var{function-body}]])],
24027   [@var{action-if-true}],
24028   [@var{action-if-false}])
24029 @end example
24031 @noindent
24032 @xref{Running the Compiler}.
24034 This macro double quotes both @var{includes} and @var{function-body}.
24036 For C and C++, @var{includes} is any @code{#include} statements needed
24037 by the code in @var{function-body} (@var{includes} is ignored if
24038 the currently selected language is Fortran or Fortran 77).  The compiler
24039 and compilation flags are determined by the current language
24040 (@pxref{Language Choice}).
24041 @end defmac
24043 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
24044 @acindex{TRY_CPP}
24045 Same as:
24047 @example
24048 AC_PREPROC_IFELSE(
24049   [AC_LANG_SOURCE([[@var{input}]])],
24050   [@var{action-if-true}],
24051   [@var{action-if-false}])
24052 @end example
24054 @noindent
24055 @xref{Running the Preprocessor}.
24057 This macro double quotes the @var{input}.
24058 @end defmac
24060 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
24061   @ovar{action-if-true}, @ovar{action-if-false})
24062 @acindex{TRY_LINK}
24063 Same as:
24065 @example
24066 AC_LINK_IFELSE(
24067   [AC_LANG_PROGRAM([[@var{includes}]],
24068      [[@var{function-body}]])],
24069   [@var{action-if-true}],
24070   [@var{action-if-false}])
24071 @end example
24073 @noindent
24074 @xref{Running the Compiler}.
24076 This macro double quotes both @var{includes} and @var{function-body}.
24078 Depending on the current language (@pxref{Language Choice}), create a
24079 test program to see whether a function whose body consists of
24080 @var{function-body} can be compiled and linked.  If the file compiles
24081 and links successfully, run shell commands @var{action-if-found},
24082 otherwise run @var{action-if-not-found}.
24084 This macro double quotes both @var{includes} and @var{function-body}.
24086 For C and C++, @var{includes} is any @code{#include} statements needed
24087 by the code in @var{function-body} (@var{includes} is ignored if
24088 the currently selected language is Fortran or Fortran 77).  The compiler
24089 and compilation flags are determined by the current language
24090 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
24091 @code{LIBS} are used for linking.
24092 @end defmac
24094 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
24095   @ovar{action-if-not-found})
24096 @acindex{TRY_LINK_FUNC}
24097 This macro is equivalent to
24098 @example
24099 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
24100   [@var{action-if-found}], [@var{action-if-not-found}])
24101 @end example
24102 @noindent
24103 @xref{AC_LINK_IFELSE}.
24104 @end defmac
24106 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
24107   @ovar{action-if-false}, @dvar{action-if-cross-compiling, AC_MSG_FAILURE})
24108 @acindex{TRY_RUN}
24109 Same as:
24111 @example
24112 AC_RUN_IFELSE(
24113   [AC_LANG_SOURCE([[@var{program}]])],
24114   [@var{action-if-true}],
24115   [@var{action-if-false}],
24116   [@var{action-if-cross-compiling}])
24117 @end example
24119 @noindent
24120 @xref{Runtime}.
24121 @end defmac
24123 @anchor{AC_TYPE_SIGNAL}
24124 @defmac AC_TYPE_SIGNAL
24125 @acindex{TYPE_SIGNAL}
24126 @cvindex RETSIGTYPE
24127 @hdrindex{signal.h}
24128 If @file{signal.h} declares @code{signal} as returning a pointer to a
24129 function returning @code{void}, define @code{RETSIGTYPE} to be
24130 @code{void}; otherwise, define it to be @code{int}.  These days, it is
24131 portable to assume C89, and that signal handlers return @code{void},
24132 without needing to use this macro or @code{RETSIGTYPE}.
24134 When targeting older K&R C, it is possible to define signal handlers as
24135 returning type @code{RETSIGTYPE}, and omit a return statement:
24137 @example
24138 @group
24139 RETSIGTYPE
24140 hup_handler ()
24142 @dots{}
24144 @end group
24145 @end example
24146 @end defmac
24148 @defmac AC_UID_T
24149 @acindex{UID_T}
24150 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
24151 @end defmac
24153 @defmac AC_UNISTD_H
24154 @acindex{UNISTD_H}
24155 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}),
24156 which is one of the tests done as a side effect by
24157 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), so usually
24158 unnecessary to write explicitly.
24159 @end defmac
24161 @defmac AC_USG
24162 @acindex{USG}
24163 @cvindex USG
24164 Define @code{USG} if the BSD string functions (@code{bcopy},
24165 @code{bzero}, @code{index}, @code{rindex}, etc) are @emph{not} defined
24166 in @file{strings.h}.  Modern code should assume @file{string.h} exists
24167 and should use the ISO C string functions (@code{memmove}, @code{memset},
24168 @code{strchr}, @code{strrchr}, etc) unconditionally.
24170 @file{strings.h} may be the only header that declares @code{strcasecmp},
24171 @code{strncasecmp}, and @code{ffs}.  @code{AC_INCLUDES_DEFAULT} checks
24172 for it (@pxref{Default Includes}); test @code{HAVE_STRINGS_H}.
24173 @end defmac
24175 @defmac AC_UTIME_NULL
24176 @acindex{UTIME_NULL}
24177 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
24178 @end defmac
24180 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
24181 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
24182 If the cache file is inconsistent with the current host, target and
24183 build system types, it used to execute @var{cmd} or print a default
24184 error message.  This is now handled by default.
24185 @end defmac
24187 @defmac AC_VERBOSE (@var{result-description})
24188 @acindex{VERBOSE}
24189 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
24190 @end defmac
24192 @defmac AC_VFORK
24193 @acindex{VFORK}
24194 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
24195 @end defmac
24197 @defmac AC_VPRINTF
24198 @acindex{VPRINTF}
24199 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
24200 @end defmac
24202 @defmac AC_WAIT3
24203 @acindex{WAIT3}
24204 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
24205 portable programs should use @code{waitpid}, not @code{wait3}, as
24206 @code{wait3} has been removed from Posix.
24207 @end defmac
24209 @defmac AC_WARN
24210 @acindex{WARN}
24211 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
24212 @end defmac
24214 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
24215   @ovar{action-if-not-given})
24216 @acindex{WITH}
24217 This is an obsolete version of @code{AC_ARG_WITH} that does not
24218 support providing a help string (@pxref{AC_ARG_WITH}).
24219 @end defmac
24221 @defmac AC_WORDS_BIGENDIAN
24222 @acindex{WORDS_BIGENDIAN}
24223 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
24224 @end defmac
24226 @defmac AC_XENIX_DIR
24227 @acindex{XENIX_DIR}
24228 @ovindex LIBS
24229 This macro used to add @option{-lx} to output variable @code{LIBS} if on
24230 Xenix.  Also, if @file{dirent.h} is being checked for, added
24231 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
24232 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
24233 running XENIX on which you should not depend:
24235 @example
24236 AC_MSG_CHECKING([for Xenix])
24237 AC_EGREP_CPP([yes],
24238 [#if defined M_XENIX && !defined M_UNIX
24239   yes
24240 #endif],
24241              [AC_MSG_RESULT([yes]); XENIX=yes],
24242              [AC_MSG_RESULT([no]); XENIX=])
24243 @end example
24244 @noindent
24245 Don't use this macro, the dignified means to check the nature of the
24246 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
24247 @end defmac
24249 @defmac AC_YYTEXT_POINTER
24250 @acindex{YYTEXT_POINTER}
24251 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
24252 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
24253 @end defmac
24255 @node Autoconf 1
24256 @section Upgrading From Version 1
24257 @cindex Upgrading autoconf
24258 @cindex Autoconf upgrading
24260 Autoconf version 2 is mostly backward compatible with version 1.
24261 However, it introduces better ways to do some things, and doesn't
24262 support some of the ugly things in version 1.  So, depending on how
24263 sophisticated your @file{configure.ac} files are, you might have to do
24264 some manual work in order to upgrade to version 2.  This chapter points
24265 out some problems to watch for when upgrading.  Also, perhaps your
24266 @command{configure} scripts could benefit from some of the new features in
24267 version 2; the changes are summarized in the file @file{NEWS} in the
24268 Autoconf distribution.
24270 @menu
24271 * Changed File Names::          Files you might rename
24272 * Changed Makefiles::           New things to put in @file{Makefile.in}
24273 * Changed Macros::              Macro calls you might replace
24274 * Changed Results::             Changes in how to check test results
24275 * Changed Macro Writing::       Better ways to write your own macros
24276 @end menu
24278 @node Changed File Names
24279 @subsection Changed File Names
24281 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
24282 in a particular package's source directory), you must rename it to
24283 @file{acsite.m4}.  @xref{autoconf Invocation}.
24285 If you distribute @file{install.sh} with your package, rename it to
24286 @file{install-sh} so @command{make} builtin rules don't inadvertently
24287 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
24288 looks for the script under both names, but it is best to use the new name.
24290 If you were using @file{config.h.top}, @file{config.h.bot}, or
24291 @file{acconfig.h}, you still can, but you have less clutter if you
24292 use the @code{AH_} macros.  @xref{Autoheader Macros}.
24294 @node Changed Makefiles
24295 @subsection Changed Makefiles
24297 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
24298 your @file{Makefile.in} files, so they can take advantage of the values
24299 of those variables in the environment when @command{configure} is run.
24300 Doing this isn't necessary, but it's a convenience for users.
24302 Also add @samp{@@configure_input@@} in a comment to each input file for
24303 @code{AC_OUTPUT}, so that the output files contain a comment saying
24304 they were produced by @command{configure}.  Automatically selecting the
24305 right comment syntax for all the kinds of files that people call
24306 @code{AC_OUTPUT} on became too much work.
24308 Add @file{config.log} and @file{config.cache} to the list of files you
24309 remove in @code{distclean} targets.
24311 If you have the following in @file{Makefile.in}:
24313 @example
24314 prefix = /usr/local
24315 exec_prefix = $(prefix)
24316 @end example
24318 @noindent
24319 you must change it to:
24321 @example
24322 prefix = @@prefix@@
24323 exec_prefix = @@exec_prefix@@
24324 @end example
24326 @noindent
24327 The old behavior of replacing those variables without @samp{@@}
24328 characters around them has been removed.
24330 @node Changed Macros
24331 @subsection Changed Macros
24333 Many of the macros were renamed in Autoconf version 2.  You can still
24334 use the old names, but the new ones are clearer, and it's easier to find
24335 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
24336 new names for the old macros.  Use the @command{autoupdate} program to
24337 convert your @file{configure.ac} to using the new macro names.
24338 @xref{autoupdate Invocation}.
24340 Some macros have been superseded by similar ones that do the job better,
24341 but are not call-compatible.  If you get warnings about calling obsolete
24342 macros while running @command{autoconf}, you may safely ignore them, but
24343 your @command{configure} script generally works better if you follow
24344 the advice that is printed about what to replace the obsolete macros with.  In
24345 particular, the mechanism for reporting the results of tests has
24346 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
24347 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
24348 looks better if you switch to @code{AC_MSG_CHECKING} and
24349 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
24350 in conjunction with cache variables.  @xref{Caching Results}.
24354 @node Changed Results
24355 @subsection Changed Results
24357 If you were checking the results of previous tests by examining the
24358 shell variable @code{DEFS}, you need to switch to checking the values of
24359 the cache variables for those tests.  @code{DEFS} no longer exists while
24360 @command{configure} is running; it is only created when generating output
24361 files.  This difference from version 1 is because properly quoting the
24362 contents of that variable turned out to be too cumbersome and
24363 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
24364 Variable Names}.
24366 For example, here is a @file{configure.ac} fragment written for Autoconf
24367 version 1:
24369 @example
24370 AC_HAVE_FUNCS(syslog)
24371 case "$DEFS" in
24372 *-DHAVE_SYSLOG*) ;;
24373 *) # syslog is not in the default libraries.  See if it's in some other.
24374   saved_LIBS="$LIBS"
24375   for lib in bsd socket inet; do
24376     AC_CHECKING(for syslog in -l$lib)
24377     LIBS="-l$lib $saved_LIBS"
24378     AC_HAVE_FUNCS(syslog)
24379     case "$DEFS" in
24380     *-DHAVE_SYSLOG*) break ;;
24381     *) ;;
24382     esac
24383     LIBS="$saved_LIBS"
24384   done ;;
24385 esac
24386 @end example
24388 Here is a way to write it for version 2:
24390 @example
24391 AC_CHECK_FUNCS([syslog])
24392 if test "x$ac_cv_func_syslog" = xno; then
24393   # syslog is not in the default libraries.  See if it's in some other.
24394   for lib in bsd socket inet; do
24395     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
24396       LIBS="-l$lib $LIBS"; break])
24397   done
24399 @end example
24401 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
24402 backslashes before quotes, you need to remove them.  It now works
24403 predictably, and does not treat quotes (except back quotes) specially.
24404 @xref{Setting Output Variables}.
24406 All of the Boolean shell variables set by Autoconf macros now use
24407 @samp{yes} for the true value.  Most of them use @samp{no} for false,
24408 though for backward compatibility some use the empty string instead.  If
24409 you were relying on a shell variable being set to something like 1 or
24410 @samp{t} for true, you need to change your tests.
24412 @node Changed Macro Writing
24413 @subsection Changed Macro Writing
24415 When defining your own macros, you should now use @code{AC_DEFUN}
24416 instead of @code{define}.  @code{AC_DEFUN} automatically calls
24417 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
24418 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
24419 messages on the screen.  There's no actual harm in continuing to use the
24420 older way, but it's less convenient and attractive.  @xref{Macro
24421 Definitions}.
24423 You probably looked at the macros that came with Autoconf as a guide for
24424 how to do things.  It would be a good idea to take a look at the new
24425 versions of them, as the style is somewhat improved and they take
24426 advantage of some new features.
24428 If you were doing tricky things with undocumented Autoconf internals
24429 (macros, variables, diversions), check whether you need to change
24430 anything to account for changes that have been made.  Perhaps you can
24431 even use an officially supported technique in version 2 instead of
24432 kludging.  Or perhaps not.
24434 To speed up your locally written feature tests, add caching to them.
24435 See whether any of your tests are of general enough usefulness to
24436 encapsulate them into macros that you can share.
24439 @node Autoconf 2.13
24440 @section Upgrading From Version 2.13
24441 @cindex Upgrading autoconf
24442 @cindex Autoconf upgrading
24444 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
24445 suits this section@enddots{}
24447 @quotation
24448 Autoconf version 2.50 is mostly backward compatible with version 2.13.
24449 However, it introduces better ways to do some things, and doesn't
24450 support some of the ugly things in version 2.13.  So, depending on how
24451 sophisticated your @file{configure.ac} files are, you might have to do
24452 some manual work in order to upgrade to version 2.50.  This chapter
24453 points out some problems to watch for when upgrading.  Also, perhaps
24454 your @command{configure} scripts could benefit from some of the new
24455 features in version 2.50; the changes are summarized in the file
24456 @file{NEWS} in the Autoconf distribution.
24457 @end quotation
24459 @menu
24460 * Changed Quotation::           Broken code which used to work
24461 * New Macros::                  Interaction with foreign macros
24462 * Hosts and Cross-Compilation::  Bugward compatibility kludges
24463 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
24464 * AC_ACT_IFELSE vs AC_TRY_ACT::  A more generic scheme for testing sources
24465 @end menu
24467 @node Changed Quotation
24468 @subsection Changed Quotation
24470 The most important changes are invisible to you: the implementation of
24471 most macros have completely changed.  This allowed more factorization of
24472 the code, better error messages, a higher uniformity of the user's
24473 interface etc.  Unfortunately, as a side effect, some construct which
24474 used to (miraculously) work might break starting with Autoconf 2.50.
24475 The most common culprit is bad quotation.
24477 For instance, in the following example, the message is not properly
24478 quoted:
24480 @example
24481 AC_INIT
24482 AC_CHECK_HEADERS(foo.h, ,
24483   AC_MSG_ERROR(cannot find foo.h, bailing out))
24484 AC_OUTPUT
24485 @end example
24487 @noindent
24488 Autoconf 2.13 simply ignores it:
24490 @example
24491 $ @kbd{autoconf-2.13; ./configure --silent}
24492 creating cache ./config.cache
24493 configure: error: cannot find foo.h
24495 @end example
24497 @noindent
24498 while Autoconf 2.50 produces a broken @file{configure}:
24500 @example
24501 $ @kbd{autoconf-2.50; ./configure --silent}
24502 configure: error: cannot find foo.h
24503 ./configure: exit: bad non-numeric arg `bailing'
24504 ./configure: exit: bad non-numeric arg `bailing'
24506 @end example
24508 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
24509 too!
24511 @example
24512 AC_INIT([Example], [1.0], [bug-example@@example.org])
24513 AC_CHECK_HEADERS([foo.h], [],
24514   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
24515 AC_OUTPUT
24516 @end example
24518 Many many (and many more) Autoconf macros were lacking proper quotation,
24519 including no less than@dots{} @code{AC_DEFUN} itself!
24521 @example
24522 $ @kbd{cat configure.in}
24523 AC_DEFUN([AC_PROG_INSTALL],
24524 [# My own much better version
24526 AC_INIT
24527 AC_PROG_INSTALL
24528 AC_OUTPUT
24529 $ @kbd{autoconf-2.13}
24530 autoconf: Undefined macros:
24531 ***BUG in Autoconf--please report*** AC_FD_MSG
24532 ***BUG in Autoconf--please report*** AC_EPI
24533 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
24534 configure.in:5:AC_PROG_INSTALL
24535 $ @kbd{autoconf-2.50}
24537 @end example
24540 @node New Macros
24541 @subsection New Macros
24543 @cindex undefined macro
24544 @cindex @code{_m4_divert_diversion}
24546 While Autoconf was relatively dormant in the late 1990s, Automake
24547 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
24548 in 2001, Autoconf provided
24549 versions of these macros, integrated in the @code{AC_} namespace,
24550 instead of @code{AM_}.  But in order to ease the upgrading via
24551 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
24553 Unfortunately older versions of Automake (e.g., Automake 1.4)
24554 did not quote the names of these macros.
24555 Therefore, when @command{m4} finds something like
24556 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
24557 @code{AM_TYPE_PTRDIFF_T} is
24558 expanded, replaced with its Autoconf definition.
24560 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
24561 complains, in its own words:
24563 @example
24564 $ @kbd{cat configure.ac}
24565 AC_INIT([Example], [1.0], [bug-example@@example.org])
24566 AM_TYPE_PTRDIFF_T
24567 $ @kbd{aclocal-1.4}
24568 $ @kbd{autoconf}
24569 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
24570 aclocal.m4:17: the top level
24571 autom4te: m4 failed with exit status: 1
24573 @end example
24575 Modern versions of Automake no longer define most of these
24576 macros, and properly quote the names of the remaining macros.
24577 If you must use an old Automake, do not depend upon macros from Automake
24578 as it is simply not its job
24579 to provide macros (but the one it requires itself):
24581 @example
24582 $ @kbd{cat configure.ac}
24583 AC_INIT([Example], [1.0], [bug-example@@example.org])
24584 AM_TYPE_PTRDIFF_T
24585 $ @kbd{rm aclocal.m4}
24586 $ @kbd{autoupdate}
24587 autoupdate: `configure.ac' is updated
24588 $ @kbd{cat configure.ac}
24589 AC_INIT([Example], [1.0], [bug-example@@example.org])
24590 AC_CHECK_TYPES([ptrdiff_t])
24591 $ @kbd{aclocal-1.4}
24592 $ @kbd{autoconf}
24594 @end example
24597 @node Hosts and Cross-Compilation
24598 @subsection Hosts and Cross-Compilation
24599 @cindex Cross compilation
24601 Based on the experience of compiler writers, and after long public
24602 debates, many aspects of the cross-compilation chain have changed:
24604 @itemize @minus
24605 @item
24606 the relationship between the build, host, and target architecture types,
24608 @item
24609 the command line interface for specifying them to @command{configure},
24611 @item
24612 the variables defined in @command{configure},
24614 @item
24615 the enabling of cross-compilation mode.
24616 @end itemize
24618 @sp 1
24620 The relationship between build, host, and target have been cleaned up:
24621 the chain of default is now simply: target defaults to host, host to
24622 build, and build to the result of @command{config.guess}.  Nevertheless,
24623 in order to ease the transition from 2.13 to 2.50, the following
24624 transition scheme is implemented.  @emph{Do not rely on it}, as it will
24625 be completely disabled in a couple of releases (we cannot keep it, as it
24626 proves to cause more problems than it cures).
24628 They all default to the result of running @command{config.guess}, unless
24629 you specify either @option{--build} or @option{--host}.  In this case,
24630 the default becomes the system type you specified.  If you specify both,
24631 and they're different, @command{configure} enters cross compilation
24632 mode, so it doesn't run any tests that require execution.
24634 Hint: if you mean to override the result of @command{config.guess},
24635 prefer @option{--build} over @option{--host}.
24637 @sp 1
24639 For backward compatibility, @command{configure} accepts a system
24640 type as an option by itself.  Such an option overrides the
24641 defaults for build, host, and target system types.  The following
24642 configure statement configures a cross toolchain that runs on
24643 NetBSD/alpha but generates code for GNU Hurd/sparc,
24644 which is also the build platform.
24646 @example
24647 ./configure --host=alpha-netbsd sparc-gnu
24648 @end example
24650 @sp 1
24652 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
24653 and @code{target} had a different semantics before and after the
24654 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
24655 @option{--build} is strictly copied into @code{build_alias}, and is left
24656 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
24657 set to the canonicalized build type.  To ease the transition, before,
24658 its contents is the same as that of @code{build_alias}.  Do @emph{not}
24659 rely on this broken feature.
24661 For consistency with the backward compatibility scheme exposed above,
24662 when @option{--host} is specified but @option{--build} isn't, the build
24663 system is assumed to be the same as @option{--host}, and
24664 @samp{build_alias} is set to that value.  Eventually, this
24665 historically incorrect behavior will go away.
24667 @sp 1
24669 The former scheme to enable cross-compilation proved to cause more harm
24670 than good, in particular, it used to be triggered too easily, leaving
24671 regular end users puzzled in front of cryptic error messages.
24672 @command{configure} could even enter cross-compilation mode only
24673 because the compiler was not functional.  This is mainly because
24674 @command{configure} used to try to detect cross-compilation, instead of
24675 waiting for an explicit flag from the user.
24677 Now, @command{configure} enters cross-compilation mode if and only if
24678 @option{--host} is passed.
24680 That's the short documentation.  To ease the transition between 2.13 and
24681 its successors, a more complicated scheme is implemented.  @emph{Do not
24682 rely on the following}, as it will be removed in the near future.
24684 If you specify @option{--host}, but not @option{--build}, when
24685 @command{configure} performs the first compiler test it tries to run
24686 an executable produced by the compiler.  If the execution fails, it
24687 enters cross-compilation mode.  This is fragile.  Moreover, by the time
24688 the compiler test is performed, it may be too late to modify the
24689 build-system type: other tests may have already been performed.
24690 Therefore, whenever you specify @option{--host}, be sure to specify
24691 @option{--build} too.
24693 @example
24694 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
24695 @end example
24697 @noindent
24698 enters cross-compilation mode.  The former interface, which
24699 consisted in setting the compiler to a cross-compiler without informing
24700 @command{configure} is obsolete.  For instance, @command{configure}
24701 fails if it can't run the code generated by the specified compiler if you
24702 configure as follows:
24704 @example
24705 ./configure CC=m68k-coff-gcc
24706 @end example
24709 @node AC_LIBOBJ vs LIBOBJS
24710 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
24712 Up to Autoconf 2.13, the replacement of functions was triggered via the
24713 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
24714 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
24715 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
24717 This change is mandated by the unification of the GNU Build System
24718 components.  In particular, the various fragile techniques used to parse
24719 a @file{configure.ac} are all replaced with the use of traces.  As a
24720 consequence, any action must be traceable, which obsoletes critical
24721 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
24722 and it can even be handled gracefully (read, ``without your having to
24723 change something'').
24725 There were two typical uses of @code{LIBOBJS}: asking for a replacement
24726 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
24728 @sp 1
24730 As for function replacement, the fix is immediate: use
24731 @code{AC_LIBOBJ}.  For instance:
24733 @example
24734 LIBOBJS="$LIBOBJS fnmatch.o"
24735 LIBOBJS="$LIBOBJS malloc.$ac_objext"
24736 @end example
24738 @noindent
24739 should be replaced with:
24741 @example
24742 AC_LIBOBJ([fnmatch])
24743 AC_LIBOBJ([malloc])
24744 @end example
24746 @sp 1
24748 @ovindex LIBOBJDIR
24749 When used with Automake 1.10 or newer, a suitable value for
24750 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
24751 can be referenced from any @file{Makefile.am}.  Even without Automake,
24752 arranging for @code{LIBOBJDIR} to be set correctly enables
24753 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
24754 The @code{LIBOBJDIR} feature is experimental.
24757 @node AC_ACT_IFELSE vs AC_TRY_ACT
24758 @subsection @code{AC_@var{ACT}_IFELSE} vs.@: @code{AC_TRY_@var{ACT}}
24759 @c the anchor keeps the old node name, to try to avoid breaking links
24760 @anchor{AC_FOO_IFELSE vs AC_TRY_FOO}
24762 @acindex{@var{ACT}_IFELSE}
24763 @acindex{TRY_@var{ACT}}
24764 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
24765 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
24766 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCE},
24767 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
24768 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
24769 @code{AC_TRY_RUN}.  The motivations where:
24770 @itemize @minus
24771 @item
24772 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
24773 quoting their arguments;
24775 @item
24776 the combinatoric explosion is solved by decomposing on the one hand the
24777 generation of sources, and on the other hand executing the program;
24779 @item
24780 this scheme helps supporting more languages than plain C and C++.
24781 @end itemize
24783 In addition to the change of syntax, the philosophy has changed too:
24784 while emphasis was put on speed at the expense of accuracy, today's
24785 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
24786 expense of speed.
24789 As a perfect example of what is @emph{not} to be done, here is how to
24790 find out whether a header file contains a particular declaration, such
24791 as a typedef, a structure, a structure member, or a function.  Use
24792 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
24793 header file; on some systems the symbol might be defined in another
24794 header file that the file you are checking includes.
24796 As a (bad) example, here is how you should not check for C preprocessor
24797 symbols, either defined by header files or predefined by the C
24798 preprocessor: using @code{AC_EGREP_CPP}:
24800 @example
24801 @group
24802 AC_EGREP_CPP(yes,
24803 [#ifdef _AIX
24804   yes
24805 #endif
24806 ], is_aix=yes, is_aix=no)
24807 @end group
24808 @end example
24810 The above example, properly written would (i) use
24811 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
24813 @example
24814 @group
24815 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
24816 [[#ifndef _AIX
24817  error: This isn't AIX!
24818 #endif
24819 ]])],
24820                    [is_aix=yes],
24821                    [is_aix=no])
24822 @end group
24823 @end example
24826 @c ============================= Generating Test Suites with Autotest
24828 @node Using Autotest
24829 @chapter Generating Test Suites with Autotest
24831 @cindex Autotest
24833 @display
24834 @strong{N.B.: This section describes a feature which is still
24835 stabilizing.  Although we believe that Autotest is useful as-is, this
24836 documentation describes an interface which might change in the future:
24837 do not depend upon Autotest without subscribing to the Autoconf mailing
24838 lists.}
24839 @end display
24841 It is paradoxical that portable projects depend on nonportable tools
24842 to run their test suite.  Autoconf by itself is the paragon of this
24843 problem: although it aims at perfectly portability, up to 2.13 its
24844 test suite was using DejaGNU, a rich and complex testing
24845 framework, but which is far from being standard on Posix systems.
24846 Worse yet, it was likely to be missing on the most fragile platforms,
24847 the very platforms that are most likely to torture Autoconf and
24848 exhibit deficiencies.
24850 To circumvent this problem, many package maintainers have developed their
24851 own testing framework, based on simple shell scripts whose sole outputs
24852 are exit status values describing whether the test succeeded.  Most of
24853 these tests share common patterns, and this can result in lots of
24854 duplicated code and tedious maintenance.
24856 Following exactly the same reasoning that yielded to the inception of
24857 Autoconf, Autotest provides a test suite generation framework, based on
24858 M4 macros building a portable shell script.  The suite itself is
24859 equipped with automatic logging and tracing facilities which greatly
24860 diminish the interaction with bug reporters, and simple timing reports.
24862 Autoconf itself has been using Autotest for years, and we do attest that
24863 it has considerably improved the strength of the test suite and the
24864 quality of bug reports.  Other projects are known to use some generation
24865 of Autotest, such as Bison, Free Recode, Free Wdiff, GNU Tar, each of
24866 them with different needs, and this usage has validated Autotest as a general
24867 testing framework.
24869 Nonetheless, compared to DejaGNU, Autotest is inadequate for
24870 interactive tool testing, which is probably its main limitation.
24872 @menu
24873 * Using an Autotest Test Suite::  Autotest and the user
24874 * Writing Testsuites::          Autotest macros
24875 * testsuite Invocation::        Running @command{testsuite} scripts
24876 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
24877 @end menu
24879 @node Using an Autotest Test Suite
24880 @section Using an Autotest Test Suite
24882 @menu
24883 * testsuite Scripts::           The concepts of Autotest
24884 * Autotest Logs::               Their contents
24885 @end menu
24887 @node testsuite Scripts
24888 @subsection @command{testsuite} Scripts
24890 @cindex @command{testsuite}
24892 Generating testing or validation suites using Autotest is rather easy.
24893 The whole validation suite is held in a file to be processed through
24894 @command{autom4te}, itself using GNU M4 under the hood, to
24895 produce a stand-alone Bourne shell script which then gets distributed.
24896 Neither @command{autom4te} nor GNU M4 are needed at
24897 the installer's end.
24899 @cindex test group
24900 Each test of the validation suite should be part of some test group.  A
24901 @dfn{test group} is a sequence of interwoven tests that ought to be
24902 executed together, usually because one test in the group creates data
24903 files that a later test in the same group needs to read.  Complex test
24904 groups make later debugging more tedious.  It is much better to
24905 keep only a few tests per test group.  Ideally there is only one test
24906 per test group.
24908 For all but the simplest packages, some file such as @file{testsuite.at}
24909 does not fully hold all test sources, as these are often easier to
24910 maintain in separate files.  Each of these separate files holds a single
24911 test group, or a sequence of test groups all addressing some common
24912 functionality in the package.  In such cases, @file{testsuite.at}
24913 merely initializes the validation suite, and sometimes does elementary
24914 health checking, before listing include statements for all other test
24915 files.  The special file @file{package.m4}, containing the
24916 identification of the package, is automatically included if found.
24918 A convenient alternative consists in moving all the global issues
24919 (local Autotest macros, elementary health checking, and @code{AT_INIT}
24920 invocation) into the file @code{local.at}, and making
24921 @file{testsuite.at} be a simple list of @code{m4_include}s of sub test
24922 suites.  In such case, generating the whole test suite or pieces of it
24923 is only a matter of choosing the @command{autom4te} command line
24924 arguments.
24926 The validation scripts that Autotest produces are by convention called
24927 @command{testsuite}.  When run, @command{testsuite} executes each test
24928 group in turn, producing only one summary line per test to say if that
24929 particular test succeeded or failed.  At end of all tests, summarizing
24930 counters get printed.  One debugging directory is left for each test
24931 group which failed, if any: such directories are named
24932 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
24933 the test group, and they include:
24935 @itemize @bullet
24936 @item a debugging script named @file{run} which reruns the test in
24937 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
24938 of debugging scripts has the purpose of easing the chase for bugs.
24940 @item all the files created with @code{AT_DATA}
24942 @item all the Erlang source code files created with @code{AT_CHECK_EUNIT}
24944 @item a log of the run, named @file{testsuite.log}
24945 @end itemize
24947 In the ideal situation, none of the tests fail, and consequently no
24948 debugging directory is left behind for validation.
24950 It often happens in practice that individual tests in the validation
24951 suite need to get information coming out of the configuration process.
24952 Some of this information, common for all validation suites, is provided
24953 through the file @file{atconfig}, automatically created by
24954 @code{AC_CONFIG_TESTDIR}.  For configuration information which your
24955 testing environment specifically needs, you might prepare an optional
24956 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
24957 The configuration process produces @file{atconfig} and @file{atlocal}
24958 out of these two input files, and these two produced files are
24959 automatically read by the @file{testsuite} script.
24961 Here is a diagram showing the relationship between files.
24963 @noindent
24964 Files used in preparing a software package for distribution:
24966 @example
24967                 [package.m4] -->.
24968                                  \
24969 subfile-1.at ->.  [local.at] ---->+
24970     ...         \                  \
24971 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
24972     ...         /
24973 subfile-n.at ->'
24974 @end example
24976 @noindent
24977 Files used in configuring a software package:
24979 @example
24980                                      .--> atconfig
24981                                     /
24982 [atlocal.in] -->  config.status* --<
24983                                     \
24984                                      `--> [atlocal]
24985 @end example
24987 @noindent
24988 Files created during test suite execution:
24990 @example
24991 atconfig -->.                    .--> testsuite.log
24992              \                  /
24993               >-- testsuite* --<
24994              /                  \
24995 [atlocal] ->'                    `--> [testsuite.dir]
24996 @end example
24999 @node Autotest Logs
25000 @subsection Autotest Logs
25002 When run, the test suite creates a log file named after itself, e.g., a
25003 test suite named @command{testsuite} creates @file{testsuite.log}.  It
25004 contains a lot of information, usually more than maintainers actually
25005 need, but therefore most of the time it contains all that is needed:
25007 @table @asis
25008 @item command line arguments
25009 A bad but unfortunately widespread habit consists of
25010 setting environment variables before the command, such as in
25011 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
25012 know this change, hence (i) it cannot report it to you, and (ii)
25013 it cannot preserve the value of @code{CC} for subsequent runs.
25014 Autoconf faced exactly the same problem, and solved it by asking
25015 users to pass the variable definitions as command line arguments.
25016 Autotest requires this rule, too, but has no means to enforce it; the log
25017 then contains a trace of the variables that were changed by the user.
25019 @item @file{ChangeLog} excerpts
25020 The topmost lines of all the @file{ChangeLog} files found in the source
25021 hierarchy.  This is especially useful when bugs are reported against
25022 development versions of the package, since the version string does not
25023 provide sufficient information to know the exact state of the sources
25024 the user compiled.  Of course, this relies on the use of a
25025 @file{ChangeLog}.
25027 @item build machine
25028 Running a test suite in a cross-compile environment is not an easy task,
25029 since it would mean having the test suite run on a machine @var{build},
25030 while running programs on a machine @var{host}.  It is much simpler to
25031 run both the test suite and the programs on @var{host}, but then, from
25032 the point of view of the test suite, there remains a single environment,
25033 @var{host} = @var{build}.  The log contains relevant information on the
25034 state of the @var{build} machine, including some important environment
25035 variables.
25036 @c FIXME: How about having an M4sh macro to say `hey, log the value
25037 @c of `@dots{}'?  This would help both Autoconf and Autotest.
25039 @item tested programs
25040 The absolute file name and answers to @option{--version} of the tested
25041 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
25043 @item configuration log
25044 The contents of @file{config.log}, as created by @command{configure},
25045 are appended.  It contains the configuration flags and a detailed report
25046 on the configuration itself.
25047 @end table
25050 @node Writing Testsuites
25051 @section Writing @file{testsuite.at}
25053 The @file{testsuite.at} is a Bourne shell script making use of special
25054 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
25055 its beginning followed by one call to @code{m4_include} per source file
25056 for tests.  Each such included file, or the remainder of
25057 @file{testsuite.at} if include files are not used, contain a sequence of
25058 test groups.  Each test group begins with a call to @code{AT_SETUP},
25059 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
25060 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
25061 groups can be categorized by a call to @code{AT_BANNER}.
25063 All of the public Autotest macros have all-uppercase names in the
25064 namespace @samp{^AT_} to prevent them from accidentally conflicting with
25065 other text; Autoconf also reserves the namespace @samp{^_AT_} for
25066 internal macros.  All shell variables used in the testsuite for internal
25067 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
25068 also uses here-document delimiters in the namespace @samp{^_AT[A-Z]}, and
25069 makes use of the file system namespace @samp{^at-}.
25071 Since Autoconf is built on top of M4sugar (@pxref{Programming in
25072 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
25073 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
25074 @emph{should not use} the namespace of a package that does not own the
25075 macro or shell code you are writing.
25077 @defmac AT_INIT (@ovar{name})
25078 @atindex{INIT}
25079 @c FIXME: Not clear, plus duplication of the information.
25080 Initialize Autotest.  Giving a @var{name} to the test suite is
25081 encouraged if your package includes several test suites.  Before this
25082 macro is called, @code{AT_PACKAGE_STRING} and
25083 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
25084 information about the testsuite to the user.  Typically, these macros
25085 are provided by a file @file{package.m4} built by @command{make}
25086 (@pxref{Making testsuite Scripts}), in order to inherit the package
25087 name, version, and bug reporting address from @file{configure.ac}.
25088 @end defmac
25090 @defmac AT_COPYRIGHT (@var{copyright-notice})
25091 @atindex{COPYRIGHT}
25092 @cindex Copyright Notice
25093 State that, in addition to the Free Software Foundation's copyright on
25094 the Autotest macros, parts of your test suite are covered by
25095 @var{copyright-notice}.
25097 The @var{copyright-notice} shows up in both the head of
25098 @command{testsuite} and in @samp{testsuite --version}.
25099 @end defmac
25101 @defmac AT_ARG_OPTION (@var{options}, @var{help-text}, @
25102   @ovar{action-if-given}, @ovar{action-if-not-given})
25103 @atindex{ARG_OPTION}
25104 @vrindex at_arg_@var{option}
25105 Accept options from the space-separated list @var{options}, a list that
25106 has leading dashes removed from the options.  Long options will be
25107 prefixed with @samp{--}, single-character options with @samp{-}.  The
25108 first word in this list is the primary @var{option}, any others are
25109 assumed to be short-hand aliases.  The variable associated with it
25110 is @code{at_arg_@var{option}}, with any dashes in @var{option} replaced
25111 with underscores.
25113 If the user passes @option{--@var{option}} to the @command{testsuite},
25114 the variable will be set to @samp{:}.  If the user does not pass the
25115 option, or passes @option{--no-@var{option}}, then the variable will be
25116 set to @samp{false}.
25118 @vrindex at_optarg
25119 @vrindex at_optarg_@var{option}
25120 @var{action-if-given} is run each time the option is encountered; here,
25121 the variable @code{at_optarg} will be set to @samp{:} or @samp{false} as
25122 appropriate.  @code{at_optarg} is actually just a copy of
25123 @code{at_arg_@var{option}}.
25125 @var{action-if-not-given} will be run once after option parsing is
25126 complete and if no option from @var{options} was used.
25128 @var{help-text} is added to the end of the list of options shown in
25129 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25131 It is recommended that you use a package-specific prefix to @var{options}
25132 names in order to avoid clashes with future Autotest built-in options.
25133 @end defmac
25135 @defmac AT_ARG_OPTION_ARG (@var{options}, @var{help-text}, @
25136   @ovar{action-if-given}, @ovar{action-if-not-given})
25137 @atindex{ARG_OPTION_ARG}
25138 @vrindex at_arg_@var{option}
25139 Accept options with arguments from the space-separated list
25140 @var{options}, a list that has leading dashes removed from the options.
25141 Long options will be prefixed with @samp{--}, single-character options
25142 with @samp{-}.  The first word in this list is the primary @var{option},
25143 any others are assumed to be short-hand aliases.  The variable associated
25144 with it is @code{at_arg_@var{option}}, with any dashes in @var{option}
25145 replaced with underscores.
25147 If the user passes @option{--@var{option}=@var{arg}} or
25148 @option{--@var{option} @var{arg}} to the @command{testsuite}, the
25149 variable will be set to @samp{@var{arg}}.
25151 @vrindex at_optarg
25152 @var{action-if-given} is run each time the option is encountered; here,
25153 the variable @code{at_optarg} will be set to @samp{@var{arg}}.
25154 @code{at_optarg} is actually just a copy of @code{at_arg_@var{option}}.
25156 @var{action-if-not-given} will be run once after option parsing is
25157 complete and if no option from @var{options} was used.
25159 @var{help-text} is added to the end of the list of options shown in
25160 @command{testsuite --help} (@pxref{AS_HELP_STRING}).
25162 It is recommended that you use a package-specific prefix to @var{options}
25163 names in order to avoid clashes with future Autotest built-in options.
25164 @end defmac
25166 @defmac AT_COLOR_TESTS
25167 @atindex{COLOR_TESTS}
25168 Enable colored test results by default when the output is connected to
25169 a terminal.
25170 @end defmac
25172 @defmac AT_TESTED (@var{executables})
25173 @atindex{TESTED}
25174 Log the file name and answer to @option{--version} of each program in
25175 space-separated list @var{executables}.  Several invocations register
25176 new executables, in other words, don't fear registering one program
25177 several times.
25179 Autotest test suites rely on @env{PATH} to find the tested program.
25180 This avoids the need to generate absolute names of the various tools, and
25181 makes it possible to test installed programs.  Therefore, knowing which
25182 programs are being exercised is crucial to understanding problems in
25183 the test suite itself, or its occasional misuses.  It is a good idea to
25184 also subscribe foreign programs you depend upon, to avoid incompatible
25185 diagnostics.
25187 @var{executables} is implicitly wrapped in shell double quotes, but it
25188 will still use shell variable expansion (@samp{$}), command substitution
25189 (@samp{`}), and backslash escaping (@samp{\}).  In particular, the
25190 @env{EXEEXT} variable is available if it is passed to the testsuite
25191 via @file{atlocal} or @file{atconfig}.
25192 @end defmac
25194 @sp 1
25196 @defmac AT_BANNER (@var{test-category-name})
25197 @atindex{BANNER}
25198 This macro identifies the start of a category of related test groups.
25199 When the resulting @file{testsuite} is invoked with more than one test
25200 group to run, its output will include a banner containing
25201 @var{test-category-name} prior to any tests run from that category.  The
25202 banner should be no more than about 40 or 50 characters.  A blank banner
25203 indicates uncategorized tests; an empty line will be inserted after
25204 tests from an earlier category, effectively ending that category.
25205 @end defmac
25207 @defmac AT_SETUP (@var{test-group-name})
25208 @atindex{SETUP}
25209 This macro starts a group of related tests, all to be executed in the
25210 same subshell.  It accepts a single argument, which holds a few words
25211 (no more than about 30 or 40 characters) quickly describing the purpose
25212 of the test group being started.  @var{test-group-name} must not expand
25213 to unbalanced quotes, although quadrigraphs can be used.
25214 @end defmac
25216 @defmac AT_KEYWORDS (@var{keywords})
25217 @atindex{KEYWORDS}
25218 Associate the space-separated list of @var{keywords} to the enclosing
25219 test group.  This makes it possible to run ``slices'' of the test suite.
25220 For instance, if some of your test groups exercise some @samp{foo}
25221 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
25222 @samp{./testsuite -k foo} to run exclusively these test groups.  The
25223 @var{test-group-name} of the test group is automatically recorded to
25224 @code{AT_KEYWORDS}.
25226 Several invocations within a test group accumulate new keywords.  In
25227 other words, don't fear registering the same keyword several times in a
25228 test group.
25229 @end defmac
25231 @defmac AT_CAPTURE_FILE (@var{file})
25232 @atindex{CAPTURE_FILE}
25233 If the current test group fails, log the contents of @var{file}.
25234 Several identical calls within one test group have no additional effect.
25235 @end defmac
25237 @defmac AT_FAIL_IF (@var{shell-condition})
25238 @atindex{FAIL_IF}
25239 Make the test group fail and skip the rest of its execution, if
25240 @var{shell-condition} is true.  @var{shell-condition} is a shell expression
25241 such as a @code{test} command.  Tests before @command{AT_FAIL_IF}
25242 will be executed and may still cause the test group to be skipped.
25243 You can instantiate this macro many times from within the same test group.
25245 You should use this macro only for very simple failure conditions.  If the
25246 @var{shell-condition} could emit any kind of output you should instead
25247 use @command{AT_CHECK} like
25248 @example
25249 AT_CHECK([if @var{shell-condition}; then exit 99; fi])
25250 @end example
25251 @noindent
25252 so that such output is properly recorded in the @file{testsuite.log}
25253 file.
25254 @end defmac
25256 @defmac AT_SKIP_IF (@var{shell-condition})
25257 @atindex{SKIP_IF}
25258 Determine whether the test should be skipped because it requires
25259 features that are unsupported on the machine under test.
25260 @var{shell-condition} is a shell expression such as a @code{test}
25261 command.  Tests before @command{AT_SKIP_IF} will be executed
25262 and may still cause the test group to fail.  You can instantiate this
25263 macro many times from within the same test group.
25265 You should use this macro only for very simple skip conditions.  If the
25266 @var{shell-condition} could emit any kind of output you should instead
25267 use @command{AT_CHECK} like
25268 @example
25269 AT_CHECK([if @var{shell-condition}; then exit 77; fi])
25270 @end example
25271 @noindent
25272 so that such output is properly recorded in the @file{testsuite.log}
25273 file.
25274 @end defmac
25276 @defmac AT_XFAIL_IF (@var{shell-condition})
25277 @atindex{XFAIL_IF}
25278 Determine whether the test is expected to fail because it is a known
25279 bug (for unsupported features, you should skip the test).
25280 @var{shell-condition} is a shell expression such as a @code{test}
25281 command; you can instantiate this macro many times from within the
25282 same test group, and one of the conditions is enough to turn
25283 the test into an expected failure.
25284 @end defmac
25286 @defmac AT_CLEANUP
25287 @atindex{CLEANUP}
25288 End the current test group.
25289 @end defmac
25291 @sp 1
25293 @defmac AT_DATA (@var{file}, @var{contents})
25294 @defmacx AT_DATA_UNQUOTED (@var{file}, @var{contents})
25295 @atindex{DATA}
25296 Initialize an input data @var{file} with given @var{contents}.  Of
25297 course, the @var{contents} have to be properly quoted between square
25298 brackets to protect against included commas or spurious M4
25299 expansion.  @var{contents} must be empty or end with a newline.
25300 @var{file} must
25301 be a single shell word that expands into a single file name.
25303 The difference between @code{AT_DATA} and @code{AT_DATA_UNQUOTED} is
25304 that only the latter performs shell variable expansion (@samp{$}),
25305 command substitution (@samp{`}), and backslash escaping (@samp{\})
25306 on @var{contents}.
25307 @end defmac
25309 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25310   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25311 @defmacx AT_CHECK_UNQUOTED (@var{commands}, @dvar{status, 0}, @ovar{stdout}, @
25312   @ovar{stderr}, @ovar{run-if-fail}, @ovar{run-if-pass})
25313 @atindex{CHECK}
25314 @atindex{CHECK_UNQUOTED}
25315 @vrindex at_status
25316 Execute a test by performing given shell @var{commands} in a subshell.
25317 @var{commands} is output as-is, so shell expansions are honored.  These
25318 commands should normally exit with @var{status}, while producing expected
25319 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
25320 unexpected status 77, then the rest of the test group is skipped.  If
25321 @var{commands} exit with unexpected status 99, then the test group is
25322 immediately failed.  Otherwise, if this test fails, run shell commands
25323 @var{run-if-fail} or, if this test passes, run shell commands
25324 @var{run-if-pass}, both inside the current shell execution environment.
25325 At the beginning of @var{run-if-fail} and @var{run-if-pass}, the status of
25326 @var{commands} is available in the @code{at_status} shell variable.
25328 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25330 If @var{status} is the literal @samp{ignore}, then the corresponding
25331 exit status is not checked, except for the special cases of 77 (skip)
25332 and 99 (hard failure).  The existence of hard failures allows one to
25333 mark a test as an expected failure with @code{AT_XFAIL_IF} because a
25334 feature has not yet been implemented, but to still distinguish between
25335 gracefully handling the missing feature and dumping core.  A hard
25336 failure also inhibits post-test actions in @var{run-if-fail}.
25338 If the value of the @var{stdout} or @var{stderr} parameter is one of the
25339 literals in the following table, then the test treats the output
25340 according to the rules of that literal.  Otherwise, the value of the
25341 parameter is treated as text that must exactly match the output given by
25342 @var{commands} on standard output and standard error (including an empty
25343 parameter for no output); any differences are captured in the testsuite
25344 log and the test is failed (unless an unexpected exit status of 77
25345 skipped the test instead).  The difference between @code{AT_CHECK} and
25346 @code{AT_CHECK_UNQUOTED} is that only the latter performs shell variable
25347 expansion (@samp{$}), command substitution (@samp{`}), and backslash
25348 escaping (@samp{\}) on comparison text given in the @var{stdout} and
25349 @var{stderr} arguments; if the text includes a trailing newline, this
25350 would be the same as if it were specified via an unquoted
25351 here-document.  (However, there is no difference in the interpretation
25352 of @var{commands}).
25354 @table @samp
25355 @item ignore
25356 The content of the output is ignored, but still captured in the test
25357 group log (if the testsuite is run with option @option{-v}, the test
25358 group log is displayed as the test is run; if the test group later
25359 fails, the test group log is also copied into the overall testsuite
25360 log).  This action is valid for both @var{stdout} and @var{stderr}.
25362 @item ignore-nolog
25363 The content of the output is ignored, and nothing is captured in the log
25364 files.  If @var{commands} are likely to produce binary output (including
25365 long lines) or large amounts of output, then logging the output can make
25366 it harder to locate details related to subsequent tests within the
25367 group, and could potentially corrupt terminal display of a user running
25368 @command{testsuite -v}.
25370 @item stdout
25371 For the @var{stdout} parameter, capture the content of standard output
25372 to both the file @file{stdout} and the test group log.  Subsequent
25373 commands in the test group can then post-process the file.  This action
25374 is often used when it is desired to use @command{grep} to look for a
25375 substring in the output, or when the output must be post-processed to
25376 normalize error messages into a common form.
25378 @item stderr
25379 Like @samp{stdout}, except that it only works for the @var{stderr}
25380 parameter, and the standard error capture file will be named
25381 @file{stderr}.
25383 @item stdout-nolog
25384 @itemx stderr-nolog
25385 Like @samp{stdout} or @samp{stderr}, except that the captured output is
25386 not duplicated into the test group log.  This action is particularly
25387 useful for an intermediate check that produces large amounts of data,
25388 which will be followed by another check that filters down to the
25389 relevant data, as it makes it easier to locate details in the log.
25391 @item expout
25392 For the @var{stdout} parameter, compare standard output contents with
25393 the previously created file @file{expout}, and list any differences in
25394 the testsuite log.
25396 @item experr
25397 Like @samp{expout}, except that it only works for the @var{stderr}
25398 parameter, and the standard error contents are compared with
25399 @file{experr}.
25400 @end table
25401 @end defmac
25403 @defmac AT_CHECK_EUNIT (@var{module}, @var{test-spec}, @ovar{erlflags}, @
25404   @ovar{run-if-fail}, @ovar{run-if-pass})
25405 @atindex{CHECK_EUNIT}
25406 Initialize and execute an Erlang module named @var{module} that performs
25407 tests following the @var{test-spec} EUnit test specification.
25408 @var{test-spec} must be a valid EUnit test specification, as defined in
25409 the @uref{http://@/erlang.org/@/doc/@/apps/@/eunit/@/index.html, EUnit
25410 Reference Manual}.  @var{erlflags} are optional command-line options
25411 passed to the Erlang interpreter to execute the test Erlang module.
25412 Typically, @var{erlflags} defines at least the paths to directories
25413 containing the compiled Erlang modules under test, as @samp{-pa path1
25414 path2 ...}.
25416 For example, the unit tests associated with Erlang module @samp{testme},
25417 which compiled code is in subdirectory @file{src}, can be performed
25418 with:
25420 @example
25421 AT_CHECK_EUNIT([testme_testsuite], [@{module, testme@}],
25422                [-pa "$@{abs_top_builddir@}/src"])
25423 @end example
25425 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
25427 Variables @code{ERL}, @code{ERLC}, and (optionally) @code{ERLCFLAGS}
25428 must be defined as the path of the Erlang interpreter, the path of the
25429 Erlang compiler, and the command-line flags to pass to the compiler,
25430 respectively.  Those variables should be configured in
25431 @file{configure.ac} using the @command{AC_ERLANG_PATH_ERL} and
25432 @command{AC_ERLANG_PATH_ERLC} macros, and the configured values of those
25433 variables are automatically defined in the testsuite.  If @code{ERL} or
25434 @code{ERLC} is not defined, the test group is skipped.
25436 If the EUnit library cannot be found, i.e. if module @code{eunit} cannot
25437 be loaded, the test group is skipped.  Otherwise, if @var{test-spec} is
25438 an invalid EUnit test specification, the test group fails.  Otherwise,
25439 if the EUnit test passes, shell commands @var{run-if-pass} are executed
25440 or, if the EUnit test fails, shell commands @var{run-if-fail} are
25441 executed and the test group fails.
25443 Only the generated test Erlang module is automatically compiled and
25444 executed.  If @var{test-spec} involves testing other Erlang modules,
25445 e.g. module @samp{testme} in the example above, those modules must be
25446 already compiled.
25448 If the testsuite is run in verbose mode, with option @option{--verbose},
25449 EUnit is also run in verbose mode to output more details about
25450 individual unit tests.
25451 @end defmac
25454 @node testsuite Invocation
25455 @section Running @command{testsuite} Scripts
25456 @cindex @command{testsuite}
25458 Autotest test suites support the following options:
25460 @table @option
25461 @item --help
25462 @itemx -h
25463 Display the list of options and exit successfully.
25465 @item --version
25466 @itemx -V
25467 Display the version of the test suite and exit successfully.
25469 @item --directory=@var{dir}
25470 @itemx -C @var{dir}
25471 Change the current directory to @var{dir} before creating any files.
25472 Useful for running the testsuite in a subdirectory from a top-level
25473 Makefile.
25475 @item --jobs@r{[}=@var{n}@r{]}
25476 @itemx -j@ovar{n}
25477 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
25478 run all given tests in parallel.  Note that there should be no space
25479 before the argument to @option{-j}, as @option{-j @var{number}} denotes
25480 the separate arguments @option{-j} and @option{@var{number}}, see below.
25482 In parallel mode, the standard input device of the testsuite script is
25483 not available to commands inside a test group.  Furthermore, banner
25484 lines are not printed, and the summary line for each test group is
25485 output after the test group completes.  Summary lines may appear
25486 unordered.  If verbose and trace output are enabled (see below), they
25487 may appear intermixed from concurrently running tests.
25489 Parallel mode requires the @command{mkfifo} command to work, and will be
25490 silently disabled otherwise.
25492 @item --clean
25493 @itemx -c
25494 Remove all the files the test suite might have created and exit.  Meant
25495 for @code{clean} Make targets.
25497 @item --list
25498 @itemx -l
25499 List all the tests (or only the selection), including their possible
25500 keywords.
25501 @end table
25503 @sp 1
25505 By default all tests are performed (or described with @option{--list})
25506 silently in the default environment, but the environment, set of tests,
25507 and verbosity level can be tuned:
25509 @table @samp
25510 @item @var{variable}=@var{value}
25511 Set the environment @var{variable} to @var{value}.  Use this rather
25512 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
25513 different environment.
25515 @cindex @code{AUTOTEST_PATH}
25516 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
25517 to @env{PATH}.  Relative directory names (not starting with
25518 @samp{/}) are considered to be relative to the top level of the
25519 package being built.  All directories are made absolute, first
25520 starting from the top level @emph{build} tree, then from the
25521 @emph{source} tree.  For instance @samp{./testsuite
25522 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
25523 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
25524 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
25525 @env{PATH}.
25527 @item @var{number}
25528 @itemx @var{number}-@var{number}
25529 @itemx @var{number}-
25530 @itemx -@var{number}
25531 Add the corresponding test groups, with obvious semantics, to the
25532 selection.
25534 @item --keywords=@var{keywords}
25535 @itemx -k @var{keywords}
25536 Add to the selection the test groups with title or keywords (arguments
25537 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
25538 of the comma separated list @var{keywords}, case-insensitively.  Use
25539 @samp{!} immediately before the keyword to invert the selection for this
25540 keyword.  By default, the keywords match whole words; enclose them in
25541 @samp{.*} to also match parts of words.
25543 For example, running
25545 @example
25546 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
25547 @end example
25549 @noindent
25550 selects all tests tagged @samp{autoupdate} @emph{and} with tags
25551 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
25552 etc.), while
25554 @example
25555 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
25556 @end example
25558 @noindent
25559 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
25560 containing @samp{FUNC}.
25562 @item --errexit
25563 @itemx -e
25564 If any test fails, immediately abort testing.  This implies
25565 @option{--debug}: post test group clean up, and top-level logging
25566 are inhibited.  This option is meant for the full test
25567 suite, it is not really useful for generated debugging scripts.
25568 If the testsuite is run in parallel mode using @option{--jobs},
25569 then concurrently running tests will finish before exiting.
25571 @item --verbose
25572 @itemx -v
25573 Force more verbosity in the detailed output of what is being done.  This
25574 is the default for debugging scripts.
25576 @item --color
25577 @itemx --color@r{[}=never@r{|}auto@r{|}always@r{]}
25578 Enable colored test results.  Without an argument, or with @samp{always},
25579 test results will be colored.  With @samp{never}, color mode is turned
25580 off.  Otherwise, if either the macro @code{AT_COLOR_TESTS} is used by
25581 the testsuite author, or the argument @samp{auto} is given, then test
25582 results are colored if standard output is connected to a terminal.
25584 @item --debug
25585 @itemx -d
25586 Do not remove the files after a test group was performed---but they are
25587 still removed @emph{before}, therefore using this option is sane when
25588 running several test groups.  Create debugging scripts.  Do not
25589 overwrite the top-level
25590 log (in order to preserve a supposedly existing full log file).  This is
25591 the default for debugging scripts, but it can also be useful to debug
25592 the testsuite itself.
25594 @item --recheck
25595 Add to the selection all test groups that failed or passed unexpectedly
25596 during the last non-debugging test run.
25598 @item --trace
25599 @itemx -x
25600 Trigger shell tracing of the test groups.
25601 @end table
25603 Besides these options accepted by every Autotest testsuite, the
25604 testsuite author might have added package-specific options
25605 via the @code{AT_ARG_OPTION} and @code{AT_ARG_OPTION_ARG} macros
25606 (@pxref{Writing Testsuites}); refer to @command{testsuite --help} and
25607 the package documentation for details.
25610 @node Making testsuite Scripts
25611 @section Making @command{testsuite} Scripts
25613 For putting Autotest into movement, you need some configuration and
25614 makefile machinery.  We recommend, at least if your package uses deep or
25615 shallow hierarchies, that you use @file{tests/} as the name of the
25616 directory holding all your tests and their makefile.  Here is a
25617 check list of things to do, followed by an example, taking into
25618 consideration whether you are also using Automake.
25620 @itemize @minus
25622 @item
25623 @cindex @file{package.m4}
25624 @atindex{PACKAGE_STRING}
25625 @atindex{PACKAGE_BUGREPORT}
25626 @atindex{PACKAGE_NAME}
25627 @atindex{PACKAGE_TARNAME}
25628 @atindex{PACKAGE_VERSION}
25629 @atindex{PACKAGE_URL}
25630 Make sure to create the file @file{package.m4}, which defines the
25631 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
25632 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
25633 address to which bug reports should be sent.  For sake of completeness,
25634 we suggest that you also define @code{AT_PACKAGE_NAME},
25635 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
25636 @code{AT_PACKAGE_URL}.
25637 @xref{Initializing configure}, for a description of these variables.
25638 Be sure to distribute @file{package.m4} and to put it into the source
25639 hierarchy: the test suite ought to be shipped!  See below for an example.
25641 @item
25642 Invoke @code{AC_CONFIG_TESTDIR} in your @file{configure.ac}.
25644 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvarv{test-path, directory})
25645 @acindex{CONFIG_TESTDIR}
25646 An Autotest test suite is to be configured in @var{directory}.  This
25647 macro causes @file{@var{directory}/atconfig} to be created by
25648 @command{config.status} and sets the default @code{AUTOTEST_PATH} to
25649 @var{test-path} (@pxref{testsuite Invocation}).
25650 @end defmac
25652 @item
25653 Still within @file{configure.ac}, as appropriate, ensure that some
25654 @code{AC_CONFIG_FILES} command includes substitution for
25655 @file{tests/atlocal}.
25657 @item
25658 Also within your @file{configure.ac}, arrange for the @code{AUTOM4TE}
25659 variable to be set.
25661 @item
25662 The appropriate @file{Makefile} should be modified so the validation in
25663 your package is triggered by @samp{make check}.
25664 @end itemize
25666 The following example demonstrates the above checklist, first by
25667 assuming that you are using Automake (see below for tweaks to make to
25668 get the same results without Automake).  Begin by adding the following
25669 lines to your @file{configure.ac}:
25671 @example
25672 # Initialize the test suite.
25673 AC_CONFIG_TESTDIR([tests])
25674 AC_CONFIG_FILES([tests/Makefile tests/atlocal])
25675 AM_MISSING_PROG([AUTOM4TE], [autom4te])
25676 @end example
25678 Next, add the following lines to your @file{tests/Makefile.am}, in order
25679 to link @samp{make check} with a validation suite.
25681 @example
25682 # The `:;' works around a Bash 3.2 bug when the output is not writable.
25683 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
25684         :;@{ \
25685           echo '# Signature of the current package.' && \
25686           echo 'm4_define([AT_PACKAGE_NAME],' && \
25687           echo '  [$(PACKAGE_NAME)])' && \
25688           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
25689           echo '  [$(PACKAGE_TARNAME)])' && \
25690           echo 'm4_define([AT_PACKAGE_VERSION],' && \
25691           echo '  [$(PACKAGE_VERSION)])' && \
25692           echo 'm4_define([AT_PACKAGE_STRING],' && \
25693           echo '  [$(PACKAGE_STRING)])' && \
25694           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
25695           echo '  [$(PACKAGE_BUGREPORT)])'; \
25696           echo 'm4_define([AT_PACKAGE_URL],' && \
25697           echo '  [$(PACKAGE_URL)])'; \
25698         @} >'$(srcdir)/package.m4'
25700 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
25701 TESTSUITE = $(srcdir)/testsuite
25703 check-local: atconfig atlocal $(TESTSUITE)
25704         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
25706 installcheck-local: atconfig atlocal $(TESTSUITE)
25707         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
25708           $(TESTSUITEFLAGS)
25710 clean-local:
25711         test ! -f '$(TESTSUITE)' || \
25712          $(SHELL) '$(TESTSUITE)' --clean
25714 AUTOTEST = $(AUTOM4TE) --language=autotest
25715 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
25716         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
25717         mv $@@.tmp $@@
25718 @end example
25720 Note that the built testsuite is distributed; this is necessary because
25721 users might not have Autoconf installed, and thus would not be able to
25722 rebuild it.  Likewise, the use of Automake's @code{AM_MISSING_PROG} will
25723 arrange for the definition of @code{$AUTOM4TE} within the Makefile to
25724 provide the user with
25725 a nicer error message if they modify a source file to the testsuite, and
25726 accidentally trigger the rebuild rules.
25728 You might want to list explicitly the dependencies, i.e., the list of
25729 the files @file{testsuite.at} includes.
25731 If you don't use Automake, you should make the following tweaks.  In
25732 your @file{configure.ac}, replace the @code{AM_MISSING_PROG} line above
25733 with @code{AC_PATH_PROG([AUTOM4TE], [autom4te], [false])}.  You are
25734 welcome to also try using the @command{missing} script from the Automake
25735 project instead of @command{false}, to try to get a nicer error message
25736 when the user modifies prerequisites but did not have Autoconf
25737 installed, but at that point you may be better off using Automake.
25738 Then, take the code suggested above for @file{tests/@/Makefile.am} and
25739 place it in your @file{tests/@/Makefile.in} instead.  Add code to your
25740 @file{tests/@/Makefile.in} to ensure that @code{$(EXTRA_DIST)} files are
25741 distributed, as well as adding the following additional lines to prepare
25742 the set of needed Makefile variables:
25744 @example
25745 subdir = tests
25746 PACKAGE_NAME = @@PACKAGE_NAME@@
25747 PACKAGE_TARNAME = @@PACKAGE_TARNAME@@
25748 PACKAGE_VERSION = @@PACKAGE_VERSION@@
25749 PACKAGE_STRING = @@PACKAGE_STRING@@
25750 PACKAGE_BUGREPORT = @@PACKAGE_BUGREPORT@@
25751 PACKAGE_URL = @@PACKAGE_URL@@
25752 AUTOM4TE = @@AUTOM4TE@@
25754 atconfig: $(top_builddir)/config.status
25755         cd $(top_builddir) && \
25756            $(SHELL) ./config.status $(subdir)/$@@
25758 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
25759         cd $(top_builddir) && \
25760            $(SHELL) ./config.status $(subdir)/$@@
25761 @end example
25763 Using the above example (with or without Automake), and assuming you
25764 were careful to not initialize @samp{TESTSUITEFLAGS} within your
25765 makefile, you can now fine-tune test suite execution at runtime by
25766 altering this variable, for example:
25768 @example
25769 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
25770 @end example
25774 @c =============================== Frequent Autoconf Questions, with answers
25776 @node FAQ
25777 @chapter Frequent Autoconf Questions, with answers
25779 Several questions about Autoconf come up occasionally.  Here some of them
25780 are addressed.
25782 @menu
25783 * Distributing::                Distributing @command{configure} scripts
25784 * Why GNU M4::                  Why not use the standard M4?
25785 * Bootstrapping::               Autoconf and GNU M4 require each other?
25786 * Why Not Imake::               Why GNU uses @command{configure} instead of Imake
25787 * Defining Directories::        Passing @code{datadir} to program
25788 * Autom4te Cache::              What is it?  Can I remove it?
25789 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
25790 * Expanded Before Required::    Expanded Before Required
25791 * Debugging::                   Debugging @command{configure} scripts
25792 @end menu
25794 @node Distributing
25795 @section Distributing @command{configure} Scripts
25796 @cindex License
25798 @display
25799 What are the restrictions on distributing @command{configure}
25800 scripts that Autoconf generates?  How does that affect my
25801 programs that use them?
25802 @end display
25804 There are no restrictions on how the configuration scripts that Autoconf
25805 produces may be distributed or used.  In Autoconf version 1, they were
25806 covered by the GNU General Public License.  We still encourage
25807 software authors to distribute their work under terms like those of the
25808 GPL, but doing so is not required to use Autoconf.
25810 Of the other files that might be used with @command{configure},
25811 @file{config.h.in} is under whatever copyright you use for your
25812 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
25813 exception to the GPL when they are used with an Autoconf-generated
25814 @command{configure} script, which permits you to distribute them under the
25815 same terms as the rest of your package.  @file{install-sh} is from the X
25816 Consortium and is not copyrighted.
25818 @node Why GNU M4
25819 @section Why Require GNU M4?
25821 @display
25822 Why does Autoconf require GNU M4?
25823 @end display
25825 Many M4 implementations have hard-coded limitations on the size and
25826 number of macros that Autoconf exceeds.  They also lack several
25827 builtin macros that it would be difficult to get along without in a
25828 sophisticated application like Autoconf, including:
25830 @example
25831 m4_builtin
25832 m4_indir
25833 m4_bpatsubst
25834 __file__
25835 __line__
25836 @end example
25838 Autoconf requires version 1.4.6 or later of GNU M4.
25840 Since only software maintainers need to use Autoconf, and since GNU
25841 M4 is simple to configure and install, it seems reasonable to require
25842 GNU M4 to be installed also.  Many maintainers of GNU and
25843 other free software already have most of the GNU utilities
25844 installed, since they prefer them.
25846 @node Bootstrapping
25847 @section How Can I Bootstrap?
25848 @cindex Bootstrap
25850 @display
25851 If Autoconf requires GNU M4 and GNU M4 has an Autoconf
25852 @command{configure} script, how do I bootstrap?  It seems like a chicken
25853 and egg problem!
25854 @end display
25856 This is a misunderstanding.  Although GNU M4 does come with a
25857 @command{configure} script produced by Autoconf, Autoconf is not required
25858 in order to run the script and install GNU M4.  Autoconf is only
25859 required if you want to change the M4 @command{configure} script, which few
25860 people have to do (mainly its maintainer).
25862 @node Why Not Imake
25863 @section Why Not Imake?
25864 @cindex Imake
25866 @display
25867 Why not use Imake instead of @command{configure} scripts?
25868 @end display
25870 Several people have written addressing this question, so
25871 adaptations of their explanations are included here.
25873 The following answer is based on one written by Richard Pixley:
25875 @quotation
25876 Autoconf generated scripts frequently work on machines that it has
25877 never been set up to handle before.  That is, it does a good job of
25878 inferring a configuration for a new system.  Imake cannot do this.
25880 Imake uses a common database of host specific data.  For X11, this makes
25881 sense because the distribution is made as a collection of tools, by one
25882 central authority who has control over the database.
25884 GNU tools are not released this way.  Each GNU tool has a
25885 maintainer; these maintainers are scattered across the world.  Using a
25886 common database would be a maintenance nightmare.  Autoconf may appear
25887 to be this kind of database, but in fact it is not.  Instead of listing
25888 host dependencies, it lists program requirements.
25890 If you view the GNU suite as a collection of native tools, then the
25891 problems are similar.  But the GNU development tools can be
25892 configured as cross tools in almost any host+target permutation.  All of
25893 these configurations can be installed concurrently.  They can even be
25894 configured to share host independent files across hosts.  Imake doesn't
25895 address these issues.
25897 Imake templates are a form of standardization.  The GNU coding
25898 standards address the same issues without necessarily imposing the same
25899 restrictions.
25900 @end quotation
25903 Here is some further explanation, written by Per Bothner:
25905 @quotation
25906 One of the advantages of Imake is that it is easy to generate large
25907 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
25908 However, @code{cpp} is not programmable: it has limited conditional
25909 facilities, and no looping.  And @code{cpp} cannot inspect its
25910 environment.
25912 All of these problems are solved by using @code{sh} instead of
25913 @code{cpp}.  The shell is fully programmable, has macro substitution,
25914 can execute (or source) other shell scripts, and can inspect its
25915 environment.
25916 @end quotation
25919 Paul Eggert elaborates more:
25921 @quotation
25922 With Autoconf, installers need not assume that Imake itself is already
25923 installed and working well.  This may not seem like much of an advantage
25924 to people who are accustomed to Imake.  But on many hosts Imake is not
25925 installed or the default installation is not working well, and requiring
25926 Imake to install a package hinders the acceptance of that package on
25927 those hosts.  For example, the Imake template and configuration files
25928 might not be installed properly on a host, or the Imake build procedure
25929 might wrongly assume that all source files are in one big directory
25930 tree, or the Imake configuration might assume one compiler whereas the
25931 package or the installer needs to use another, or there might be a
25932 version mismatch between the Imake expected by the package and the Imake
25933 supported by the host.  These problems are much rarer with Autoconf,
25934 where each package comes with its own independent configuration
25935 processor.
25937 Also, Imake often suffers from unexpected interactions between
25938 @command{make} and the installer's C preprocessor.  The fundamental problem
25939 here is that the C preprocessor was designed to preprocess C programs,
25940 not makefiles.  This is much less of a problem with Autoconf,
25941 which uses the general-purpose preprocessor M4, and where the
25942 package's author (rather than the installer) does the preprocessing in a
25943 standard way.
25944 @end quotation
25947 Finally, Mark Eichin notes:
25949 @quotation
25950 Imake isn't all that extensible, either.  In order to add new features to
25951 Imake, you need to provide your own project template, and duplicate most
25952 of the features of the existing one.  This means that for a sophisticated
25953 project, using the vendor-provided Imake templates fails to provide any
25954 leverage---since they don't cover anything that your own project needs
25955 (unless it is an X11 program).
25957 On the other side, though:
25959 The one advantage that Imake has over @command{configure}:
25960 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
25961 than @file{Makefile.in} files.  There is a fix to this, however---at least
25962 for the Kerberos V5 tree, we've modified things to call in common
25963 @file{post.in} and @file{pre.in} makefile fragments for the
25964 entire tree.  This means that a lot of common things don't have to be
25965 duplicated, even though they normally are in @command{configure} setups.
25966 @end quotation
25969 @node Defining Directories
25970 @section How Do I @code{#define} Installation Directories?
25972 @display
25973 My program needs library files, installed in @code{datadir} and
25974 similar.  If I use
25976 @example
25977 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
25978   [Define to the read-only architecture-independent
25979    data directory.])
25980 @end example
25982 @noindent
25983 I get
25985 @example
25986 #define DATADIR "$@{prefix@}/share"
25987 @end example
25988 @end display
25990 As already explained, this behavior is on purpose, mandated by the
25991 GNU Coding Standards, see @ref{Installation Directory
25992 Variables}.  There are several means to achieve a similar goal:
25994 @itemize @minus
25995 @item
25996 Do not use @code{AC_DEFINE} but use your makefile to pass the
25997 actual value of @code{datadir} via compilation flags.
25998 @xref{Installation Directory Variables}, for the details.
26000 @item
26001 This solution can be simplified when compiling a program: you may either
26002 extend the @code{CPPFLAGS}:
26004 @example
26005 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
26006 @end example
26008 @noindent
26009 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
26011 @example
26012 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
26013 @end example
26015 @noindent
26016 Alternatively, create a dedicated header file:
26018 @example
26019 DISTCLEANFILES = myprog-paths.h
26020 myprog-paths.h: Makefile
26021         echo '#define DATADIR "$(datadir)"' >$@@
26022 @end example
26024 @noindent
26025 The gnulib module @samp{configmake} provides such a header with all the
26026 standard directory variables defined, @pxref{configmake,,, gnulib, GNU
26027 Gnulib}.
26029 @item
26030 Use @code{AC_DEFINE} but have @command{configure} compute the literal
26031 value of @code{datadir} and others.  Many people have wrapped macros to
26032 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
26033 the @uref{http://@/www.gnu.org/@/software/@/autoconf-archive/, Autoconf Macro
26034 Archive}.
26036 This solution does not conform to the GNU Coding Standards.
26038 @item
26039 Note that all the previous solutions hard wire the absolute name of
26040 these directories in the executables, which is not a good property.  You
26041 may try to compute the names relative to @code{prefix}, and try to
26042 find @code{prefix} at runtime, this way your package is relocatable.
26043 @end itemize
26046 @node Autom4te Cache
26047 @section What is @file{autom4te.cache}?
26049 @display
26050 What is this directory @file{autom4te.cache}?  Can I safely remove it?
26051 @end display
26053 In the GNU Build System, @file{configure.ac} plays a central
26054 role and is read by many tools: @command{autoconf} to create
26055 @file{configure}, @command{autoheader} to create @file{config.h.in},
26056 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
26057 check the completeness of @file{configure.ac}, @command{autoreconf} to
26058 check the GNU Build System components that are used.  To
26059 ``read @file{configure.ac}'' actually means to compile it with M4,
26060 which can be a long process for complex @file{configure.ac}.
26062 This is why all these tools, instead of running directly M4, invoke
26063 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
26064 a specific demand, stores additional information in
26065 @file{autom4te.cache} for future runs.  For instance, if you run
26066 @command{autoconf}, behind the scenes, @command{autom4te} also
26067 stores information for the other tools, so that when you invoke
26068 @command{autoheader} or @command{automake} etc., reprocessing
26069 @file{configure.ac} is not needed.  The speed up is frequently 30%,
26070 and is increasing with the size of @file{configure.ac}.
26072 But it is and remains being simply a cache: you can safely remove it.
26074 @sp 1
26076 @display
26077 Can I permanently get rid of it?
26078 @end display
26080 The creation of this cache can be disabled from
26081 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
26082 details.  You should be aware that disabling the cache slows down the
26083 Autoconf test suite by 40%.  The more GNU Build System
26084 components are used, the more the cache is useful; for instance
26085 running @samp{autoreconf -f} on the Core Utilities is twice slower without
26086 the cache @emph{although @option{--force} implies that the cache is
26087 not fully exploited}, and eight times slower than without
26088 @option{--force}.
26091 @node Present But Cannot Be Compiled
26092 @section Header Present But Cannot Be Compiled
26094 The most important guideline to bear in mind when checking for
26095 features is to mimic as much as possible the intended use.
26096 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
26097 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
26098 the preprocessor, instead of the compiler, to check for headers.  As a
26099 result, incompatibilities between headers went unnoticed during
26100 configuration, and maintainers finally had to deal with this issue
26101 elsewhere.
26103 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
26104 checks are performed, and @command{configure} complains loudly if the
26105 compiler and the preprocessor do not agree.  However, only the compiler
26106 result is considered.  As of Autoconf 2.70, only the compiler check is
26107 performed.
26109 Consider the following example:
26111 @smallexample
26112 $ @kbd{cat number.h}
26113 typedef int number;
26114 $ @kbd{cat pi.h}
26115 const number pi = 3;
26116 $ @kbd{cat configure.ac}
26117 AC_INIT([Example], [1.0], [bug-example@@example.org])
26118 AC_CHECK_HEADERS([pi.h])
26119 $ @kbd{autoconf -Wall}
26120 $ @kbd{./configure CPPFLAGS='-I.'}
26121 checking for gcc... gcc
26122 checking whether the C compiler works... yes
26123 checking for C compiler default output file name... a.out
26124 checking for suffix of executables...
26125 checking whether we are cross compiling... no
26126 checking for suffix of object files... o
26127 checking whether the compiler supports GNU C... yes
26128 checking whether gcc accepts -g... yes
26129 checking for gcc option to enable C11 features... -std=gnu11
26130 checking for sys/types.h... yes
26131 checking for sys/stat.h... yes
26132 checking for strings.h... yes
26133 checking for inttypes.h... yes
26134 checking for stdint.h... yes
26135 checking for unistd.h... yes
26136 checking for pi.h... no
26137 @end smallexample
26139 @noindent
26140 The proper way to handle this case is using the fourth argument
26141 (@pxref{Generic Headers}):
26143 @example
26144 $ @kbd{cat configure.ac}
26145 AC_INIT([Example], [1.0], [bug-example@@example.org])
26146 AC_CHECK_HEADERS([number.h pi.h], [], [],
26147 [[#ifdef HAVE_NUMBER_H
26148 # include <number.h>
26149 #endif
26151 $ @kbd{autoconf -Wall}
26152 $ @kbd{./configure CPPFLAGS='-I.'}
26153 checking for gcc... gcc
26154 checking whether the C compiler works... yes
26155 checking for C compiler default output file name... a.out
26156 checking for suffix of executables...
26157 checking whether we are cross compiling... no
26158 checking for suffix of object files... o
26159 checking whether the compiler supports GNU C... yes
26160 checking whether gcc accepts -g... yes
26161 checking for gcc option to enable C11 features... -std=gnu11
26162 checking for number.h... yes
26163 checking for pi.h... yes
26164 @end example
26166 See @ref{Particular Headers}, for a list of headers with their
26167 prerequisites.
26169 @node Expanded Before Required
26170 @section Expanded Before Required
26172 @cindex expanded before required
26173 Older versions of Autoconf silently built files with incorrect ordering
26174 between dependent macros if an outer macro first expanded, then later
26175 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
26176 situation no longer generates out-of-order code, but results in
26177 duplicate output and a syntax warning:
26179 @example
26180 $ @kbd{cat configure.ac}
26181 @result{}AC_DEFUN([TESTA], [[echo in A
26182 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
26183 @result{}SEEN_A=:]])
26184 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
26185 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
26186 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
26187 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
26188 @result{}TESTA
26189 @result{}TESTC])
26190 @result{}AC_INIT
26191 @result{}OUTER
26192 @result{}AC_OUTPUT
26193 $ @kbd{autoconf}
26194 @result{}configure.ac:11: warning: AC_REQUIRE:
26195 @result{} `TESTA' was expanded before it was required
26196 @result{}configure.ac:4: TESTB is expanded from...
26197 @result{}configure.ac:6: TESTC is expanded from...
26198 @result{}configure.ac:7: OUTER is expanded from...
26199 @result{}configure.ac:11: the top level
26200 @end example
26202 @noindent
26203 To avoid this warning, decide what purpose the macro in question serves.
26204 If it only needs to be expanded once (for example, if it provides
26205 initialization text used by later macros), then the simplest fix is to
26206 change the macro to be declared with @code{AC_DEFUN_ONCE}
26207 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
26208 newer.  A more portable fix is to change all
26209 instances of direct calls to instead go through @code{AC_REQUIRE}
26210 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
26211 by arguments or by the current definition of other macros in the m4
26212 environment, then the macro should always be directly expanded instead
26213 of required.
26215 For another case study, consider this example trimmed down from an
26216 actual package.  Originally, the package contained shell code and
26217 multiple macro invocations at the top level of @file{configure.ac}:
26219 @example
26220 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26221 foobar=
26222 AC_PROG_CC
26224 @end example
26226 @noindent
26227 but that was getting complex, so the author wanted to offload some of
26228 the text into a new macro in another file included via
26229 @file{aclocal.m4}.  The na@"ive approach merely wraps the text in a new
26230 macro:
26232 @example
26233 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26234 AC_DEFUN([BAR], [
26235 foobar=
26236 AC_PROG_CC
26240 @end example
26242 @noindent
26243 With older versions of Autoconf, the setting of @samp{foobar=} occurs
26244 before the single compiler check, as the author intended.  But with
26245 Autoconf 2.64, this issues the ``expanded before it was required''
26246 warning for @code{AC_PROG_CC}, and outputs two copies of the compiler
26247 check, one before @samp{foobar=}, and one after.  To understand why this
26248 is happening, remember that the use of @code{AC_COMPILE_IFELSE} includes
26249 a call to @code{AC_REQUIRE([AC_PROG_CC])} under the hood.  According to
26250 the documented semantics of @code{AC_REQUIRE}, this means that
26251 @code{AC_PROG_CC} @emph{must} occur before the body of the outermost
26252 @code{AC_DEFUN}, which in this case is @code{BAR}, thus preceding the
26253 use of @samp{foobar=}.  The older versions of Autoconf were broken with
26254 regards to the rules of @code{AC_REQUIRE}, which explains why the code
26255 changed from one over to two copies of @code{AC_PROG_CC} when upgrading
26256 autoconf.  In other words, the author was unknowingly relying on a bug
26257 exploit to get the desired results, and that exploit broke once the bug
26258 was fixed.
26260 So, what recourse does the author have, to restore their intended
26261 semantics of setting @samp{foobar=} prior to a single compiler check,
26262 regardless of whether Autoconf 2.63 or 2.64 is used?  One idea is to
26263 remember that only @code{AC_DEFUN} is impacted by @code{AC_REQUIRE};
26264 there is always the possibility of using the lower-level
26265 @code{m4_define}:
26267 @example
26268 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26269 m4_define([BAR], [
26270 foobar=
26271 AC_PROG_CC
26275 @end example
26277 @noindent
26278 This works great if everything is in the same file.  However, it does
26279 not help in the case where the author wants to have @command{aclocal}
26280 find the definition of @code{BAR} from its own file, since
26281 @command{aclocal} requires the use of @code{AC_DEFUN}.  In this case, a
26282 better fix is to recognize that if @code{BAR} also uses
26283 @code{AC_REQUIRE}, then there will no longer be direct expansion prior
26284 to a subsequent require.  Then, by creating yet another helper macro,
26285 the author can once again guarantee a single invocation of
26286 @code{AC_PROG_CC}, which will still occur after @code{foobar=}.  The
26287 author can also use @code{AC_BEFORE} to make sure no other macro
26288 appearing before @code{BAR} has triggered an unwanted expansion of
26289 @code{AC_PROG_CC}.
26291 @example
26292 AC_DEFUN([FOO], [AC_COMPILE_IFELSE([@dots{}])])
26293 AC_DEFUN([BEFORE_CC], [
26294 foobar=
26296 AC_DEFUN([BAR], [
26297 AC_BEFORE([$0], [AC_PROG_CC])dnl
26298 AC_REQUIRE([BEFORE_CC])dnl
26299 AC_REQUIRE([AC_PROG_CC])dnl
26303 @end example
26306 @node Debugging
26307 @section Debugging @command{configure} scripts
26309 While in general, @command{configure} scripts generated by Autoconf
26310 strive to be fairly portable to various systems, compilers, shells, and
26311 other tools, it may still be necessary to debug a failing test, broken
26312 script or makefile, or fix or override an incomplete, faulty, or erroneous
26313 test, especially during macro development.  Failures can occur at all levels,
26314 in M4 syntax or semantics, shell script issues, or due to bugs in the
26315 test or the tools invoked by @command{configure}.  Together with the
26316 rather arcane error message that @command{m4} and @command{make} may
26317 produce when their input contains syntax errors, this can make debugging
26318 rather painful.
26320 Nevertheless, here is a list of hints and strategies that may help:
26322 @itemize
26323 @item
26324 When @command{autoconf} fails, common causes for error include:
26326 @itemize
26327 @item
26328 mismatched or unbalanced parentheses or braces (@pxref{Balancing
26329 Parentheses}),
26331 @item under- or overquoted macro arguments (@pxref{Autoconf
26332 Language}, @pxref{Quoting and Parameters}, @pxref{Quotation and Nested
26333 Macros}),
26335 @item spaces between macro name and opening parenthesis (@pxref{Autoconf
26336 Language}).
26337 @end itemize
26339 Typically, it helps to go back to the last working version of the input
26340 and compare the differences for each of these errors.  Another
26341 possibility is to sprinkle pairs of @code{m4_traceon} and
26342 @code{m4_traceoff} judiciously in the code, either without a parameter
26343 or listing some macro names and watch @command{m4} expand its input
26344 verbosely (@pxref{Debugging via autom4te}).
26346 @item
26347 Sometimes @command{autoconf} succeeds but the generated
26348 @command{configure} script has invalid shell syntax.  You can detect this
26349 case by running @samp{bash -n configure} or @samp{sh -n configure}.
26350 If this command fails, the same tips apply, as if @command{autoconf} had
26351 failed.
26353 @item
26354 Debugging @command{configure} script execution may be done by sprinkling
26355 pairs of @code{set -x} and @code{set +x} into the shell script before
26356 and after the region that contains a bug.  Running the whole script with
26357 @samp{@var{shell} -vx ./configure 2>&1 | tee @var{log-file}} with a decent
26358 @var{shell} may work, but produces lots of output.  Here, it can help to
26359 search for markers like @samp{checking for} a particular test in the
26360 @var{log-file}.
26362 @item
26363 Alternatively, you might use a shell with debugging capabilities like
26364 @uref{http://bashdb.sourceforge.net/, bashdb}.
26366 @item
26367 When @command{configure} tests produce invalid results for your system,
26368 it may be necessary to override them:
26370 @itemize
26371 @item
26372 For programs, tools or libraries variables, preprocessor, compiler, or
26373 linker flags, it is often sufficient to override them at @command{make}
26374 run time with some care (@pxref{Macros and Submakes}).  Since this
26375 normally won't cause @command{configure} to be run again with these
26376 changed settings, it may fail if the changed variable would have caused
26377 different test results from @command{configure}, so this may work only
26378 for simple differences.
26380 @item
26381 Most tests which produce their result in a substituted variable allow to
26382 override the test by setting the variable on the @command{configure}
26383 command line (@pxref{Compilers and Options}, @pxref{Defining Variables},
26384 @pxref{Particular Systems}).
26386 @item
26387 Many tests store their result in a cache variable (@pxref{Caching
26388 Results}).  This lets you override them either on the
26389 @command{configure} command line as above, or through a primed cache or
26390 site file (@pxref{Cache Files}, @pxref{Site Defaults}).  The name of a
26391 cache variable is documented with a test macro or may be inferred from
26392 @ref{Cache Variable Names}; the precise semantics of undocumented
26393 variables are often internal details, subject to change.
26394 @end itemize
26396 @item
26397 Alternatively, @command{configure} may produce invalid results because
26398 of uncaught programming errors, in your package or in an upstream
26399 library package.  For example, when @code{AC_CHECK_LIB} fails to find a
26400 library with a specified function, always check @file{config.log}.  This
26401 will reveal the exact error that produced the failing result: the
26402 library linked by @code{AC_CHECK_LIB} probably has a fatal bug.
26403 @end itemize
26405 Conversely, as macro author, you can make it easier for users of your
26406 macro:
26408 @itemize
26409 @item
26410 by minimizing dependencies between tests and between test results as far
26411 as possible,
26413 @item
26414 by using @command{make} variables to factorize and allow
26415 override of settings at @command{make} run time,
26417 @item
26418 by honoring the GNU Coding Standards and not overriding flags
26419 reserved for the user except temporarily during @command{configure}
26420 tests,
26422 @item
26423 by not requiring users of your macro to use the cache variables.
26424 Instead, expose the result of the test via @var{run-if-true} and
26425 @var{run-if-false} parameters.  If the result is not a boolean,
26426 then provide it through documented shell variables.
26427 @end itemize
26430 @c ===================================================== History of Autoconf.
26432 @node History
26433 @chapter History of Autoconf
26434 @cindex History of autoconf
26436 @emph{This chapter was written by the original author, David MacKenzie.}
26438 You may be wondering, Why was Autoconf originally written?  How did it
26439 get into its present form?  (Why does it look like gorilla spit?)  If
26440 you're not wondering, then this chapter contains no information useful
26441 to you, and you might as well skip it.  If you @emph{are} wondering,
26442 then let there be light@enddots{}
26444 @menu
26445 * Genesis::                     Prehistory and naming of @command{configure}
26446 * Exodus::                      The plagues of M4 and Perl
26447 * Leviticus::                   The priestly code of portability arrives
26448 * Numbers::                     Growth and contributors
26449 * Deuteronomy::                 Approaching the promises of easy configuration
26450 @end menu
26452 @node Genesis
26453 @section Genesis
26455 In June 1991 I was maintaining many of the GNU utilities for the
26456 Free Software Foundation.  As they were ported to more platforms and
26457 more programs were added, the number of @option{-D} options that users
26458 had to select in the makefile (around 20) became burdensome.
26459 Especially for me---I had to test each new release on a bunch of
26460 different systems.  So I wrote a little shell script to guess some of
26461 the correct settings for the fileutils package, and released it as part
26462 of fileutils 2.0.  That @command{configure} script worked well enough that
26463 the next month I adapted it (by hand) to create similar @command{configure}
26464 scripts for several other GNU utilities packages.  Brian Berliner
26465 also adapted one of my scripts for his CVS revision control system.
26467 Later that summer, I learned that Richard Stallman and Richard Pixley
26468 were developing similar scripts to use in the GNU compiler tools;
26469 so I adapted my @command{configure} scripts to support their evolving
26470 interface: using the file name @file{Makefile.in} as the templates;
26471 adding @samp{+srcdir}, the first option (of many); and creating
26472 @file{config.status} files.
26474 @node Exodus
26475 @section Exodus
26477 As I got feedback from users, I incorporated many improvements, using
26478 Emacs to search and replace, cut and paste, similar changes in each of
26479 the scripts.  As I adapted more GNU utilities packages to use
26480 @command{configure} scripts, updating them all by hand became impractical.
26481 Rich Murphey, the maintainer of the GNU graphics utilities, sent me
26482 mail saying that the @command{configure} scripts were great, and asking if
26483 I had a tool for generating them that I could send him.  No, I thought,
26484 but I should!  So I started to work out how to generate them.  And the
26485 journey from the slavery of hand-written @command{configure} scripts to the
26486 abundance and ease of Autoconf began.
26488 Cygnus @command{configure}, which was being developed at around that time,
26489 is table driven; it is meant to deal mainly with a discrete number of
26490 system types with a small number of mainly unguessable features (such as
26491 details of the object file format).  The automatic configuration system
26492 that Brian Fox had developed for Bash takes a similar approach.  For
26493 general use, it seems to me a hopeless cause to try to maintain an
26494 up-to-date database of which features each variant of each operating
26495 system has.  It's easier and more reliable to check for most features on
26496 the fly---especially on hybrid systems that people have hacked on
26497 locally or that have patches from vendors installed.
26499 I considered using an architecture similar to that of Cygnus
26500 @command{configure}, where there is a single @command{configure} script that
26501 reads pieces of @file{configure.in} when run.  But I didn't want to have
26502 to distribute all of the feature tests with every package, so I settled
26503 on having a different @command{configure} made from each
26504 @file{configure.in} by a preprocessor.  That approach also offered more
26505 control and flexibility.
26507 I looked briefly into using the Metaconfig package, by Larry Wall,
26508 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
26509 reasons.  The @command{Configure} scripts it produces are interactive,
26510 which I find quite inconvenient; I didn't like the ways it checked for
26511 some features (such as library functions); I didn't know that it was
26512 still being maintained, and the @command{Configure} scripts I had
26513 seen didn't work on many modern systems (such as System V R4 and NeXT);
26514 it wasn't flexible in what it could do in response to a feature's
26515 presence or absence; I found it confusing to learn; and it was too big
26516 and complex for my needs (I didn't realize then how much Autoconf would
26517 eventually have to grow).
26519 I considered using Perl to generate my style of @command{configure}
26520 scripts, but decided that M4 was better suited to the job of simple
26521 textual substitutions: it gets in the way less, because output is
26522 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
26523 the GNU extensions to M4.)  Also, some of my friends at the
26524 University of Maryland had recently been putting M4 front ends on
26525 several programs, including @code{tvtwm}, and I was interested in trying
26526 out a new language.
26528 @node Leviticus
26529 @section Leviticus
26531 Since my @command{configure} scripts determine the system's capabilities
26532 automatically, with no interactive user intervention, I decided to call
26533 the program that generates them Autoconfig.  But with a version number
26534 tacked on, that name would be too long for old Unix file systems,
26535 so I shortened it to Autoconf.
26537 In the fall of 1991 I called together a group of fellow questers after
26538 the Holy Grail of portability (er, that is, alpha testers) to give me
26539 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
26540 and continued to add features and improve the techniques used in the
26541 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
26542 with the idea of making an Autoconf shell script to run M4
26543 and check for unresolved macro calls; Richard Pixley, who suggested
26544 running the compiler instead of searching the file system to find
26545 include files and symbols, for more accurate results; Karl Berry, who
26546 got Autoconf to configure @TeX{} and added the macro index to the
26547 documentation; and Ian Lance Taylor, who added support for creating a C
26548 header file as an alternative to putting @option{-D} options in a
26549 makefile, so he could use Autoconf for his UUCP package.
26550 The alpha testers cheerfully adjusted their files again and again as the
26551 names and calling conventions of the Autoconf macros changed from
26552 release to release.  They all contributed many specific checks, great
26553 ideas, and bug fixes.
26555 @node Numbers
26556 @section Numbers
26558 In July 1992, after months of alpha testing, I released Autoconf 1.0,
26559 and converted many GNU packages to use it.  I was surprised by how
26560 positive the reaction to it was.  More people started using it than I
26561 could keep track of, including people working on software that wasn't
26562 part of the GNU Project (such as TCL, FSP, and Kerberos V5).
26563 Autoconf continued to improve rapidly, as many people using the
26564 @command{configure} scripts reported problems they encountered.
26566 Autoconf turned out to be a good torture test for M4 implementations.
26567 Unix M4 started to dump core because of the length of the
26568 macros that Autoconf defined, and several bugs showed up in GNU
26569 M4 as well.  Eventually, we realized that we needed to use some
26570 features that only GNU M4 has.  4.3BSD M4, in
26571 particular, has an impoverished set of builtin macros; the System V
26572 version is better, but still doesn't provide everything we need.
26574 More development occurred as people put Autoconf under more stresses
26575 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
26576 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
26577 invalid arguments.  Jim Blandy bravely coerced it into configuring
26578 GNU Emacs, laying the groundwork for several later improvements.
26579 Roland McGrath got it to configure the GNU C Library, wrote the
26580 @command{autoheader} script to automate the creation of C header file
26581 templates, and added a @option{--verbose} option to @command{configure}.
26582 Noah Friedman added the @option{--autoconf-dir} option and
26583 @code{AC_MACRODIR} environment variable.  (He also coined the term
26584 @dfn{autoconfiscate} to mean ``adapt a software package to use
26585 Autoconf''.)  Roland and Noah improved the quoting protection in
26586 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
26587 dealing with portability problems from February through June, 1993.
26589 @node Deuteronomy
26590 @section Deuteronomy
26592 A long wish list for major features had accumulated, and the effect of
26593 several years of patching by various people had left some residual
26594 cruft.  In April 1994, while working for Cygnus Support, I began a major
26595 revision of Autoconf.  I added most of the features of the Cygnus
26596 @command{configure} that Autoconf had lacked, largely by adapting the
26597 relevant parts of Cygnus @command{configure} with the help of david zuhn
26598 and Ken Raeburn.  These features include support for using
26599 @file{config.sub}, @file{config.guess}, @option{--host}, and
26600 @option{--target}; making links to files; and running @command{configure}
26601 scripts in subdirectories.  Adding these features enabled Ken to convert
26602 GNU @code{as}, and Rob Savoye to convert DejaGNU, to using
26603 Autoconf.
26605 I added more features in response to other peoples' requests.  Many
26606 people had asked for @command{configure} scripts to share the results of
26607 the checks between runs, because (particularly when configuring a large
26608 source tree, like Cygnus does) they were frustratingly slow.  Mike
26609 Haertel suggested adding site-specific initialization scripts.  People
26610 distributing software that had to unpack on MS-DOS asked for a way to
26611 override the @file{.in} extension on the file names, which produced file
26612 names like @file{config.h.in} containing two dots.  Jim Avera did an
26613 extensive examination of the problems with quoting in @code{AC_DEFINE}
26614 and @code{AC_SUBST}; his insights led to significant improvements.
26615 Richard Stallman asked that compiler output be sent to @file{config.log}
26616 instead of @file{/dev/null}, to help people debug the Emacs
26617 @command{configure} script.
26619 I made some other changes because of my dissatisfaction with the quality
26620 of the program.  I made the messages showing results of the checks less
26621 ambiguous, always printing a result.  I regularized the names of the
26622 macros and cleaned up coding style inconsistencies.  I added some
26623 auxiliary utilities that I had developed to help convert source code
26624 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
26625 the macros not interrupt each others' messages.  (That feature revealed
26626 some performance bottlenecks in GNU M4, which he hastily
26627 corrected!)  I reorganized the documentation around problems people want
26628 to solve.  And I began a test suite, because experience had shown that
26629 Autoconf has a pronounced tendency to regress when we change it.
26631 Again, several alpha testers gave invaluable feedback, especially
26632 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
26633 and Mark Eichin.
26635 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
26636 have free time again.  I think.  Yeah, right.)
26639 @c ========================================================== Appendices
26642 @node GNU Free Documentation License
26643 @appendix GNU Free Documentation License
26645 @include fdl.texi
26647 @node Indices
26648 @appendix Indices
26650 @menu
26651 * Environment Variable Index::  Index of environment variables used
26652 * Output Variable Index::       Index of variables set in output files
26653 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
26654 * Cache Variable Index::        Index of documented cache variables
26655 * Autoconf Macro Index::        Index of Autoconf macros
26656 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
26657 * Autotest Macro Index::        Index of Autotest macros
26658 * Program & Function Index::    Index of those with portability problems
26659 * Concept Index::               General index
26660 @end menu
26662 @node Environment Variable Index
26663 @appendixsec Environment Variable Index
26665 This is an alphabetical list of the environment variables that might
26666 influence Autoconf checks.
26668 @printindex ev
26670 @node Output Variable Index
26671 @appendixsec Output Variable Index
26673 This is an alphabetical list of the variables that Autoconf can
26674 substitute into files that it creates, typically one or more
26675 makefiles.  @xref{Setting Output Variables}, for more information
26676 on how this is done.
26678 @printindex ov
26680 @node Preprocessor Symbol Index
26681 @appendixsec Preprocessor Symbol Index
26683 This is an alphabetical list of the C preprocessor symbols that the
26684 Autoconf macros define.  To work with Autoconf, C source code needs to
26685 use these names in @code{#if} or @code{#ifdef} directives.
26687 @printindex cv
26689 @node Cache Variable Index
26690 @appendixsec Cache Variable Index
26692 This is an alphabetical list of documented cache variables used
26693 by macros defined in Autoconf.  Autoconf macros may use additional cache
26694 variables internally.
26695 @ifset shortindexflag
26696 To make the list easier to use, the variables are listed without their
26697 preceding @samp{ac_cv_}.
26698 @end ifset
26700 @printindex CA
26702 @node Autoconf Macro Index
26703 @appendixsec Autoconf Macro Index
26705 This is an alphabetical list of the Autoconf macros.
26706 @ifset shortindexflag
26707 To make the list easier to use, the macros are listed without their
26708 preceding @samp{AC_}.
26709 @end ifset
26711 @printindex AC
26713 @node M4 Macro Index
26714 @appendixsec M4 Macro Index
26716 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
26717 @ifset shortindexflag
26718 To make the list easier to use, the macros are listed without their
26719 preceding @samp{m4_} or @samp{AS_}.  The prefix is @samp{m4_} for
26720 all-lowercase macro names and @samp{AS_} for all-uppercase macro
26721 names.
26722 @end ifset
26724 @printindex MS
26726 @node Autotest Macro Index
26727 @appendixsec Autotest Macro Index
26729 This is an alphabetical list of the Autotest macros.
26730 @ifset shortindexflag
26731 To make the list easier to use, the macros are listed without their
26732 preceding @samp{AT_}.
26733 @end ifset
26735 @printindex AT
26737 @node Program & Function Index
26738 @appendixsec Program and Function Index
26740 This is an alphabetical list of the programs and functions whose
26741 portability is discussed in this document.
26743 @printindex pr
26745 @node Concept Index
26746 @appendixsec Concept Index
26748 This is an alphabetical list of the files, tools, and concepts
26749 introduced in this document.
26751 @printindex cp
26753 @bye
26755 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
26756 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
26757 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
26758 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
26759 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
26760 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
26761 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
26762 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
26763 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
26764 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
26765 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
26766 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
26767 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
26768 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
26769 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
26770 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
26771 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
26772 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
26773 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
26774 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
26775 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
26776 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
26777 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
26778 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
26779 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
26780 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
26781 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
26782 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
26783 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
26784 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
26785 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
26786 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
26787 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
26788 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
26789 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
26790 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
26791 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
26792 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
26793 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
26794 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
26795 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
26796 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
26797 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
26798 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
26799 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
26800 @c  LocalWords:  STDBOOL BOOL stdbool cplusplus bool Bool stdarg tm
26801 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
26802 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
26803 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
26804 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
26805 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
26806 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
26807 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
26808 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
26809 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
26810 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
26811 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
26812 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
26813 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
26814 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
26815 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
26816 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
26817 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
26818 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
26819 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
26820 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
26821 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
26822 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
26823 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
26824 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
26825 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
26826 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
26827 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
26828 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
26829 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
26830 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
26831 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
26832 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
26833 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
26834 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
26835 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
26836 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
26837 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
26838 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
26839 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
26840 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
26841 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
26842 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
26843 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
26844 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
26845 @c  LocalWords:  Dynix basename aname cname macroexpands xno xcheck
26846 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
26848 @c Local Variables:
26849 @c fill-column: 72
26850 @c ispell-local-dictionary: "american"
26851 @c indent-tabs-mode: nil
26852 @c whitespace-check-buffer-indent: nil
26853 @c End: