Fix 'make pdf'.
[autoconf.git] / doc / autoconf.texi
blob6109bb2ab0dda5d5814a83605dc1ae696e13d47c
1 \input texinfo @c -*-texinfo-*-
2 @comment ========================================================
3 @comment %**start of header
4 @setfilename autoconf.info
5 @include version.texi
6 @settitle Autoconf
7 @setchapternewpage odd
8 @ifnothtml
9 @setcontentsaftertitlepage
10 @end ifnothtml
11 @finalout
13 @c @ovar(ARG)
14 @c ----------
15 @c The ARG is an optional argument.  To be used for macro arguments in
16 @c their documentation (@defmac).
17 @macro ovar{varname}
18 @r{[}@var{\varname\}@r{]}@c
19 @end macro
21 @c @dvar(ARG, DEFAULT)
22 @c -------------------
23 @c The ARG is an optional argument, defaulting to DEFAULT.  To be used
24 @c for macro arguments in their documentation (@defmac).
25 @macro dvar{varname, default}
26 @r{[}@var{\varname\} = @samp{\default\}@r{]}@c
27 @end macro
29 @c Handling the indexes with Texinfo yields several different problems.
31 @c Because we want to drop out the AC_ part of the macro names in the
32 @c printed manual, but not in the other outputs, we need a layer above
33 @c the usual @acindex{} etc.  That's why we first define indexes such as
34 @c acx meant to become the macro @acindex.  First of all, using ``ac_''
35 @c does not work with makeinfo, and using ``ac1'' doesn't work with TeX.
36 @c So use something more regular ``acx''.  Then you finish with a printed
37 @c index saying ``index is not existent''.  Of course: you ought to use
38 @c two letters :(  So you use capitals.
40 @c Second, when defining a macro in the TeX world, following spaces are
41 @c eaten.  But then, since we embed @acxindex commands that use the end
42 @c of line as an end marker, the whole things wrecks itself.  So make
43 @c sure you do *force* an additional end of line, add a ``@c''.
45 @c Finally, you might want to get rid of TeX expansion, using --expand
46 @c with texi2dvi.  But then you wake up an old problem: we use macros
47 @c in @defmac etc. where TeX does perform the expansion, but not makeinfo.
49 @c Define an environment variable index.
50 @defcodeindex ev
51 @c Define an output variable index.
52 @defcodeindex ov
53 @c Define a CPP variable index.
54 @defcodeindex cv
55 @c Define an Autoconf macro index that @defmac doesn't write to.
56 @defcodeindex AC
57 @c Define an Autotest macro index that @defmac doesn't write to.
58 @defcodeindex AT
59 @c Define an M4sugar macro index that @defmac doesn't write to.
60 @defcodeindex MS
61 @c Define an index for *foreign* programs: `mv' etc.  Used for the
62 @c portability sections and so on.
63 @defindex pr
65 @c shortindexflag
66 @c --------------
67 @c Shall we factor AC_ out of the Autoconf macro index etc.?
68 @iftex
69 @set shortindexflag
70 @end iftex
72 @c @acindex{MACRO}
73 @c ---------------
74 @c Registering an AC_\MACRO\.
75 @ifset shortindexflag
76 @macro acindex{macro}
77 @ACindex \macro\
79 @end macro
80 @end ifset
81 @ifclear shortindexflag
82 @macro acindex{macro}
83 @ACindex AC_\macro\
84 @end macro
85 @end ifclear
87 @c @ahindex{MACRO}
88 @c ---------------
89 @c Registering an AH_\MACRO\.
90 @macro ahindex{macro}
91 @ACindex AH_\macro\
93 @end macro
95 @c @asindex{MACRO}
96 @c ---------------
97 @c Registering an AS_\MACRO\.
98 @ifset shortindexflag
99 @macro asindex{macro}
100 @MSindex \macro\
102 @end macro
103 @end ifset
104 @ifclear shortindexflag
105 @macro asindex{macro}
106 @MSindex AS_\macro\
107 @end macro
108 @end ifclear
110 @c @atindex{MACRO}
111 @c ---------------
112 @c Registering an AT_\MACRO\.
113 @ifset shortindexflag
114 @macro atindex{macro}
115 @ATindex \macro\
117 @end macro
118 @end ifset
119 @ifclear shortindexflag
120 @macro atindex{macro}
121 @ATindex AT_\macro\
122 @end macro
123 @end ifclear
125 @c @auindex{MACRO}
126 @c ---------------
127 @c Registering an AU_\MACRO\.
128 @macro auindex{macro}
129 @ACindex AU_\macro\
131 @end macro
133 @c @hdrindex{MACRO}
134 @c ----------------
135 @c Indexing a header.
136 @macro hdrindex{macro}
137 @prindex @file{\macro\}
139 @end macro
141 @c @msindex{MACRO}
142 @c ---------------
143 @c Registering an m4_\MACRO\.
144 @ifset shortindexflag
145 @macro msindex{macro}
146 @MSindex \macro\
148 @end macro
149 @end ifset
150 @ifclear shortindexflag
151 @macro msindex{macro}
152 @MSindex m4_\macro\
153 @end macro
154 @end ifclear
157 @c Define an index for functions: `alloca' etc.  Used for the
158 @c portability sections and so on.  We can't use `fn' (aka `fnindex),
159 @c since `@defmac' goes into it => we'd get all the macros too.
161 @c   FIXME: Aaarg!  It seems there are too many indices for TeX :(
163 @c   ! No room for a new @write .
164 @c   l.112 @defcodeindex fu
166 @c   so don't define yet another one :(  Just put some tags before each
167 @c   @prindex which is actually a @funindex.
169 @c   @defcodeindex fu
172 @c   @c Put the programs and functions into their own index.
173 @c   @syncodeindex fu pr
175 @comment %**end of header
176 @comment ========================================================
178 @copying
180 This manual (@value{UPDATED}) is for @acronym{GNU} Autoconf
181 (version @value{VERSION}),
182 a package for creating scripts to configure source code packages using
183 templates and an M4 macro package.
185 Copyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000,
186 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software
187 Foundation, Inc.
189 @quotation
190 Permission is granted to copy, distribute and/or modify this document
191 under the terms of the @acronym{GNU} Free Documentation License,
192 Version 1.2 or any later version published by the Free Software
193 Foundation; with no Invariant Sections, with the Front-Cover texts
194 being ``A @acronym{GNU} Manual,'' and with the Back-Cover Texts as in
195 (a) below.  A copy of the license is included in the section entitled
196 ``@acronym{GNU} Free Documentation License.''
198 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
199 modify this @acronym{GNU} manual.  Buying copies from the @acronym{FSF}
200 supports it in developing @acronym{GNU} and promoting software
201 freedom.''
202 @end quotation
203 @end copying
207 @dircategory Software development
208 @direntry
209 * Autoconf: (autoconf).         Create source code configuration scripts.
210 @end direntry
212 @dircategory Individual utilities
213 @direntry
214 * autoscan: (autoconf)autoscan Invocation.
215                                 Semi-automatic @file{configure.ac} writing
216 * ifnames: (autoconf)ifnames Invocation.        Listing conditionals in source.
217 * autoconf-invocation: (autoconf)autoconf Invocation.
218                                 How to create configuration scripts
219 * autoreconf: (autoconf)autoreconf Invocation.
220                                 Remaking multiple @command{configure} scripts
221 * autoheader: (autoconf)autoheader Invocation.
222                                 How to create configuration templates
223 * autom4te: (autoconf)autom4te Invocation.
224                                 The Autoconf executables backbone
225 * configure: (autoconf)configure Invocation.    Configuring a package.
226 * autoupdate: (autoconf)autoupdate Invocation.
227                                 Automatic update of @file{configure.ac}
228 * config.status: (autoconf)config.status Invocation. Recreating configurations.
229 * testsuite: (autoconf)testsuite Invocation.    Running an Autotest test suite.
230 @end direntry
232 @titlepage
233 @title Autoconf
234 @subtitle Creating Automatic Configuration Scripts
235 @subtitle for version @value{VERSION}, @value{UPDATED}
236 @author David MacKenzie
237 @author Ben Elliston
238 @author Akim Demaille
239 @page
240 @vskip 0pt plus 1filll
241 @insertcopying
242 @end titlepage
244 @contents
247 @ifnottex
248 @node Top
249 @top Autoconf
250 @insertcopying
251 @end ifnottex
253 @c The master menu, created with texinfo-master-menu, goes here.
255 @menu
256 * Introduction::                Autoconf's purpose, strengths, and weaknesses
257 * The GNU Build System::        A set of tools for portable software packages
258 * Making configure Scripts::    How to organize and produce Autoconf scripts
259 * Setup::                       Initialization and output
260 * Existing Tests::              Macros that check for particular features
261 * Writing Tests::               How to write new feature checks
262 * Results::                     What to do with results from feature checks
263 * Programming in M4::           Layers on top of which Autoconf is written
264 * Programming in M4sh::         Shell portability layer
265 * Writing Autoconf Macros::     Adding new macros to Autoconf
266 * Portable Shell::              Shell script portability pitfalls
267 * Portable Make::               Makefile portability pitfalls
268 * Portable C and C++::          C and C++ portability pitfalls
269 * Manual Configuration::        Selecting features that can't be guessed
270 * Site Configuration::          Local defaults for @command{configure}
271 * Running configure Scripts::   How to use the Autoconf output
272 * config.status Invocation::    Recreating a configuration
273 * Obsolete Constructs::         Kept for backward compatibility
274 * Using Autotest::              Creating portable test suites
275 * FAQ::                         Frequent Autoconf Questions, with answers
276 * History::                     History of Autoconf
277 * GNU Free Documentation License::  License for copying this manual
278 * Indices::                     Indices of symbols, concepts, etc.
280 @detailmenu
281  --- The Detailed Node Listing ---
283 The @acronym{GNU} Build System
285 * Automake::                    Escaping makefile hell
286 * Gnulib::                      The @acronym{GNU} portability library
287 * Libtool::                     Building libraries portably
288 * Pointers::                    More info on the @acronym{GNU} build system
290 Making @command{configure} Scripts
292 * Writing Autoconf Input::      What to put in an Autoconf input file
293 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
294 * ifnames Invocation::          Listing the conditionals in source code
295 * autoconf Invocation::         How to create configuration scripts
296 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
298 Writing @file{configure.ac}
300 * Shell Script Compiler::       Autoconf as solution of a problem
301 * Autoconf Language::           Programming in Autoconf
302 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
304 Initialization and Output Files
306 * Initializing configure::      Option processing etc.
307 * Versioning::                  Dealing with Autoconf versions
308 * Notices::                     Copyright, version numbers in @command{configure}
309 * Input::                       Where Autoconf should find files
310 * Output::                      Outputting results from the configuration
311 * Configuration Actions::       Preparing the output based on results
312 * Configuration Files::         Creating output files
313 * Makefile Substitutions::      Using output variables in makefiles
314 * Configuration Headers::       Creating a configuration header file
315 * Configuration Commands::      Running arbitrary instantiation commands
316 * Configuration Links::         Links depending on the configuration
317 * Subdirectories::              Configuring independent packages together
318 * Default Prefix::              Changing the default installation prefix
320 Substitutions in Makefiles
322 * Preset Output Variables::     Output variables that are always set
323 * Installation Directory Variables::  Other preset output variables
324 * Changed Directory Variables:: Warnings about @file{datarootdir}
325 * Build Directories::           Supporting multiple concurrent compiles
326 * Automatic Remaking::          Makefile rules for configuring
328 Configuration Header Files
330 * Header Templates::            Input for the configuration headers
331 * autoheader Invocation::       How to create configuration templates
332 * Autoheader Macros::           How to specify CPP templates
334 Existing Tests
336 * Common Behavior::             Macros' standard schemes
337 * Alternative Programs::        Selecting between alternative programs
338 * Files::                       Checking for the existence of files
339 * Libraries::                   Library archives that might be missing
340 * Library Functions::           C library functions that might be missing
341 * Header Files::                Header files that might be missing
342 * Declarations::                Declarations that may be missing
343 * Structures::                  Structures or members that might be missing
344 * Types::                       Types that might be missing
345 * Compilers and Preprocessors::  Checking for compiling programs
346 * System Services::             Operating system services
347 * Posix Variants::              Special kludges for specific Posix variants
348 * Erlang Libraries::            Checking for the existence of Erlang libraries
350 Common Behavior
352 * Standard Symbols::            Symbols defined by the macros
353 * Default Includes::            Includes used by the generic macros
355 Alternative Programs
357 * Particular Programs::         Special handling to find certain programs
358 * Generic Programs::            How to find other programs
360 Library Functions
362 * Function Portability::        Pitfalls with usual functions
363 * Particular Functions::        Special handling to find certain functions
364 * Generic Functions::           How to find other functions
366 Header Files
368 * Header Portability::          Collected knowledge on common headers
369 * Particular Headers::          Special handling to find certain headers
370 * Generic Headers::             How to find other headers
372 Declarations
374 * Particular Declarations::     Macros to check for certain declarations
375 * Generic Declarations::        How to find other declarations
377 Structures
379 * Particular Structures::       Macros to check for certain structure members
380 * Generic Structures::          How to find other structure members
382 Types
384 * Particular Types::            Special handling to find certain types
385 * Generic Types::               How to find other types
387 Compilers and Preprocessors
389 * Specific Compiler Characteristics::  Some portability issues
390 * Generic Compiler Characteristics::  Language independent tests and features
391 * C Compiler::                  Checking its characteristics
392 * C++ Compiler::                Likewise
393 * Objective C Compiler::        Likewise
394 * Erlang Compiler and Interpreter::  Likewise
395 * Fortran Compiler::            Likewise
397 Writing Tests
399 * Language Choice::             Selecting which language to use for testing
400 * Writing Test Programs::       Forging source files for compilers
401 * Running the Preprocessor::    Detecting preprocessor symbols
402 * Running the Compiler::        Detecting language or header features
403 * Running the Linker::          Detecting library features
404 * Runtime::                     Testing for runtime features
405 * Systemology::                 A zoology of operating systems
406 * Multiple Cases::              Tests for several possible values
408 Writing Test Programs
410 * Guidelines::                  General rules for writing test programs
411 * Test Functions::              Avoiding pitfalls in test programs
412 * Generating Sources::          Source program boilerplate
414 Results of Tests
416 * Defining Symbols::            Defining C preprocessor symbols
417 * Setting Output Variables::    Replacing variables in output files
418 * Special Chars in Variables::  Characters to beware of in variables
419 * Caching Results::             Speeding up subsequent @command{configure} runs
420 * Printing Messages::           Notifying @command{configure} users
422 Caching Results
424 * Cache Variable Names::        Shell variables used in caches
425 * Cache Files::                 Files @command{configure} uses for caching
426 * Cache Checkpointing::         Loading and saving the cache file
428 Programming in M4
430 * M4 Quotation::                Protecting macros from unwanted expansion
431 * Using autom4te::              The Autoconf executables backbone
432 * Programming in M4sugar::      Convenient pure M4 macros
434 Programming in M4sh
436 * Common Shell Constructs::     Portability layer for common shell constructs
437 * Polymorphic Variables::       Support for indirect variable names
438 * Initialization Macros::       Macros to establish a sane shell environment
439 * File Descriptor Macros::      File descriptor macros for input and output
441 M4 Quotation
443 * Active Characters::           Characters that change the behavior of M4
444 * One Macro Call::              Quotation and one macro call
445 * Quoting and Parameters::      M4 vs. shell parameters
446 * Quotation and Nested Macros::  Macros calling macros
447 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
448 * Quadrigraphs::                Another way to escape special characters
449 * Balancing Parentheses::       Dealing with unbalanced parentheses
450 * Quotation Rule Of Thumb::     One parenthesis, one quote
452 Using @command{autom4te}
454 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
455 * Customizing autom4te::        Customizing the Autoconf package
457 Programming in M4sugar
459 * Redefined M4 Macros::         M4 builtins changed in M4sugar
460 * Diagnostic Macros::           Diagnostic messages from M4sugar
461 * Diversion support::           Diversions in M4sugar
462 * Conditional constructs::      Conditions in M4
463 * Looping constructs::          Iteration in M4
464 * Evaluation Macros::           More quotation and evaluation control
465 * Text processing Macros::      String manipulation in M4
466 * Number processing Macros::    Arithmetic computation in M4
467 * Set manipulation Macros::     Set manipulation in M4
468 * Forbidden Patterns::          Catching unexpanded macros
470 Writing Autoconf Macros
472 * Macro Definitions::           Basic format of an Autoconf macro
473 * Macro Names::                 What to call your new macros
474 * Reporting Messages::          Notifying @command{autoconf} users
475 * Dependencies Between Macros::  What to do when macros depend on other macros
476 * Obsoleting Macros::           Warning about old ways of doing things
477 * Coding Style::                Writing Autoconf macros @`a la Autoconf
479 Dependencies Between Macros
481 * Prerequisite Macros::         Ensuring required information
482 * Suggested Ordering::          Warning about possible ordering problems
483 * One-Shot Macros::             Ensuring a macro is called only once
485 Portable Shell Programming
487 * Shellology::                  A zoology of shells
488 * Here-Documents::              Quirks and tricks
489 * File Descriptors::            FDs and redirections
490 * File System Conventions::     File names
491 * Shell Pattern Matching::      Pattern matching
492 * Shell Substitutions::         Variable and command expansions
493 * Assignments::                 Varying side effects of assignments
494 * Parentheses::                 Parentheses in shell scripts
495 * Slashes::                     Slashes in shell scripts
496 * Special Shell Variables::     Variables you should not change
497 * Shell Functions::             What to look out for if you use them
498 * Limitations of Builtins::     Portable use of not so portable /bin/sh
499 * Limitations of Usual Tools::  Portable use of portable tools
501 Portable Make Programming
503 * $< in Ordinary Make Rules::   $< in ordinary rules
504 * Failure in Make Rules::       Failing portably in rules
505 * Special Chars in Names::      Special Characters in Macro Names
506 * Backslash-Newline-Newline::   Empty last lines in macro definitions
507 * Backslash-Newline Comments::  Spanning comments across line boundaries
508 * Long Lines in Makefiles::     Line length limitations
509 * Macros and Submakes::         @code{make macro=value} and submakes
510 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
511 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
512 * Comments in Make Rules::      Other problems with Make comments
513 * obj/ and Make::               Don't name a subdirectory @file{obj}
514 * make -k Status::              Exit status of @samp{make -k}
515 * VPATH and Make::              @code{VPATH} woes
516 * Single Suffix Rules::         Single suffix rules and separated dependencies
517 * Timestamps and Make::         Subsecond timestamp resolution
519 @code{VPATH} and Make
521 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
522 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
523 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
524 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
525 * Make Target Lookup::          More details about @code{VPATH} lookup
527 Portable C and C++ Programming
529 * Varieties of Unportability::  How to make your programs unportable
530 * Integer Overflow::            When integers get too large
531 * Preprocessor Arithmetic::     @code{#if} expression problems
532 * Null Pointers::               Properties of null pointers
533 * Buffer Overruns::             Subscript errors and the like
534 * Volatile Objects::            @code{volatile} and signals
535 * Floating Point Portability::  Portable floating-point arithmetic
536 * Exiting Portably::            Exiting and the exit status
538 Manual Configuration
540 * Specifying Names::            Specifying the system type
541 * Canonicalizing::              Getting the canonical system type
542 * Using System Type::           What to do with the system type
544 Site Configuration
546 * Help Formatting::             Customizing @samp{configure --help}
547 * External Software::           Working with other optional software
548 * Package Options::             Selecting optional features
549 * Pretty Help Strings::         Formatting help string
550 * Option Checking::             Controlling checking of @command{configure} options
551 * Site Details::                Configuring site details
552 * Transforming Names::          Changing program names when installing
553 * Site Defaults::               Giving @command{configure} local defaults
555 Transforming Program Names When Installing
557 * Transformation Options::      @command{configure} options to transform names
558 * Transformation Examples::     Sample uses of transforming names
559 * Transformation Rules::        Makefile uses of transforming names
561 Running @command{configure} Scripts
563 * Basic Installation::          Instructions for typical cases
564 * Compilers and Options::       Selecting compilers and optimization
565 * Multiple Architectures::      Compiling for multiple architectures at once
566 * Installation Names::          Installing in different directories
567 * Optional Features::           Selecting optional features
568 * Particular Systems::          Particular systems
569 * System Type::                 Specifying the system type
570 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
571 * Defining Variables::          Specifying the compiler etc.
572 * configure Invocation::        Changing how @command{configure} runs
574 Obsolete Constructs
576 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
577 * acconfig Header::             Additional entries in @file{config.h.in}
578 * autoupdate Invocation::       Automatic update of @file{configure.ac}
579 * Obsolete Macros::             Backward compatibility macros
580 * Autoconf 1::                  Tips for upgrading your files
581 * Autoconf 2.13::               Some fresher tips
583 Upgrading From Version 1
585 * Changed File Names::          Files you might rename
586 * Changed Makefiles::           New things to put in @file{Makefile.in}
587 * Changed Macros::              Macro calls you might replace
588 * Changed Results::             Changes in how to check test results
589 * Changed Macro Writing::       Better ways to write your own macros
591 Upgrading From Version 2.13
593 * Changed Quotation::           Broken code which used to work
594 * New Macros::                  Interaction with foreign macros
595 * Hosts and Cross-Compilation::  Bugward compatibility kludges
596 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
597 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
599 Generating Test Suites with Autotest
601 * Using an Autotest Test Suite::  Autotest and the user
602 * Writing Testsuites::          Autotest macros
603 * testsuite Invocation::        Running @command{testsuite} scripts
604 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
606 Using an Autotest Test Suite
608 * testsuite Scripts::           The concepts of Autotest
609 * Autotest Logs::               Their contents
611 Frequent Autoconf Questions, with answers
613 * Distributing::                Distributing @command{configure} scripts
614 * Why GNU M4::                  Why not use the standard M4?
615 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
616 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
617 * Defining Directories::        Passing @code{datadir} to program
618 * Autom4te Cache::              What is it?  Can I remove it?
619 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
620 * Expanded Before Required::    Expanded Before Required
622 History of Autoconf
624 * Genesis::                     Prehistory and naming of @command{configure}
625 * Exodus::                      The plagues of M4 and Perl
626 * Leviticus::                   The priestly code of portability arrives
627 * Numbers::                     Growth and contributors
628 * Deuteronomy::                 Approaching the promises of easy configuration
630 Indices
632 * Environment Variable Index::  Index of environment variables used
633 * Output Variable Index::       Index of variables set in output files
634 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
635 * Autoconf Macro Index::        Index of Autoconf macros
636 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
637 * Autotest Macro Index::        Index of Autotest macros
638 * Program & Function Index::    Index of those with portability problems
639 * Concept Index::               General index
641 @end detailmenu
642 @end menu
644 @c ============================================================= Introduction.
646 @node Introduction
647 @chapter Introduction
648 @cindex Introduction
650 @flushright
651 A physicist, an engineer, and a computer scientist were discussing the
652 nature of God.  ``Surely a Physicist,'' said the physicist, ``because
653 early in the Creation, God made Light; and you know, Maxwell's
654 equations, the dual nature of electromagnetic waves, the relativistic
655 consequences@enddots{}'' ``An Engineer!,'' said the engineer, ``because
656 before making Light, God split the Chaos into Land and Water; it takes a
657 hell of an engineer to handle that big amount of mud, and orderly
658 separation of solids from liquids@enddots{}'' The computer scientist
659 shouted: ``And the Chaos, where do you think it was coming from, hmm?''
661 ---Anonymous
662 @end flushright
663 @c (via Franc,ois Pinard)
665 Autoconf is a tool for producing shell scripts that automatically
666 configure software source code packages to adapt to many kinds of
667 Posix-like systems.  The configuration scripts produced by Autoconf
668 are independent of Autoconf when they are run, so their users do not
669 need to have Autoconf.
671 The configuration scripts produced by Autoconf require no manual user
672 intervention when run; they do not normally even need an argument
673 specifying the system type.  Instead, they individually test for the
674 presence of each feature that the software package they are for might need.
675 (Before each check, they print a one-line message stating what they are
676 checking for, so the user doesn't get too bored while waiting for the
677 script to finish.)  As a result, they deal well with systems that are
678 hybrids or customized from the more common Posix variants.  There is
679 no need to maintain files that list the features supported by each
680 release of each variant of Posix.
682 For each software package that Autoconf is used with, it creates a
683 configuration script from a template file that lists the system features
684 that the package needs or can use.  After the shell code to recognize
685 and respond to a system feature has been written, Autoconf allows it to
686 be shared by many software packages that can use (or need) that feature.
687 If it later turns out that the shell code needs adjustment for some
688 reason, it needs to be changed in only one place; all of the
689 configuration scripts can be regenerated automatically to take advantage
690 of the updated code.
692 @c "Those who do not understand Unix are condemned to reinvent it, poorly."
693 @c --Henry Spencer, 1987 (see http://en.wikipedia.org/wiki/Unix_philosophy)
694 Those who do not understand Autoconf are condemned to reinvent it, poorly.
695 The primary goal of Autoconf is making the @emph{user's} life easier;
696 making the @emph{maintainer's} life easier is only a secondary goal.
697 Put another way, the primary goal is not to make the generation of
698 @file{configure} automatic for package maintainers (although patches
699 along that front are welcome, since package maintainers form the user
700 base of Autoconf); rather, the goal is to make @file{configure}
701 painless, portable, and predictable for the end user of each
702 @dfn{autoconfiscated} package.  And to this degree, Autoconf is highly
703 successful at its goal --- most complaints to the Autoconf list are
704 about difficulties in writing Autoconf input, and not in the behavior of
705 the resulting @file{configure}.  Even packages that don't use Autoconf
706 will generally provide a @file{configure} script, and the most common
707 complaint about these alternative home-grown scripts is that they fail
708 to meet one or more of the @acronym{GNU} Coding Standards that users
709 have come to expect from Autoconf-generated @file{configure} scripts.
711 The Metaconfig package is similar in purpose to Autoconf, but the
712 scripts it produces require manual user intervention, which is quite
713 inconvenient when configuring large source trees.  Unlike Metaconfig
714 scripts, Autoconf scripts can support cross-compiling, if some care is
715 taken in writing them.
717 Autoconf does not solve all problems related to making portable
718 software packages---for a more complete solution, it should be used in
719 concert with other @acronym{GNU} build tools like Automake and
720 Libtool.  These other tools take on jobs like the creation of a
721 portable, recursive makefile with all of the standard targets,
722 linking of shared libraries, and so on.  @xref{The GNU Build System},
723 for more information.
725 Autoconf imposes some restrictions on the names of macros used with
726 @code{#if} in C programs (@pxref{Preprocessor Symbol Index}).
728 Autoconf requires @acronym{GNU} M4 version 1.4.5 or later in order to
729 generate the scripts.  It uses features that some versions of M4,
730 including @acronym{GNU} M4 1.3, do not have.  Autoconf works better
731 with @acronym{GNU} M4 version 1.4.11 or later, though this is not
732 required.
734 @xref{Autoconf 1}, for information about upgrading from version 1.
735 @xref{History}, for the story of Autoconf's development.  @xref{FAQ},
736 for answers to some common questions about Autoconf.
738 See the @uref{http://@/www.gnu.org/@/software/@/autoconf/,
739 Autoconf web page} for up-to-date information, details on the mailing
740 lists, pointers to a list of known bugs, etc.
742 Mail suggestions to @email{autoconf@@gnu.org, the Autoconf mailing
743 list}.  Past suggestions are
744 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf/, archived}.
746 Mail bug reports to @email{bug-autoconf@@gnu.org, the
747 Autoconf Bugs mailing list}.  Past bug reports are
748 @uref{http://@/lists.gnu.org/@/archive/@/html/@/bug-autoconf/, archived}.
750 If possible, first check that your bug is
751 not already solved in current development versions, and that it has not
752 been reported yet.  Be sure to include all the needed information and a
753 short @file{configure.ac} that demonstrates the problem.
755 Autoconf's development tree is accessible via @command{git}; see the
756 @uref{http://@/savannah.gnu.org/@/projects/@/autoconf/, Autoconf
757 Summary} for details, or view
758 @uref{http://@/git.sv.gnu.org/@/gitweb/@/?p=autoconf.git, the actual
759 repository}.  Anonymous @acronym{CVS} access is also available, see
760 @file{README} for more details.  Patches relative to the
761 current @command{git} version can be sent for review to the
762 @email{autoconf-patches@@gnu.org, Autoconf Patches mailing list}, with
763 discussion on prior patches
764 @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-@/patches/,
765 archived}; and all commits are posted in the read-only
766 @email{autoconf-commit@@gnu.org, Autoconf Commit mailing list}, which is
767 also @uref{http://@/lists.gnu.org/@/archive/@/html/@/autoconf-commit/,
768 archived}.
770 Because of its mission, the Autoconf package itself
771 includes only a set of often-used
772 macros that have already demonstrated their usefulness.  Nevertheless,
773 if you wish to share your macros, or find existing ones, see the
774 @uref{http://@/autoconf-archive.cryp.to/, Autoconf Macro
775 Archive}, which is kindly run by @email{simons@@cryp.to,
776 Peter Simons}.
779 @c ================================================= The GNU Build System
781 @node The GNU Build System
782 @chapter The @acronym{GNU} Build System
783 @cindex @acronym{GNU} build system
785 Autoconf solves an important problem---reliable discovery of
786 system-specific build and runtime information---but this is only one
787 piece of the puzzle for the development of portable software.  To this
788 end, the @acronym{GNU} project has developed a suite of integrated
789 utilities to finish the job Autoconf started: the @acronym{GNU} build
790 system, whose most important components are Autoconf, Automake, and
791 Libtool.  In this chapter, we introduce you to those tools, point you
792 to sources of more information, and try to convince you to use the
793 entire @acronym{GNU} build system for your software.
795 @menu
796 * Automake::                    Escaping makefile hell
797 * Gnulib::                      The @acronym{GNU} portability library
798 * Libtool::                     Building libraries portably
799 * Pointers::                    More info on the @acronym{GNU} build system
800 @end menu
802 @node Automake
803 @section Automake
805 The ubiquity of @command{make} means that a makefile is almost the
806 only viable way to distribute automatic build rules for software, but
807 one quickly runs into its numerous limitations.  Its lack of
808 support for automatic dependency tracking, recursive builds in
809 subdirectories, reliable timestamps (e.g., for network file systems), and
810 so on, mean that developers must painfully (and often incorrectly)
811 reinvent the wheel for each project.  Portability is non-trivial, thanks
812 to the quirks of @command{make} on many systems.  On top of all this is the
813 manual labor required to implement the many standard targets that users
814 have come to expect (@code{make install}, @code{make distclean},
815 @code{make uninstall}, etc.).  Since you are, of course, using Autoconf,
816 you also have to insert repetitive code in your @file{Makefile.in} to
817 recognize @code{@@CC@@}, @code{@@CFLAGS@@}, and other substitutions
818 provided by @command{configure}.  Into this mess steps @dfn{Automake}.
819 @cindex Automake
821 Automake allows you to specify your build needs in a @file{Makefile.am}
822 file with a vastly simpler and more powerful syntax than that of a plain
823 makefile, and then generates a portable @file{Makefile.in} for
824 use with Autoconf.  For example, the @file{Makefile.am} to build and
825 install a simple ``Hello world'' program might look like:
827 @example
828 bin_PROGRAMS = hello
829 hello_SOURCES = hello.c
830 @end example
832 @noindent
833 The resulting @file{Makefile.in} (~400 lines) automatically supports all
834 the standard targets, the substitutions provided by Autoconf, automatic
835 dependency tracking, @code{VPATH} building, and so on.  @command{make}
836 builds the @code{hello} program, and @code{make install} installs it
837 in @file{/usr/local/bin} (or whatever prefix was given to
838 @command{configure}, if not @file{/usr/local}).
840 The benefits of Automake increase for larger packages (especially ones
841 with subdirectories), but even for small programs the added convenience
842 and portability can be substantial.  And that's not all@enddots{}
844 @node Gnulib
845 @section Gnulib
847 @acronym{GNU} software has a well-deserved reputation for running on
848 many different types of systems.  While our primary goal is to write
849 software for the @acronym{GNU} system, many users and developers have
850 been introduced to us through the systems that they were already using.
852 @cindex Gnulib
853 Gnulib is a central location for common @acronym{GNU} code, intended to
854 be shared among free software packages.  Its components are typically
855 shared at the source level, rather than being a library that gets built,
856 installed, and linked against.  The idea is to copy files from Gnulib
857 into your own source tree.  There is no distribution tarball; developers
858 should just grab source modules from the repository.  The source files
859 are available online, under various licenses, mostly @acronym{GNU}
860 @acronym{GPL} or @acronym{GNU} @acronym{LGPL}.
862 Gnulib modules typically contain C source code along with Autoconf
863 macros used to configure the source code.  For example, the Gnulib
864 @code{stdbool} module implements a @file{stdbool.h} header that nearly
865 conforms to C99, even on old-fashioned hosts that lack @file{stdbool.h}.
866 This module contains a source file for the replacement header, along
867 with an Autoconf macro that arranges to use the replacement header on
868 old-fashioned systems.
870 @node Libtool
871 @section Libtool
873 Often, one wants to build not only programs, but libraries, so that
874 other programs can benefit from the fruits of your labor.  Ideally, one
875 would like to produce @emph{shared} (dynamically linked) libraries,
876 which can be used by multiple programs without duplication on disk or in
877 memory and can be updated independently of the linked programs.
878 Producing shared libraries portably, however, is the stuff of
879 nightmares---each system has its own incompatible tools, compiler flags,
880 and magic incantations.  Fortunately, @acronym{GNU} provides a solution:
881 @dfn{Libtool}.
882 @cindex Libtool
884 Libtool handles all the requirements of building shared libraries for
885 you, and at this time seems to be the @emph{only} way to do so with any
886 portability.  It also handles many other headaches, such as: the
887 interaction of Make rules with the variable suffixes of
888 shared libraries, linking reliably with shared libraries before they are
889 installed by the superuser, and supplying a consistent versioning system
890 (so that different versions of a library can be installed or upgraded
891 without breaking binary compatibility).  Although Libtool, like
892 Autoconf, can be used without Automake, it is most simply utilized in
893 conjunction with Automake---there, Libtool is used automatically
894 whenever shared libraries are needed, and you need not know its syntax.
896 @node Pointers
897 @section Pointers
899 Developers who are used to the simplicity of @command{make} for small
900 projects on a single system might be daunted at the prospect of
901 learning to use Automake and Autoconf.  As your software is
902 distributed to more and more users, however, you otherwise
903 quickly find yourself putting lots of effort into reinventing the
904 services that the @acronym{GNU} build tools provide, and making the
905 same mistakes that they once made and overcame.  (Besides, since
906 you're already learning Autoconf, Automake is a piece of cake.)
908 There are a number of places that you can go to for more information on
909 the @acronym{GNU} build tools.
911 @itemize @minus
913 @item Web
915 The project home pages for
916 @uref{http://@/www@/.gnu@/.org/@/software/@/autoconf/, Autoconf},
917 @uref{http://@/www@/.gnu@/.org/@/software/@/automake/, Automake},
918 @uref{http://@/www@/.gnu@/.org/@/software/@/gnulib/, Gnulib}, and
919 @uref{http://@/www@/.gnu@/.org/@/software/@/libtool/, Libtool}.
921 @item Automake Manual
923 @xref{Top, , Automake, automake, @acronym{GNU} Automake}, for more
924 information on Automake.
926 @item Books
928 The book @cite{@acronym{GNU} Autoconf, Automake and
929 Libtool}@footnote{@cite{@acronym{GNU} Autoconf, Automake and Libtool},
930 by G. V. Vaughan, B. Elliston, T. Tromey, and I. L. Taylor.  SAMS (originally
931 New Riders), 2000, ISBN 1578701902.} describes the complete @acronym{GNU}
932 build environment.  You can also find
933 @uref{http://@/sources.redhat.com/@/autobook/, the entire book on-line}.
935 @end itemize
937 @c ================================================= Making configure Scripts.
939 @node Making configure Scripts
940 @chapter Making @command{configure} Scripts
941 @cindex @file{aclocal.m4}
942 @cindex @command{configure}
944 The configuration scripts that Autoconf produces are by convention
945 called @command{configure}.  When run, @command{configure} creates several
946 files, replacing configuration parameters in them with appropriate
947 values.  The files that @command{configure} creates are:
949 @itemize @minus
950 @item
951 one or more @file{Makefile} files, usually one in each subdirectory of the
952 package (@pxref{Makefile Substitutions});
954 @item
955 optionally, a C header file, the name of which is configurable,
956 containing @code{#define} directives (@pxref{Configuration Headers});
958 @item
959 a shell script called @file{config.status} that, when run, recreates
960 the files listed above (@pxref{config.status Invocation});
962 @item
963 an optional shell script normally called @file{config.cache}
964 (created when using @samp{configure --config-cache}) that
965 saves the results of running many of the tests (@pxref{Cache Files});
967 @item
968 a file called @file{config.log} containing any messages produced by
969 compilers, to help debugging if @command{configure} makes a mistake.
970 @end itemize
972 @cindex @file{configure.in}
973 @cindex @file{configure.ac}
974 To create a @command{configure} script with Autoconf, you need to write an
975 Autoconf input file @file{configure.ac} (or @file{configure.in}) and run
976 @command{autoconf} on it.  If you write your own feature tests to
977 supplement those that come with Autoconf, you might also write files
978 called @file{aclocal.m4} and @file{acsite.m4}.  If you use a C header
979 file to contain @code{#define} directives, you might also run
980 @command{autoheader}, and you can distribute the generated file
981 @file{config.h.in} with the package.
983 Here is a diagram showing how the files that can be used in
984 configuration are produced.  Programs that are executed are suffixed by
985 @samp{*}.  Optional files are enclosed in square brackets (@samp{[]}).
986 @command{autoconf} and @command{autoheader} also read the installed Autoconf
987 macro files (by reading @file{autoconf.m4}).
989 @noindent
990 Files used in preparing a software package for distribution:
991 @example
992 your source files --> [autoscan*] --> [configure.scan] --> configure.ac
994 @group
995 configure.ac --.
996                |   .------> autoconf* -----> configure
997 [aclocal.m4] --+---+
998                |   `-----> [autoheader*] --> [config.h.in]
999 [acsite.m4] ---'
1000 @end group
1002 Makefile.in -------------------------------> Makefile.in
1003 @end example
1005 @noindent
1006 Files used in configuring a software package:
1007 @example
1008 @group
1009                        .-------------> [config.cache]
1010 configure* ------------+-------------> config.log
1011                        |
1012 [config.h.in] -.       v            .-> [config.h] -.
1013                +--> config.status* -+               +--> make*
1014 Makefile.in ---'                    `-> Makefile ---'
1015 @end group
1016 @end example
1018 @menu
1019 * Writing Autoconf Input::      What to put in an Autoconf input file
1020 * autoscan Invocation::         Semi-automatic @file{configure.ac} writing
1021 * ifnames Invocation::          Listing the conditionals in source code
1022 * autoconf Invocation::         How to create configuration scripts
1023 * autoreconf Invocation::       Remaking multiple @command{configure} scripts
1024 @end menu
1026 @node Writing Autoconf Input
1027 @section Writing @file{configure.ac}
1029 To produce a @command{configure} script for a software package, create a
1030 file called @file{configure.ac} that contains invocations of the
1031 Autoconf macros that test the system features your package needs or can
1032 use.  Autoconf macros already exist to check for many features; see
1033 @ref{Existing Tests}, for their descriptions.  For most other features,
1034 you can use Autoconf template macros to produce custom checks; see
1035 @ref{Writing Tests}, for information about them.  For especially tricky
1036 or specialized features, @file{configure.ac} might need to contain some
1037 hand-crafted shell commands; see @ref{Portable Shell, , Portable Shell
1038 Programming}.  The @command{autoscan} program can give you a good start
1039 in writing @file{configure.ac} (@pxref{autoscan Invocation}, for more
1040 information).
1042 Previous versions of Autoconf promoted the name @file{configure.in},
1043 which is somewhat ambiguous (the tool needed to process this file is not
1044 described by its extension), and introduces a slight confusion with
1045 @file{config.h.in} and so on (for which @samp{.in} means ``to be
1046 processed by @command{configure}'').  Using @file{configure.ac} is now
1047 preferred.
1049 @menu
1050 * Shell Script Compiler::       Autoconf as solution of a problem
1051 * Autoconf Language::           Programming in Autoconf
1052 * Autoconf Input Layout::       Standard organization of @file{configure.ac}
1053 @end menu
1055 @node Shell Script Compiler
1056 @subsection A Shell Script Compiler
1058 Just as for any other computer language, in order to properly program
1059 @file{configure.ac} in Autoconf you must understand @emph{what} problem
1060 the language tries to address and @emph{how} it does so.
1062 The problem Autoconf addresses is that the world is a mess.  After all,
1063 you are using Autoconf in order to have your package compile easily on
1064 all sorts of different systems, some of them being extremely hostile.
1065 Autoconf itself bears the price for these differences: @command{configure}
1066 must run on all those systems, and thus @command{configure} must limit itself
1067 to their lowest common denominator of features.
1069 Naturally, you might then think of shell scripts; who needs
1070 @command{autoconf}?  A set of properly written shell functions is enough to
1071 make it easy to write @command{configure} scripts by hand.  Sigh!
1072 Unfortunately, even in 2008, where shells without any function support are
1073 far and few between, there are pitfalls to avoid when making use of them.
1074 Also, finding a Bourne shell that accepts shell functions is not trivial,
1075 even though there is almost always one on interesting porting targets.
1077 So, what is really needed is some kind of compiler, @command{autoconf},
1078 that takes an Autoconf program, @file{configure.ac}, and transforms it
1079 into a portable shell script, @command{configure}.
1081 How does @command{autoconf} perform this task?
1083 There are two obvious possibilities: creating a brand new language or
1084 extending an existing one.  The former option is attractive: all
1085 sorts of optimizations could easily be implemented in the compiler and
1086 many rigorous checks could be performed on the Autoconf program
1087 (e.g., rejecting any non-portable construct).  Alternatively, you can
1088 extend an existing language, such as the @code{sh} (Bourne shell)
1089 language.
1091 Autoconf does the latter: it is a layer on top of @code{sh}.  It was
1092 therefore most convenient to implement @command{autoconf} as a macro
1093 expander: a program that repeatedly performs @dfn{macro expansions} on
1094 text input, replacing macro calls with macro bodies and producing a pure
1095 @code{sh} script in the end.  Instead of implementing a dedicated
1096 Autoconf macro expander, it is natural to use an existing
1097 general-purpose macro language, such as M4, and implement the extensions
1098 as a set of M4 macros.
1101 @node Autoconf Language
1102 @subsection The Autoconf Language
1103 @cindex quotation
1105 The Autoconf language differs from many other computer
1106 languages because it treats actual code the same as plain text.  Whereas
1107 in C, for instance, data and instructions have different syntactic
1108 status, in Autoconf their status is rigorously the same.  Therefore, we
1109 need a means to distinguish literal strings from text to be expanded:
1110 quotation.
1112 When calling macros that take arguments, there must not be any white
1113 space between the macro name and the open parenthesis.  Arguments should
1114 be enclosed within the M4 quote characters @samp{[} and @samp{]}, and be
1115 separated by commas.  Any leading blanks or newlines in arguments are ignored,
1116 unless they are quoted.  You should always quote an argument that
1117 might contain a macro name, comma, parenthesis, or a leading blank or
1118 newline.  This rule applies recursively for every macro
1119 call, including macros called from other macros.
1121 For instance:
1123 @example
1124 AC_CHECK_HEADER([stdio.h],
1125                 [AC_DEFINE([HAVE_STDIO_H], [1],
1126                    [Define to 1 if you have <stdio.h>.])],
1127                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1128 @end example
1130 @noindent
1131 is quoted properly.  You may safely simplify its quotation to:
1133 @example
1134 AC_CHECK_HEADER([stdio.h],
1135                 [AC_DEFINE([HAVE_STDIO_H], 1,
1136                    [Define to 1 if you have <stdio.h>.])],
1137                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1138 @end example
1140 @noindent
1141 because @samp{1} cannot contain a macro call.  Here, the argument of
1142 @code{AC_MSG_ERROR} must be quoted; otherwise, its comma would be
1143 interpreted as an argument separator.  Also, the second and third arguments
1144 of @samp{AC_CHECK_HEADER} must be quoted, since they contain
1145 macro calls.  The three arguments @samp{HAVE_STDIO_H}, @samp{stdio.h},
1146 and @samp{Define to 1 if you have <stdio.h>.} do not need quoting, but
1147 if you unwisely defined a macro with a name like @samp{Define} or
1148 @samp{stdio} then they would need quoting.  Cautious Autoconf users
1149 would keep the quotes, but many Autoconf users find such precautions
1150 annoying, and would rewrite the example as follows:
1152 @example
1153 AC_CHECK_HEADER(stdio.h,
1154                 [AC_DEFINE(HAVE_STDIO_H, 1,
1155                    [Define to 1 if you have <stdio.h>.])],
1156                 [AC_MSG_ERROR([Sorry, can't do anything for you])])
1157 @end example
1159 @noindent
1160 This is safe, so long as you adopt good naming conventions and do not
1161 define macros with names like @samp{HAVE_STDIO_H}, @samp{stdio}, or
1162 @samp{h}.  Though it is also safe here to omit the quotes around
1163 @samp{Define to 1 if you have <stdio.h>.} this is not recommended, as
1164 message strings are more likely to inadvertently contain commas.
1166 The following example is wrong and dangerous, as it is underquoted:
1168 @example
1169 AC_CHECK_HEADER(stdio.h,
1170                 AC_DEFINE(HAVE_STDIO_H, 1,
1171                    Define to 1 if you have <stdio.h>.),
1172                 AC_MSG_ERROR([Sorry, can't do anything for you]))
1173 @end example
1175 In other cases, you may have to use text that also resembles a macro
1176 call.  You must quote that text even when it is not passed as a macro
1177 argument:
1179 @example
1180 echo "Hard rock was here!  --[AC_DC]"
1181 @end example
1183 @noindent
1184 which results in:
1186 @example
1187 echo "Hard rock was here!  --AC_DC"
1188 @end example
1190 @noindent
1191 When you use the same text in a macro argument, you must therefore have
1192 an extra quotation level (since one is stripped away by the macro
1193 substitution).  In general, then, it is a good idea to @emph{use double
1194 quoting for all literal string arguments}:
1196 @example
1197 AC_MSG_WARN([[AC_DC stinks  --Iron Maiden]])
1198 @end example
1200 You are now able to understand one of the constructs of Autoconf that
1201 has been continually misunderstood@enddots{}  The rule of thumb is that
1202 @emph{whenever you expect macro expansion, expect quote expansion};
1203 i.e., expect one level of quotes to be lost.  For instance:
1205 @example
1206 AC_COMPILE_IFELSE([char b[10];], [], [AC_MSG_ERROR([you lose])])
1207 @end example
1209 @noindent
1210 is incorrect: here, the first argument of @code{AC_COMPILE_IFELSE} is
1211 @samp{char b[10];} and is expanded once, which results in
1212 @samp{char b10;}.  (There was an idiom common in Autoconf's past to
1213 address this issue via the M4 @code{changequote} primitive, but do not
1214 use it!)  Let's take a closer look: the author meant the first argument
1215 to be understood as a literal, and therefore it must be quoted twice:
1217 @example
1218 AC_COMPILE_IFELSE([[char b[10];]], [], [AC_MSG_ERROR([you lose])])
1219 @end example
1221 @noindent
1222 Voil@`a, you actually produce @samp{char b[10];} this time!
1224 On the other hand, descriptions (e.g., the last parameter of
1225 @code{AC_DEFINE} or @code{AS_HELP_STRING}) are not literals---they
1226 are subject to line breaking, for example---and should not be double quoted.
1227 Even if these descriptions are short and are not actually broken, double
1228 quoting them yields weird results.
1230 Some macros take optional arguments, which this documentation represents
1231 as @ovar{arg} (not to be confused with the quote characters).  You may
1232 just leave them empty, or use @samp{[]} to make the emptiness of the
1233 argument explicit, or you may simply omit the trailing commas.  The
1234 three lines below are equivalent:
1236 @example
1237 AC_CHECK_HEADERS([stdio.h], [], [], [])
1238 AC_CHECK_HEADERS([stdio.h],,,)
1239 AC_CHECK_HEADERS([stdio.h])
1240 @end example
1242 It is best to put each macro call on its own line in
1243 @file{configure.ac}.  Most of the macros don't add extra newlines; they
1244 rely on the newline after the macro call to terminate the commands.
1245 This approach makes the generated @command{configure} script a little
1246 easier to read by not inserting lots of blank lines.  It is generally
1247 safe to set shell variables on the same line as a macro call, because
1248 the shell allows assignments without intervening newlines.
1250 You can include comments in @file{configure.ac} files by starting them
1251 with the @samp{#}.  For example, it is helpful to begin
1252 @file{configure.ac} files with a line like this:
1254 @example
1255 # Process this file with autoconf to produce a configure script.
1256 @end example
1258 @node Autoconf Input Layout
1259 @subsection Standard @file{configure.ac} Layout
1261 The order in which @file{configure.ac} calls the Autoconf macros is not
1262 important, with a few exceptions.  Every @file{configure.ac} must
1263 contain a call to @code{AC_INIT} before the checks, and a call to
1264 @code{AC_OUTPUT} at the end (@pxref{Output}).  Additionally, some macros
1265 rely on other macros having been called first, because they check
1266 previously set values of some variables to decide what to do.  These
1267 macros are noted in the individual descriptions (@pxref{Existing
1268 Tests}), and they also warn you when @command{configure} is created if they
1269 are called out of order.
1271 To encourage consistency, here is a suggested order for calling the
1272 Autoconf macros.  Generally speaking, the things near the end of this
1273 list are those that could depend on things earlier in it.  For example,
1274 library functions could be affected by types and libraries.
1276 @display
1277 @group
1278 Autoconf requirements
1279 @code{AC_INIT(@var{package}, @var{version}, @var{bug-report-address})}
1280 information on the package
1281 checks for programs
1282 checks for libraries
1283 checks for header files
1284 checks for types
1285 checks for structures
1286 checks for compiler characteristics
1287 checks for library functions
1288 checks for system services
1289 @code{AC_CONFIG_FILES(@r{[}@var{file@dots{}}@r{]})}
1290 @code{AC_OUTPUT}
1291 @end group
1292 @end display
1295 @node autoscan Invocation
1296 @section Using @command{autoscan} to Create @file{configure.ac}
1297 @cindex @command{autoscan}
1299 The @command{autoscan} program can help you create and/or maintain a
1300 @file{configure.ac} file for a software package.  @command{autoscan}
1301 examines source files in the directory tree rooted at a directory given
1302 as a command line argument, or the current directory if none is given.
1303 It searches the source files for common portability problems and creates
1304 a file @file{configure.scan} which is a preliminary @file{configure.ac}
1305 for that package, and checks a possibly existing @file{configure.ac} for
1306 completeness.
1308 When using @command{autoscan} to create a @file{configure.ac}, you
1309 should manually examine @file{configure.scan} before renaming it to
1310 @file{configure.ac}; it probably needs some adjustments.
1311 Occasionally, @command{autoscan} outputs a macro in the wrong order
1312 relative to another macro, so that @command{autoconf} produces a warning;
1313 you need to move such macros manually.  Also, if you want the package to
1314 use a configuration header file, you must add a call to
1315 @code{AC_CONFIG_HEADERS} (@pxref{Configuration Headers}).  You might
1316 also have to change or add some @code{#if} directives to your program in
1317 order to make it work with Autoconf (@pxref{ifnames Invocation}, for
1318 information about a program that can help with that job).
1320 When using @command{autoscan} to maintain a @file{configure.ac}, simply
1321 consider adding its suggestions.  The file @file{autoscan.log}
1322 contains detailed information on why a macro is requested.
1324 @command{autoscan} uses several data files (installed along with Autoconf)
1325 to determine which macros to output when it finds particular symbols in
1326 a package's source files.  These data files all have the same format:
1327 each line consists of a symbol, one or more blanks, and the Autoconf macro to
1328 output if that symbol is encountered.  Lines starting with @samp{#} are
1329 comments.
1331 @command{autoscan} accepts the following options:
1333 @table @option
1334 @item --help
1335 @itemx -h
1336 Print a summary of the command line options and exit.
1338 @item --version
1339 @itemx -V
1340 Print the version number of Autoconf and exit.
1342 @item --verbose
1343 @itemx -v
1344 Print the names of the files it examines and the potentially interesting
1345 symbols it finds in them.  This output can be voluminous.
1347 @item --debug
1348 @itemx -d
1349 Don't remove temporary files.
1351 @item --include=@var{dir}
1352 @itemx -I @var{dir}
1353 Append @var{dir} to the include path.  Multiple invocations accumulate.
1355 @item --prepend-include=@var{dir}
1356 @itemx -B @var{dir}
1357 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1358 @end table
1360 @node ifnames Invocation
1361 @section Using @command{ifnames} to List Conditionals
1362 @cindex @command{ifnames}
1364 @command{ifnames} can help you write @file{configure.ac} for a software
1365 package.  It prints the identifiers that the package already uses in C
1366 preprocessor conditionals.  If a package has already been set up to have
1367 some portability, @command{ifnames} can thus help you figure out what its
1368 @command{configure} needs to check for.  It may help fill in some gaps in a
1369 @file{configure.ac} generated by @command{autoscan} (@pxref{autoscan
1370 Invocation}).
1372 @command{ifnames} scans all of the C source files named on the command line
1373 (or the standard input, if none are given) and writes to the standard
1374 output a sorted list of all the identifiers that appear in those files
1375 in @code{#if}, @code{#elif}, @code{#ifdef}, or @code{#ifndef}
1376 directives.  It prints each identifier on a line, followed by a
1377 space-separated list of the files in which that identifier occurs.
1379 @noindent
1380 @command{ifnames} accepts the following options:
1382 @table @option
1383 @item --help
1384 @itemx -h
1385 Print a summary of the command line options and exit.
1387 @item --version
1388 @itemx -V
1389 Print the version number of Autoconf and exit.
1390 @end table
1392 @node autoconf Invocation
1393 @section Using @command{autoconf} to Create @command{configure}
1394 @cindex @command{autoconf}
1396 To create @command{configure} from @file{configure.ac}, run the
1397 @command{autoconf} program with no arguments.  @command{autoconf} processes
1398 @file{configure.ac} with the M4 macro processor, using the
1399 Autoconf macros.  If you give @command{autoconf} an argument, it reads that
1400 file instead of @file{configure.ac} and writes the configuration script
1401 to the standard output instead of to @command{configure}.  If you give
1402 @command{autoconf} the argument @option{-}, it reads from the standard
1403 input instead of @file{configure.ac} and writes the configuration script
1404 to the standard output.
1406 The Autoconf macros are defined in several files.  Some of the files are
1407 distributed with Autoconf; @command{autoconf} reads them first.  Then it
1408 looks for the optional file @file{acsite.m4} in the directory that
1409 contains the distributed Autoconf macro files, and for the optional file
1410 @file{aclocal.m4} in the current directory.  Those files can contain
1411 your site's or the package's own Autoconf macro definitions
1412 (@pxref{Writing Autoconf Macros}, for more information).  If a macro is
1413 defined in more than one of the files that @command{autoconf} reads, the
1414 last definition it reads overrides the earlier ones.
1416 @command{autoconf} accepts the following options:
1418 @table @option
1419 @item --help
1420 @itemx -h
1421 Print a summary of the command line options and exit.
1423 @item --version
1424 @itemx -V
1425 Print the version number of Autoconf and exit.
1427 @item --verbose
1428 @itemx -v
1429 Report processing steps.
1431 @item --debug
1432 @itemx -d
1433 Don't remove the temporary files.
1435 @item --force
1436 @itemx -f
1437 Remake @file{configure} even if newer than its input files.
1439 @item --include=@var{dir}
1440 @itemx -I @var{dir}
1441 Append @var{dir} to the include path.  Multiple invocations accumulate.
1443 @item --prepend-include=@var{dir}
1444 @itemx -B @var{dir}
1445 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1447 @item --output=@var{file}
1448 @itemx -o @var{file}
1449 Save output (script or trace) to @var{file}.  The file @option{-} stands
1450 for the standard output.
1452 @item --warnings=@var{category}
1453 @itemx -W @var{category}
1454 @evindex WARNINGS
1455 Report the warnings related to @var{category} (which can actually be a
1456 comma separated list).  @xref{Reporting Messages}, macro
1457 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
1458 values include:
1460 @table @samp
1461 @item all
1462 report all the warnings
1464 @item none
1465 report none
1467 @item error
1468 treats warnings as errors
1470 @item no-@var{category}
1471 disable warnings falling into @var{category}
1472 @end table
1474 Warnings about @samp{syntax} are enabled by default, and the environment
1475 variable @env{WARNINGS}, a comma separated list of categories, is
1476 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1477 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1478 disable the defaults and @env{WARNINGS}, and then
1479 enable warnings about obsolete constructs, use @option{-W
1480 none,obsolete}.
1482 @cindex Back trace
1483 @cindex Macro invocation stack
1484 Because @command{autoconf} uses @command{autom4te} behind the scenes, it
1485 displays a back trace for errors, but not for warnings; if you want
1486 them, just pass @option{-W error}.  @xref{autom4te Invocation}, for some
1487 examples.
1489 @item --trace=@var{macro}[:@var{format}]
1490 @itemx -t @var{macro}[:@var{format}]
1491 Do not create the @command{configure} script, but list the calls to
1492 @var{macro} according to the @var{format}.  Multiple @option{--trace}
1493 arguments can be used to list several macros.  Multiple @option{--trace}
1494 arguments for a single macro are not cumulative; instead, you should
1495 just make @var{format} as long as needed.
1497 The @var{format} is a regular string, with newlines if desired, and
1498 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}; see
1499 @ref{autom4te Invocation}, for details on the @var{format}.
1501 @item --initialization
1502 @itemx -i
1503 By default, @option{--trace} does not trace the initialization of the
1504 Autoconf macros (typically the @code{AC_DEFUN} definitions).  This
1505 results in a noticeable speedup, but can be disabled by this option.
1506 @end table
1509 It is often necessary to check the content of a @file{configure.ac}
1510 file, but parsing it yourself is extremely fragile and error-prone.  It
1511 is suggested that you rely upon @option{--trace} to scan
1512 @file{configure.ac}.  For instance, to find the list of variables that
1513 are substituted, use:
1515 @example
1516 @group
1517 $ @kbd{autoconf -t AC_SUBST}
1518 configure.ac:2:AC_SUBST:ECHO_C
1519 configure.ac:2:AC_SUBST:ECHO_N
1520 configure.ac:2:AC_SUBST:ECHO_T
1521 @i{More traces deleted}
1522 @end group
1523 @end example
1525 @noindent
1526 The example below highlights the difference between @samp{$@@},
1527 @samp{$*}, and @samp{$%}.
1529 @example
1530 @group
1531 $ @kbd{cat configure.ac}
1532 AC_DEFINE(This, is, [an
1533 [example]])
1534 $ @kbd{autoconf -t 'AC_DEFINE:@@: $@@}
1535 *: $*
1536 %: $%'
1537 @@: [This],[is],[an
1538 [example]]
1539 *: This,is,an
1540 [example]
1541 %: This:is:an [example]
1542 @end group
1543 @end example
1545 @noindent
1546 The @var{format} gives you a lot of freedom:
1548 @example
1549 @group
1550 $ @kbd{autoconf -t 'AC_SUBST:$$ac_subst@{"$1"@} = "$f:$l";'}
1551 $ac_subst@{"ECHO_C"@} = "configure.ac:2";
1552 $ac_subst@{"ECHO_N"@} = "configure.ac:2";
1553 $ac_subst@{"ECHO_T"@} = "configure.ac:2";
1554 @i{More traces deleted}
1555 @end group
1556 @end example
1558 @noindent
1559 A long @var{separator} can be used to improve the readability of complex
1560 structures, and to ease their parsing (for instance when no single
1561 character is suitable as a separator):
1563 @example
1564 @group
1565 $ @kbd{autoconf -t 'AM_MISSING_PROG:$@{|:::::|@}*'}
1566 ACLOCAL|:::::|aclocal|:::::|$missing_dir
1567 AUTOCONF|:::::|autoconf|:::::|$missing_dir
1568 AUTOMAKE|:::::|automake|:::::|$missing_dir
1569 @i{More traces deleted}
1570 @end group
1571 @end example
1573 @node autoreconf Invocation
1574 @section Using @command{autoreconf} to Update @command{configure} Scripts
1575 @cindex @command{autoreconf}
1577 Installing the various components of the @acronym{GNU} Build System can be
1578 tedious: running @command{autopoint} for Gettext, @command{automake} for
1579 @file{Makefile.in} etc.@: in each directory.  It may be needed either
1580 because some tools such as @command{automake} have been updated on your
1581 system, or because some of the sources such as @file{configure.ac} have
1582 been updated, or finally, simply in order to install the @acronym{GNU} Build
1583 System in a fresh tree.
1585 @command{autoreconf} runs @command{autoconf}, @command{autoheader},
1586 @command{aclocal}, @command{automake}, @command{libtoolize}, and
1587 @command{autopoint} (when appropriate) repeatedly to update the
1588 @acronym{GNU} Build System in the specified directories and their
1589 subdirectories (@pxref{Subdirectories}).  By default, it only remakes
1590 those files that are older than their sources.  The environment variables
1591 @env{AUTOCONF}, @env{AUTOHEADER}, @env{AUTOMAKE}, @env{ACLOCAL},
1592 @env{AUTOPOINT}, @env{LIBTOOLIZE}, @env{M4}, and @env{MAKE} may be used
1593 to override the invocation of the respective tools.
1595 If you install a new version of some tool, you can make
1596 @command{autoreconf} remake @emph{all} of the files by giving it the
1597 @option{--force} option.
1599 @xref{Automatic Remaking}, for Make rules to automatically
1600 rebuild @command{configure} scripts when their source files change.  That
1601 method handles the timestamps of configuration header templates
1602 properly, but does not pass @option{--autoconf-dir=@var{dir}} or
1603 @option{--localdir=@var{dir}}.
1605 @cindex Gettext
1606 @cindex @command{autopoint}
1607 Gettext supplies the @command{autopoint} command to add translation
1608 infrastructure to a source package.  If you use @command{autopoint},
1609 your @file{configure.ac} should invoke both @code{AM_GNU_GETTEXT} and
1610 @code{AM_GNU_GETTEXT_VERSION(@var{gettext-version})}.  @xref{autopoint
1611 Invocation, , Invoking the @code{autopoint} Program, gettext,
1612 @acronym{GNU} @code{gettext} utilities}, for further details.
1614 @noindent
1615 @command{autoreconf} accepts the following options:
1617 @table @option
1618 @item --help
1619 @itemx -h
1620 Print a summary of the command line options and exit.
1622 @item --version
1623 @itemx -V
1624 Print the version number of Autoconf and exit.
1626 @item --verbose
1627 @itemx -V
1628 Print the name of each directory @command{autoreconf} examines and the
1629 commands it runs.  If given two or more times, pass @option{--verbose}
1630 to subordinate tools that support it.
1632 @item --debug
1633 @itemx -d
1634 Don't remove the temporary files.
1636 @item --force
1637 @itemx -f
1638 Remake even @file{configure} scripts and configuration headers that are
1639 newer than their input files (@file{configure.ac} and, if present,
1640 @file{aclocal.m4}).
1642 @item --install
1643 @itemx -i
1644 Install the missing auxiliary files in the package.  By default, files
1645 are copied; this can be changed with @option{--symlink}.
1647 If deemed appropriate, this option triggers calls to
1648 @samp{automake --add-missing},
1649 @samp{libtoolize}, @samp{autopoint}, etc.
1651 @item --no-recursive
1652 Do not rebuild files in subdirectories to configure (see @ref{Subdirectories},
1653 macro @code{AC_CONFIG_SUBDIRS}).
1655 @item --symlink
1656 @itemx -s
1657 When used with @option{--install}, install symbolic links to the missing
1658 auxiliary files instead of copying them.
1660 @item --make
1661 @itemx -m
1662 When the directories were configured, update the configuration by
1663 running @samp{./config.status --recheck && ./config.status}, and then
1664 run @samp{make}.
1666 @item --include=@var{dir}
1667 @itemx -I @var{dir}
1668 Append @var{dir} to the include path.  Multiple invocations accumulate.
1669 Passed on to @command{aclocal}, @command{autoconf} and
1670 @command{autoheader} internally.
1672 @item --prepend-include=@var{dir}
1673 @itemx -B @var{dir}
1674 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
1675 Passed on to @command{autoconf} and @command{autoheader} internally.
1677 @item --warnings=@var{category}
1678 @itemx -W @var{category}
1679 @evindex WARNINGS
1680 Report the warnings related to @var{category} (which can actually be a
1681 comma separated list).
1683 @table @samp
1684 @item cross
1685 related to cross compilation issues.
1687 @item obsolete
1688 report the uses of obsolete constructs.
1690 @item portability
1691 portability issues
1693 @item syntax
1694 dubious syntactic constructs.
1696 @item all
1697 report all the warnings
1699 @item none
1700 report none
1702 @item error
1703 treats warnings as errors
1705 @item no-@var{category}
1706 disable warnings falling into @var{category}
1707 @end table
1709 Warnings about @samp{syntax} are enabled by default, and the environment
1710 variable @env{WARNINGS}, a comma separated list of categories, is
1711 honored as well.  Passing @option{-W @var{category}} actually behaves as if
1712 you had passed @option{--warnings syntax,$WARNINGS,@var{category}}.  To
1713 disable the defaults and @env{WARNINGS}, and then
1714 enable warnings about obsolete constructs, use @option{-W
1715 none,obsolete}.
1716 @end table
1718 If you want @command{autoreconf} to pass flags that are not listed here
1719 on to @command{aclocal}, set @code{ACLOCAL_AMFLAGS} in your @file{Makefile.am}.
1720 Due to a limitation in the Autoconf implementation these flags currently
1721 must be set on a single line in @file{Makefile.am}, without any
1722 backslash-newlines.
1724 @c ========================================= Initialization and Output Files.
1726 @node Setup
1727 @chapter Initialization and Output Files
1729 Autoconf-generated @command{configure} scripts need some information about
1730 how to initialize, such as how to find the package's source files and
1731 about the output files to produce.  The following sections describe the
1732 initialization and the creation of output files.
1734 @menu
1735 * Initializing configure::      Option processing etc.
1736 * Versioning::                  Dealing with Autoconf versions
1737 * Notices::                     Copyright, version numbers in @command{configure}
1738 * Input::                       Where Autoconf should find files
1739 * Output::                      Outputting results from the configuration
1740 * Configuration Actions::       Preparing the output based on results
1741 * Configuration Files::         Creating output files
1742 * Makefile Substitutions::      Using output variables in makefiles
1743 * Configuration Headers::       Creating a configuration header file
1744 * Configuration Commands::      Running arbitrary instantiation commands
1745 * Configuration Links::         Links depending on the configuration
1746 * Subdirectories::              Configuring independent packages together
1747 * Default Prefix::              Changing the default installation prefix
1748 @end menu
1750 @node Initializing configure
1751 @section Initializing @command{configure}
1753 Every @command{configure} script must call @code{AC_INIT} before doing
1754 anything else.  The only other required macro is @code{AC_OUTPUT}
1755 (@pxref{Output}).
1757 @anchor{AC_INIT}
1758 @defmac AC_INIT (@var{package}, @var{version}, @ovar{bug-report}, @
1759   @ovar{tarname}, @ovar{url})
1760 @acindex{INIT}
1761 Process any command-line arguments and perform various initializations
1762 and verifications.
1764 Set the name of the @var{package} and its @var{version}.  These are
1765 typically used in @option{--version} support, including that of
1766 @command{configure}.  The optional argument @var{bug-report} should be
1767 the email to which users should send bug reports.  The package
1768 @var{tarname} differs from @var{package}: the latter designates the full
1769 package name (e.g., @samp{GNU Autoconf}), while the former is meant for
1770 distribution tar ball names (e.g., @samp{autoconf}).  It defaults to
1771 @var{package} with @samp{GNU } stripped, lower-cased, and all characters
1772 other than alphanumerics and underscores are changed to @samp{-}.  If
1773 provided, @var{url} should be the home page for the package.
1775 It is preferable that the arguments of @code{AC_INIT} be static, i.e.,
1776 there should not be any shell computation, but they can be computed by
1779 The following M4 macros (e.g., @code{AC_PACKAGE_NAME}), output variables
1780 (e.g., @code{PACKAGE_NAME}), and preprocessor symbols (e.g.,
1781 @code{PACKAGE_NAME}), are defined by @code{AC_INIT}:
1783 @table @asis
1784 @item @code{AC_PACKAGE_NAME}, @code{PACKAGE_NAME}
1785 @acindex{PACKAGE_NAME}
1786 @ovindex PACKAGE_NAME
1787 @cvindex PACKAGE_NAME
1788 Exactly @var{package}.
1790 @item @code{AC_PACKAGE_TARNAME}, @code{PACKAGE_TARNAME}
1791 @acindex{PACKAGE_TARNAME}
1792 @ovindex PACKAGE_TARNAME
1793 @cvindex PACKAGE_TARNAME
1794 Exactly @var{tarname}, possibly generated from @var{package}.
1796 @item @code{AC_PACKAGE_VERSION}, @code{PACKAGE_VERSION}
1797 @acindex{PACKAGE_VERSION}
1798 @ovindex PACKAGE_VERSION
1799 @cvindex PACKAGE_VERSION
1800 Exactly @var{version}.
1802 @item @code{AC_PACKAGE_STRING}, @code{PACKAGE_STRING}
1803 @acindex{PACKAGE_STRING}
1804 @ovindex PACKAGE_STRING
1805 @cvindex PACKAGE_STRING
1806 Exactly @samp{@var{package} @var{version}}.
1808 @item @code{AC_PACKAGE_BUGREPORT}, @code{PACKAGE_BUGREPORT}
1809 @acindex{PACKAGE_BUGREPORT}
1810 @ovindex PACKAGE_BUGREPORT
1811 @cvindex PACKAGE_BUGREPORT
1812 Exactly @var{bug-report}, if one was provided.
1814 @item @code{AC_PACKAGE_URL}, @code{PACKAGE_URL}
1815 @acindex{PACKAGE_URL}
1816 @ovindex PACKAGE_URL
1817 @cvindex PACKAGE_URL
1818 Exactly @var{url}, if one was provided.  If @var{url} was empty, but
1819 @var{package} begins with @samp{GNU }, then this defaults to
1820 @samp{http://@/www.gnu.org/@/software/@/@var{tarname}/}, otherwise, no URL is
1821 assumed.
1822 @end table
1823 @end defmac
1825 If your @command{configure} script does its own option processing, it
1826 should inspect @samp{$@@} or @samp{$*} immediately after calling
1827 @code{AC_INIT}, because other Autoconf macros liberally use the
1828 @command{set} command to process strings, and this has the side effect
1829 of updating @samp{$@@} and @samp{$*}.  However, we suggest that you use
1830 standard macros like @code{AC_ARG_ENABLE} instead of attempting to
1831 implement your own option processing.  @xref{Site Configuration}.
1833 @node Versioning
1834 @section Dealing with Autoconf versions
1835 @cindex Autoconf version
1836 @cindex version, Autoconf
1838 The following optional macros can be used to help choose the minimum
1839 version of Autoconf that can successfully compile a given
1840 @file{configure.ac}.
1842 @defmac AC_PREREQ (@var{version})
1843 @acindex{PREREQ}
1844 @cindex Version
1845 Ensure that a recent enough version of Autoconf is being used.  If the
1846 version of Autoconf being used to create @command{configure} is
1847 earlier than @var{version}, print an error message to the standard
1848 error output and exit with failure (exit status is 63).  For example:
1850 @example
1851 AC_PREREQ([@value{VERSION}])
1852 @end example
1854 This macro is the only macro that may be used before @code{AC_INIT}, but
1855 for consistency, you are invited not to do so.
1856 @end defmac
1858 @defmac AC_AUTOCONF_VERSION
1859 @acindex{AUTOCONF_VERSION}
1860 This macro was introduced in Autoconf 2.62.  It identifies the version
1861 of Autoconf that is currently parsing the input file, in a format
1862 suitable for @code{m4_version_compare} (@pxref{m4_version_compare}); in
1863 other words, for this release of Autoconf, its value is
1864 @samp{@value{VERSION}}.  One potential use of this macro is for writing
1865 conditional fallbacks based on when a feature was added to Autoconf,
1866 rather than using @code{AC_PREREQ} to require the newer version of
1867 Autoconf.  However, remember that the Autoconf philosophy favors feature
1868 checks over version checks.
1870 You should not expand this macro directly; use
1871 @samp{m4_defn([AC_AUTOCONF_VERSION])} instead.  This is because some
1872 users might
1873 have a beta version of Autoconf installed, with arbitrary letters
1874 included in its version string.  This means it is possible for the
1875 version string to contain the name of a defined macro, such that
1876 expanding @code{AC_AUTOCONF_VERSION} would trigger the expansion of that
1877 macro during rescanning, and change the version string to be different
1878 than what you intended to check.
1879 @end defmac
1881 @node Notices
1882 @section Notices in @command{configure}
1883 @cindex Notices in @command{configure}
1885 The following macros manage version numbers for @command{configure}
1886 scripts.  Using them is optional.
1888 @defmac AC_COPYRIGHT (@var{copyright-notice})
1889 @acindex{COPYRIGHT}
1890 @cindex Copyright Notice
1891 State that, in addition to the Free Software Foundation's copyright on
1892 the Autoconf macros, parts of your @command{configure} are covered by the
1893 @var{copyright-notice}.
1895 The @var{copyright-notice} shows up in both the head of
1896 @command{configure} and in @samp{configure --version}.
1897 @end defmac
1900 @defmac AC_REVISION (@var{revision-info})
1901 @acindex{REVISION}
1902 @cindex Revision
1903 Copy revision stamp @var{revision-info} into the @command{configure}
1904 script, with any dollar signs or double-quotes removed.  This macro lets
1905 you put a revision stamp from @file{configure.ac} into @command{configure}
1906 without @acronym{RCS} or @acronym{CVS} changing it when you check in
1907 @command{configure}.  That way, you can determine easily which revision of
1908 @file{configure.ac} a particular @command{configure} corresponds to.
1910 For example, this line in @file{configure.ac}:
1912 @c The @w prevents RCS from changing the example in the manual.
1913 @example
1914 AC_REVISION([@w{$}Revision: 1.30 $])
1915 @end example
1917 @noindent
1918 produces this in @command{configure}:
1920 @example
1921 #!/bin/sh
1922 # From configure.ac Revision: 1.30
1923 @end example
1924 @end defmac
1927 @node Input
1928 @section Finding @command{configure} Input
1930 @anchor{AC_CONFIG_SRCDIR}
1931 @defmac AC_CONFIG_SRCDIR (@var{unique-file-in-source-dir})
1932 @acindex{CONFIG_SRCDIR}
1933 @var{unique-file-in-source-dir} is some file that is in the package's
1934 source directory; @command{configure} checks for this file's existence to
1935 make sure that the directory that it is told contains the source code in
1936 fact does.  Occasionally people accidentally specify the wrong directory
1937 with @option{--srcdir}; this is a safety check.  @xref{configure
1938 Invocation}, for more information.
1939 @end defmac
1942 @c FIXME: Remove definitively once --install explained.
1944 @c Small packages may store all their macros in @code{aclocal.m4}.  As the
1945 @c set of macros grows, or for maintenance reasons, a maintainer may prefer
1946 @c to split the macros in several files.  In this case, Autoconf must be
1947 @c told which files to load, and in which order.
1949 @c @defmac AC_INCLUDE (@var{file}@dots{})
1950 @c @acindex{INCLUDE}
1951 @c @c FIXME: There is no longer shell globbing.
1952 @c Read the macro definitions that appear in the listed files.  A list of
1953 @c space-separated file names or shell globbing patterns is expected.  The
1954 @c files are read in the order they're listed.
1956 @c Because the order of definition of macros is important (only the last
1957 @c definition of a macro is used), beware that it is @code{AC_INIT} that
1958 @c loads @file{acsite.m4} and @file{aclocal.m4}.  Note that
1959 @c @code{AC_INCLUDE}ing a file before @code{AC_INIT} or within
1960 @c @file{aclocal.m4} is different from doing so after @code{AC_INIT}: in
1961 @c the latter case, non-macro lines from included files may end up in the
1962 @c @file{configure} script, whereas in the former case, they'd be discarded
1963 @c just like any text that appear before @code{AC_INIT}.
1964 @c @end defmac
1966 Packages that do manual configuration or use the @command{install} program
1967 might need to tell @command{configure} where to find some other shell
1968 scripts by calling @code{AC_CONFIG_AUX_DIR}, though the default places
1969 it looks are correct for most cases.
1971 @defmac AC_CONFIG_AUX_DIR (@var{dir})
1972 @acindex{CONFIG_AUX_DIR}
1973 Use the auxiliary build tools (e.g., @file{install-sh},
1974 @file{config.sub}, @file{config.guess}, Cygnus @command{configure},
1975 Automake and Libtool scripts, etc.)@: that are in directory @var{dir}.
1976 These are auxiliary files used in configuration.  @var{dir} can be
1977 either absolute or relative to @file{@var{srcdir}}.  The default is
1978 @file{@var{srcdir}} or @file{@var{srcdir}/..} or
1979 @file{@var{srcdir}/../..}, whichever is the first that contains
1980 @file{install-sh}.  The other files are not checked for, so that using
1981 @code{AC_PROG_INSTALL} does not automatically require distributing the
1982 other auxiliary files.  It checks for @file{install.sh} also, but that
1983 name is obsolete because some @command{make} have a rule that creates
1984 @file{install} from it if there is no makefile.
1986 The auxiliary directory is commonly named @file{build-aux}.
1987 If you need portability to @acronym{DOS} variants, do not name the
1988 auxiliary directory @file{aux}.  @xref{File System Conventions}.
1989 @end defmac
1991 @defmac AC_REQUIRE_AUX_FILE (@var{file})
1992 @acindex{REQUIRE_AUX_FILE}
1993 Declares that @var{file} is expected in the directory defined above.  In
1994 Autoconf proper, this macro does nothing: its sole purpose is to be
1995 traced by third-party tools to produce a list of expected auxiliary
1996 files.  For instance it is called by macros like @code{AC_PROG_INSTALL}
1997 (@pxref{Particular Programs}) or @code{AC_CANONICAL_BUILD}
1998 (@pxref{Canonicalizing}) to register the auxiliary files they need.
1999 @end defmac
2001 Similarly, packages that use @command{aclocal} should declare where
2002 local macros can be found using @code{AC_CONFIG_MACRO_DIR}.
2004 @defmac AC_CONFIG_MACRO_DIR (@var{dir})
2005 @acindex{CONFIG_MACRO_DIR}
2006 Specify @var{dir} as the location of additional local Autoconf macros.
2007 This macro is intended for use by future versions of commands like
2008 @command{autoreconf} that trace macro calls.  It should be called
2009 directly from @file{configure.ac} so that tools that install macros for
2010 @command{aclocal} can find the macros' declarations.
2012 Note that if you use @command{aclocal} from Automake to generate
2013 @file{aclocal.m4}, you must also set @code{ACLOCAL_AMFLAGS = -I
2014 @var{dir}} in your top-level @file{Makefile.am}.  Due to a limitation in
2015 the Autoconf implementation of @command{autoreconf}, these include
2016 directives currently must be set on a single line in @file{Makefile.am},
2017 without any backslash-newlines.
2018 @end defmac
2021 @node Output
2022 @section Outputting Files
2023 @cindex Outputting files
2025 Every Autoconf script, e.g., @file{configure.ac}, should finish by
2026 calling @code{AC_OUTPUT}.  That is the macro that generates and runs
2027 @file{config.status}, which in turn creates the makefiles and any
2028 other files resulting from configuration.  This is the only required
2029 macro besides @code{AC_INIT} (@pxref{Input}).
2031 @anchor{AC_OUTPUT}
2032 @defmac AC_OUTPUT
2033 @acindex{OUTPUT}
2034 @cindex Instantiation
2035 Generate @file{config.status} and launch it.  Call this macro once, at
2036 the end of @file{configure.ac}.
2038 @file{config.status} performs all the configuration actions: all the
2039 output files (see @ref{Configuration Files}, macro
2040 @code{AC_CONFIG_FILES}), header files (see @ref{Configuration Headers},
2041 macro @code{AC_CONFIG_HEADERS}), commands (see @ref{Configuration
2042 Commands}, macro @code{AC_CONFIG_COMMANDS}), links (see
2043 @ref{Configuration Links}, macro @code{AC_CONFIG_LINKS}), subdirectories
2044 to configure (see @ref{Subdirectories}, macro @code{AC_CONFIG_SUBDIRS})
2045 are honored.
2047 The location of your @code{AC_OUTPUT} invocation is the exact point
2048 where configuration actions are taken: any code afterwards is
2049 executed by @command{configure} once @command{config.status} was run.  If
2050 you want to bind actions to @command{config.status} itself
2051 (independently of whether @command{configure} is being run), see
2052 @ref{Configuration Commands, , Running Arbitrary Configuration
2053 Commands}.
2054 @end defmac
2056 Historically, the usage of @code{AC_OUTPUT} was somewhat different.
2057 @xref{Obsolete Macros}, for a description of the arguments that
2058 @code{AC_OUTPUT} used to support.
2061 If you run @command{make} in subdirectories, you should run it using the
2062 @command{make} variable @code{MAKE}.  Most versions of @command{make} set
2063 @code{MAKE} to the name of the @command{make} program plus any options it
2064 was given.  (But many do not include in it the values of any variables
2065 set on the command line, so those are not passed on automatically.)
2066 Some old versions of @command{make} do not set this variable.  The
2067 following macro allows you to use it even with those versions.
2069 @anchor{AC_PROG_MAKE_SET}
2070 @defmac AC_PROG_MAKE_SET
2071 @acindex{PROG_MAKE_SET}
2072 @ovindex SET_MAKE
2073 If the Make command, @code{$MAKE} if set or else @samp{make}, predefines
2074 @code{$(MAKE)}, define output variable @code{SET_MAKE} to be empty.
2075 Otherwise, define @code{SET_MAKE} to a macro definition that sets
2076 @code{$(MAKE)}, such as @samp{MAKE=make}.  Calls @code{AC_SUBST} for
2077 @code{SET_MAKE}.
2078 @end defmac
2080 If you use this macro, place a line like this in each @file{Makefile.in}
2081 that runs @command{MAKE} on other directories:
2083 @example
2084 @@SET_MAKE@@
2085 @end example
2089 @node Configuration Actions
2090 @section Performing Configuration Actions
2091 @cindex Configuration actions
2093 @file{configure} is designed so that it appears to do everything itself,
2094 but there is actually a hidden slave: @file{config.status}.
2095 @file{configure} is in charge of examining your system, but it is
2096 @file{config.status} that actually takes the proper actions based on the
2097 results of @file{configure}.  The most typical task of
2098 @file{config.status} is to @emph{instantiate} files.
2100 This section describes the common behavior of the four standard
2101 instantiating macros: @code{AC_CONFIG_FILES}, @code{AC_CONFIG_HEADERS},
2102 @code{AC_CONFIG_COMMANDS} and @code{AC_CONFIG_LINKS}.  They all
2103 have this prototype:
2105 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
2106 @c awful.
2107 @example
2108 AC_CONFIG_FOOS(@var{tag}@dots{}, [@var{commands}], [@var{init-cmds}])
2109 @end example
2111 @noindent
2112 where the arguments are:
2114 @table @var
2115 @item tag@dots{}
2116 A blank-or-newline-separated list of tags, which are typically the names of
2117 the files to instantiate.
2119 You are encouraged to use literals as @var{tags}.  In particular, you
2120 should avoid
2122 @example
2123 @dots{} && my_foos="$my_foos fooo"
2124 @dots{} && my_foos="$my_foos foooo"
2125 AC_CONFIG_FOOS([$my_foos])
2126 @end example
2128 @noindent
2129 and use this instead:
2131 @example
2132 @dots{} && AC_CONFIG_FOOS([fooo])
2133 @dots{} && AC_CONFIG_FOOS([foooo])
2134 @end example
2136 The macros @code{AC_CONFIG_FILES} and @code{AC_CONFIG_HEADERS} use
2137 special @var{tag} values: they may have the form @samp{@var{output}} or
2138 @samp{@var{output}:@var{inputs}}.  The file @var{output} is instantiated
2139 from its templates, @var{inputs} (defaulting to @samp{@var{output}.in}).
2141 @samp{AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk)]},
2142 for example, asks for
2143 the creation of the file @file{Makefile} that contains the expansion of the
2144 output variables in the concatenation of @file{boiler/top.mk} and
2145 @file{boiler/bot.mk}.
2147 The special value @samp{-} might be used to denote the standard output
2148 when used in @var{output}, or the standard input when used in the
2149 @var{inputs}.  You most probably don't need to use this in
2150 @file{configure.ac}, but it is convenient when using the command line
2151 interface of @file{./config.status}, see @ref{config.status Invocation},
2152 for more details.
2154 The @var{inputs} may be absolute or relative file names.  In the latter
2155 case they are first looked for in the build tree, and then in the source
2156 tree.
2158 @item commands
2159 Shell commands output literally into @file{config.status}, and
2160 associated with a tag that the user can use to tell @file{config.status}
2161 which commands to run.  The commands are run each time a @var{tag}
2162 request is given to @file{config.status}, typically each time the file
2163 @file{@var{tag}} is created.
2165 The variables set during the execution of @command{configure} are
2166 @emph{not} available here: you first need to set them via the
2167 @var{init-cmds}.  Nonetheless the following variables are precomputed:
2169 @table @code
2170 @item srcdir
2171 The name of the top source directory, assuming that the working
2172 directory is the top build directory.  This
2173 is what the @command{configure} option @option{--srcdir} sets.
2175 @item ac_top_srcdir
2176 The name of the top source directory, assuming that the working
2177 directory is the current build directory.
2180 @item ac_top_build_prefix
2181 The name of the top build directory, assuming that the working
2182 directory is the current build directory.
2183 It can be empty, or else ends with a slash, so that you may concatenate
2186 @item ac_srcdir
2187 The name of the corresponding source directory, assuming that the
2188 working directory is the current build directory.
2189 @end table
2191 @noindent
2192 The @dfn{current} directory refers to the directory (or
2193 pseudo-directory) containing the input part of @var{tags}.  For
2194 instance, running
2196 @example
2197 AC_CONFIG_COMMANDS([deep/dir/out:in/in.in], [@dots{}], [@dots{}])
2198 @end example
2200 @noindent
2201  with @option{--srcdir=../package} produces the following values:
2203 @example
2204 # Argument of --srcdir
2205 srcdir='../package'
2206 # Reversing deep/dir
2207 ac_top_build_prefix='../../'
2208 # Concatenation of $ac_top_build_prefix and srcdir
2209 ac_top_srcdir='../../../package'
2210 # Concatenation of $ac_top_srcdir and deep/dir
2211 ac_srcdir='../../../package/deep/dir'
2212 @end example
2214 @noindent
2215 independently of @samp{in/in.in}.
2217 @item init-cmds
2218 Shell commands output @emph{unquoted} near the beginning of
2219 @file{config.status}, and executed each time @file{config.status} runs
2220 (regardless of the tag).  Because they are unquoted, for example,
2221 @samp{$var} is output as the value of @code{var}.  @var{init-cmds}
2222 is typically used by @file{configure} to give @file{config.status} some
2223 variables it needs to run the @var{commands}.
2225 You should be extremely cautious in your variable names: all the
2226 @var{init-cmds} share the same name space and may overwrite each other
2227 in unpredictable ways.  Sorry@enddots{}
2228 @end table
2230 All these macros can be called multiple times, with different
2231 @var{tag} values, of course!
2234 @node Configuration Files
2235 @section Creating Configuration Files
2236 @cindex Creating configuration files
2237 @cindex Configuration file creation
2239 Be sure to read the previous section, @ref{Configuration Actions}.
2241 @anchor{AC_CONFIG_FILES}
2242 @defmac AC_CONFIG_FILES (@var{file}@dots{}, @ovar{cmds}, @ovar{init-cmds})
2243 @acindex{CONFIG_FILES}
2244 Make @code{AC_OUTPUT} create each @file{@var{file}} by copying an input
2245 file (by default @file{@var{file}.in}), substituting the output variable
2246 values.
2247 @c Before we used to have this feature, which was later rejected
2248 @c because it complicates the writing of makefiles:
2249 @c If the file would be unchanged, it is left untouched, to preserve
2250 @c timestamp.
2251 This macro is one of the instantiating macros; see @ref{Configuration
2252 Actions}.  @xref{Makefile Substitutions}, for more information on using
2253 output variables.  @xref{Setting Output Variables}, for more information
2254 on creating them.  This macro creates the directory that the file is in
2255 if it doesn't exist.  Usually, makefiles are created this way,
2256 but other files, such as @file{.gdbinit}, can be specified as well.
2258 Typical calls to @code{AC_CONFIG_FILES} look like this:
2260 @example
2261 AC_CONFIG_FILES([Makefile src/Makefile man/Makefile X/Imakefile])
2262 AC_CONFIG_FILES([autoconf], [chmod +x autoconf])
2263 @end example
2265 You can override an input file name by appending to @var{file} a
2266 colon-separated list of input files.  Examples:
2268 @example
2269 AC_CONFIG_FILES([Makefile:boiler/top.mk:boiler/bot.mk]
2270                 [lib/Makefile:boiler/lib.mk])
2271 @end example
2273 @noindent
2274 Doing this allows you to keep your file names acceptable to
2275 @acronym{DOS} variants, or
2276 to prepend and/or append boilerplate to the file.
2277 @end defmac
2281 @node Makefile Substitutions
2282 @section Substitutions in Makefiles
2283 @cindex Substitutions in makefiles
2284 @cindex Makefile substitutions
2286 Each subdirectory in a distribution that contains something to be
2287 compiled or installed should come with a file @file{Makefile.in}, from
2288 which @command{configure} creates a file @file{Makefile} in that directory.
2289 To create @file{Makefile}, @command{configure} performs a simple variable
2290 substitution, replacing occurrences of @samp{@@@var{variable}@@} in
2291 @file{Makefile.in} with the value that @command{configure} has determined
2292 for that variable.  Variables that are substituted into output files in
2293 this way are called @dfn{output variables}.  They are ordinary shell
2294 variables that are set in @command{configure}.  To make @command{configure}
2295 substitute a particular variable into the output files, the macro
2296 @code{AC_SUBST} must be called with that variable name as an argument.
2297 Any occurrences of @samp{@@@var{variable}@@} for other variables are
2298 left unchanged.  @xref{Setting Output Variables}, for more information
2299 on creating output variables with @code{AC_SUBST}.
2301 A software package that uses a @command{configure} script should be
2302 distributed with a file @file{Makefile.in}, but no makefile; that
2303 way, the user has to properly configure the package for the local system
2304 before compiling it.
2306 @xref{Makefile Conventions, , Makefile Conventions, standards, The
2307 @acronym{GNU} Coding Standards}, for more information on what to put in
2308 makefiles.
2310 @menu
2311 * Preset Output Variables::     Output variables that are always set
2312 * Installation Directory Variables::  Other preset output variables
2313 * Changed Directory Variables:: Warnings about @file{datarootdir}
2314 * Build Directories::           Supporting multiple concurrent compiles
2315 * Automatic Remaking::          Makefile rules for configuring
2316 @end menu
2318 @node Preset Output Variables
2319 @subsection Preset Output Variables
2320 @cindex Output variables
2322 Some output variables are preset by the Autoconf macros.  Some of the
2323 Autoconf macros set additional output variables, which are mentioned in
2324 the descriptions for those macros.  @xref{Output Variable Index}, for a
2325 complete list of output variables.  @xref{Installation Directory
2326 Variables}, for the list of the preset ones related to installation
2327 directories.  Below are listed the other preset ones.  They all are
2328 precious variables (@pxref{Setting Output Variables},
2329 @code{AC_ARG_VAR}).
2331 @c Just say no to ASCII sorting!  We're humans, not computers.
2332 @c These variables are listed as they would be in a dictionary:
2333 @c actor
2334 @c Actress
2335 @c actress
2337 @defvar CFLAGS
2338 @ovindex CFLAGS
2339 Debugging and optimization options for the C compiler.  If it is not set
2340 in the environment when @command{configure} runs, the default value is set
2341 when you call @code{AC_PROG_CC} (or empty if you don't).  @command{configure}
2342 uses this variable when compiling or linking programs to test for C features.
2344 If a compiler option affects only the behavior of the preprocessor
2345 (e.g., @option{-D @var{name}}), it should be put into @code{CPPFLAGS}
2346 instead.  If it affects only the linker (e.g., @option{-L
2347 @var{directory}}), it should be put into @code{LDFLAGS} instead.  If it
2348 affects only the compiler proper, @code{CFLAGS} is the natural home for
2349 it.  If an option affects multiple phases of the compiler, though,
2350 matters get tricky.  One approach to put such options directly into
2351 @code{CC}, e.g., @code{CC='gcc -m64'}.  Another is to put them into both
2352 @code{CPPFLAGS} and @code{LDFLAGS}, but not into @code{CFLAGS}.
2354 However, remember that some @file{Makefile} variables are reserved by
2355 the GNU Coding Standards for the use of the ``user''---the person
2356 building the package.  For instance, @code{CFLAGS} is one such variable.
2358 Sometimes package developers are tempted to set user variables such as
2359 @code{CFLAGS} because it appears to make their job easier.  However, the
2360 package itself should never set a user variable, particularly not to
2361 include switches that are required for proper compilation of the
2362 package.  Since these variables are documented as being for the package
2363 builder, that person rightfully expects to be able to override any of
2364 these variables at build time.  If the package developer needs to add
2365 switches without interfering with the user, the proper way to do that is
2366 to introduce an additional variable.  Automake makes this easy by
2367 introducing @code{AM_CFLAGS} (@pxref{Flag Variables Ordering, , ,
2368 automake, @acronym{GNU} Automake}), but the concept is the same even if
2369 Automake is not used.
2370 @end defvar
2372 @defvar configure_input
2373 @ovindex configure_input
2374 A comment saying that the file was generated automatically by
2375 @command{configure} and giving the name of the input file.
2376 @code{AC_OUTPUT} adds a comment line containing this variable to the top
2377 of every makefile it creates.  For other files, you should
2378 reference this variable in a comment at the top of each input file.  For
2379 example, an input shell script should begin like this:
2381 @example
2382 #!/bin/sh
2383 # @@configure_input@@
2384 @end example
2386 @noindent
2387 The presence of that line also reminds people editing the file that it
2388 needs to be processed by @command{configure} in order to be used.
2389 @end defvar
2391 @defvar CPPFLAGS
2392 @ovindex CPPFLAGS
2393 Preprocessor options for the C, C++, and Objective C preprocessors and
2394 compilers.  If
2395 it is not set in the environment when @command{configure} runs, the default
2396 value is empty.  @command{configure} uses this variable when preprocessing
2397 or compiling programs to test for C, C++, and Objective C features.
2399 This variable's contents should contain options like @option{-I},
2400 @option{-D}, and @option{-U} that affect only the behavior of the
2401 preprocessor.  Please see the explanation of @code{CFLAGS} for what you
2402 can do if an option affects other phases of the compiler as well.
2404 Currently, @command{configure} always links as part of a single
2405 invocation of the compiler that also preprocesses and compiles, so it
2406 uses this variable also when linking programs.  However, it is unwise to
2407 depend on this behavior because the @acronym{GNU} coding standards do
2408 not require it and many packages do not use @code{CPPFLAGS} when linking
2409 programs.
2411 @xref{Special Chars in Variables}, for limitations that @code{CPPFLAGS}
2412 might run into.
2413 @end defvar
2415 @defvar CXXFLAGS
2416 @ovindex CXXFLAGS
2417 Debugging and optimization options for the C++ compiler.  It acts like
2418 @code{CFLAGS}, but for C++ instead of C.
2419 @end defvar
2421 @defvar DEFS
2422 @ovindex DEFS
2423 @option{-D} options to pass to the C compiler.  If @code{AC_CONFIG_HEADERS}
2424 is called, @command{configure} replaces @samp{@@DEFS@@} with
2425 @option{-DHAVE_CONFIG_H} instead (@pxref{Configuration Headers}).  This
2426 variable is not defined while @command{configure} is performing its tests,
2427 only when creating the output files.  @xref{Setting Output Variables}, for
2428 how to check the results of previous tests.
2429 @end defvar
2431 @defvar ECHO_C
2432 @defvarx ECHO_N
2433 @defvarx ECHO_T
2434 @ovindex ECHO_C
2435 @ovindex ECHO_N
2436 @ovindex ECHO_T
2437 How does one suppress the trailing newline from @command{echo} for
2438 question-answer message pairs?  These variables provide a way:
2440 @example
2441 echo $ECHO_N "And the winner is... $ECHO_C"
2442 sleep 100000000000
2443 echo "$@{ECHO_T@}dead."
2444 @end example
2446 @noindent
2447 Some old and uncommon @command{echo} implementations offer no means to
2448 achieve this, in which case @code{ECHO_T} is set to tab.  You might not
2449 want to use it.
2450 @end defvar
2452 @defvar ERLCFLAGS
2453 @ovindex ERLCFLAGS
2454 Debugging and optimization options for the Erlang compiler.  If it is not set
2455 in the environment when @command{configure} runs, the default value is empty.
2456 @command{configure} uses this variable when compiling
2457 programs to test for Erlang features.
2458 @end defvar
2460 @defvar FCFLAGS
2461 @ovindex FCFLAGS
2462 Debugging and optimization options for the Fortran compiler.  If it
2463 is not set in the environment when @command{configure} runs, the default
2464 value is set when you call @code{AC_PROG_FC} (or empty if you don't).
2465 @command{configure} uses this variable when compiling or linking
2466 programs to test for Fortran features.
2467 @end defvar
2469 @defvar FFLAGS
2470 @ovindex FFLAGS
2471 Debugging and optimization options for the Fortran 77 compiler.  If it
2472 is not set in the environment when @command{configure} runs, the default
2473 value is set when you call @code{AC_PROG_F77} (or empty if you don't).
2474 @command{configure} uses this variable when compiling or linking
2475 programs to test for Fortran 77 features.
2476 @end defvar
2478 @defvar LDFLAGS
2479 @ovindex LDFLAGS
2480 Options for the linker.  If it is not set
2481 in the environment when @command{configure} runs, the default value is empty.
2482 @command{configure} uses this variable when linking programs to test for
2483 C, C++, Objective C, and Fortran features.
2485 This variable's contents should contain options like @option{-s} and
2486 @option{-L} that affect only the behavior of the linker.  Please see the
2487 explanation of @code{CFLAGS} for what you can do if an option also
2488 affects other phases of the compiler.
2490 Don't use this variable to pass library names
2491 (@option{-l}) to the linker; use @code{LIBS} instead.
2492 @end defvar
2494 @defvar LIBS
2495 @ovindex LIBS
2496 @option{-l} options to pass to the linker.  The default value is empty,
2497 but some Autoconf macros may prepend extra libraries to this variable if
2498 those libraries are found and provide necessary functions, see
2499 @ref{Libraries}.  @command{configure} uses this variable when linking
2500 programs to test for C, C++, and Fortran features.
2501 @end defvar
2503 @defvar OBJCFLAGS
2504 @ovindex OBJCFLAGS
2505 Debugging and optimization options for the Objective C compiler.  It
2506 acts like @code{CFLAGS}, but for Objective C instead of C.
2507 @end defvar
2509 @defvar builddir
2510 @ovindex builddir
2511 Rigorously equal to @samp{.}.  Added for symmetry only.
2512 @end defvar
2514 @defvar abs_builddir
2515 @ovindex abs_builddir
2516 Absolute name of @code{builddir}.
2517 @end defvar
2519 @defvar top_builddir
2520 @ovindex top_builddir
2521 The relative name of the top level of the current build tree.  In the
2522 top-level directory, this is the same as @code{builddir}.
2523 @end defvar
2525 @defvar top_build_prefix
2526 @ovindex top_build_prefix
2527 The relative name of the top level of the current build tree with final
2528 slash if nonemtpy.  This is the same as @code{top_builddir}, except that
2529 it contains zero or more runs of @code{../}, so it should not be
2530 appended with a slash for concatenation.  This helps for @command{make}
2531 implementations that otherwise do not treat @file{./file} and @file{file}
2532 as equal in the toplevel build directory.
2533 @end defvar
2535 @defvar abs_top_builddir
2536 @ovindex abs_top_builddir
2537 Absolute name of @code{top_builddir}.
2538 @end defvar
2540 @defvar srcdir
2541 @ovindex srcdir
2542 The name of the directory that contains the source code for
2543 that makefile.
2544 @end defvar
2546 @defvar abs_srcdir
2547 @ovindex abs_srcdir
2548 Absolute name of @code{srcdir}.
2549 @end defvar
2551 @defvar top_srcdir
2552 @ovindex top_srcdir
2553 The name of the top-level source code directory for the
2554 package.  In the top-level directory, this is the same as @code{srcdir}.
2555 @end defvar
2557 @defvar abs_top_srcdir
2558 @ovindex abs_top_srcdir
2559 Absolute name of @code{top_srcdir}.
2560 @end defvar
2562 @node Installation Directory Variables
2563 @subsection Installation Directory Variables
2564 @cindex Installation directories
2565 @cindex Directories, installation
2567 The following variables specify the directories for
2568 package installation, see @ref{Directory Variables, , Variables for
2569 Installation Directories, standards, The @acronym{GNU} Coding
2570 Standards}, for more information.  Each variable corresponds to an
2571 argument of @command{configure}; trailing slashes are stripped so that
2572 expressions such as @samp{$@{prefix@}/lib} expand with only one slash
2573 between directory names.  See the end of this section for
2574 details on when and how to use these variables.
2576 @defvar bindir
2577 @ovindex bindir
2578 The directory for installing executables that users run.
2579 @end defvar
2581 @defvar datadir
2582 @ovindex datadir
2583 The directory for installing idiosyncratic read-only
2584 architecture-independent data.
2585 @end defvar
2587 @defvar datarootdir
2588 @ovindex datarootdir
2589 The root of the directory tree for read-only architecture-independent
2590 data files.
2591 @end defvar
2593 @defvar docdir
2594 @ovindex docdir
2595 The directory for installing documentation files (other than Info and
2596 man).
2597 @end defvar
2599 @defvar dvidir
2600 @ovindex dvidir
2601 The directory for installing documentation files in DVI format.
2602 @end defvar
2604 @defvar exec_prefix
2605 @ovindex exec_prefix
2606 The installation prefix for architecture-dependent files.  By default
2607 it's the same as @var{prefix}.  You should avoid installing anything
2608 directly to @var{exec_prefix}.  However, the default value for
2609 directories containing architecture-dependent files should be relative
2610 to @var{exec_prefix}.
2611 @end defvar
2613 @defvar htmldir
2614 @ovindex htmldir
2615 The directory for installing HTML documentation.
2616 @end defvar
2618 @defvar includedir
2619 @ovindex includedir
2620 The directory for installing C header files.
2621 @end defvar
2623 @defvar infodir
2624 @ovindex infodir
2625 The directory for installing documentation in Info format.
2626 @end defvar
2628 @defvar libdir
2629 @ovindex libdir
2630 The directory for installing object code libraries.
2631 @end defvar
2633 @defvar libexecdir
2634 @ovindex libexecdir
2635 The directory for installing executables that other programs run.
2636 @end defvar
2638 @defvar localedir
2639 @ovindex localedir
2640 The directory for installing locale-dependent but
2641 architecture-independent data, such as message catalogs.  This directory
2642 usually has a subdirectory per locale.
2643 @end defvar
2645 @defvar localstatedir
2646 @ovindex localstatedir
2647 The directory for installing modifiable single-machine data.
2648 @end defvar
2650 @defvar mandir
2651 @ovindex mandir
2652 The top-level directory for installing documentation in man format.
2653 @end defvar
2655 @defvar oldincludedir
2656 @ovindex oldincludedir
2657 The directory for installing C header files for non-@acronym{GCC} compilers.
2658 @end defvar
2660 @defvar pdfdir
2661 @ovindex pdfdir
2662 The directory for installing PDF documentation.
2663 @end defvar
2665 @defvar prefix
2666 @ovindex prefix
2667 The common installation prefix for all files.  If @var{exec_prefix}
2668 is defined to a different value, @var{prefix} is used only for
2669 architecture-independent files.
2670 @end defvar
2672 @defvar psdir
2673 @ovindex psdir
2674 The directory for installing PostScript documentation.
2675 @end defvar
2677 @defvar sbindir
2678 @ovindex sbindir
2679 The directory for installing executables that system
2680 administrators run.
2681 @end defvar
2683 @defvar sharedstatedir
2684 @ovindex sharedstatedir
2685 The directory for installing modifiable architecture-independent data.
2686 @end defvar
2688 @defvar sysconfdir
2689 @ovindex sysconfdir
2690 The directory for installing read-only single-machine data.
2691 @end defvar
2694 Most of these variables have values that rely on @code{prefix} or
2695 @code{exec_prefix}.  It is deliberate that the directory output
2696 variables keep them unexpanded: typically @samp{@@datarootdir@@} is
2697 replaced by @samp{$@{prefix@}/share}, not @samp{/usr/local/share}, and
2698 @samp{@@datadir@@} is replaced by @samp{$@{datarootdir@}}.
2700 This behavior is mandated by the @acronym{GNU} coding standards, so that when
2701 the user runs:
2703 @table @samp
2704 @item make
2705 she can still specify a different prefix from the one specified to
2706 @command{configure}, in which case, if needed, the package should hard
2707 code dependencies corresponding to the make-specified prefix.
2709 @item make install
2710 she can specify a different installation location, in which case the
2711 package @emph{must} still depend on the location which was compiled in
2712 (i.e., never recompile when @samp{make install} is run).  This is an
2713 extremely important feature, as many people may decide to install all
2714 the files of a package grouped together, and then install links from
2715 the final locations to there.
2716 @end table
2718 In order to support these features, it is essential that
2719 @code{datarootdir} remains defined as @samp{$@{prefix@}/share},
2720 so that its value can be expanded based
2721 on the current value of @code{prefix}.
2723 A corollary is that you should not use these variables except in
2724 makefiles.  For instance, instead of trying to evaluate @code{datadir}
2725 in @file{configure} and hard-coding it in makefiles using
2726 e.g., @samp{AC_DEFINE_UNQUOTED([DATADIR], ["$datadir"], [Data directory.])},
2727 you should add
2728 @option{-DDATADIR='$(datadir)'} to your makefile's definition of
2729 @code{CPPFLAGS} (@code{AM_CPPFLAGS} if you are also using Automake).
2731 Similarly, you should not rely on @code{AC_CONFIG_FILES} to replace
2732 @code{bindir} and friends in your shell scripts and other files; instead,
2733 let @command{make} manage their replacement.  For instance Autoconf
2734 ships templates of its shell scripts ending with @samp{.in}, and uses a
2735 makefile snippet similar to the following to build scripts like
2736 @command{autoheader} and @command{autom4te}:
2738 @example
2739 @group
2740 edit = sed \
2741         -e 's|@@bindir[@@]|$(bindir)|g' \
2742         -e 's|@@pkgdatadir[@@]|$(pkgdatadir)|g' \
2743         -e 's|@@prefix[@@]|$(prefix)|g'
2744 @end group
2746 @group
2747 autoheader autom4te: Makefile
2748         rm -f $@@ $@@.tmp
2749         srcdir=''; \
2750           test -f ./$@@.in || srcdir=$(srcdir)/; \
2751           $(edit) $$@{srcdir@}$@@.in >$@@.tmp
2752         chmod +x $@@.tmp
2753         chmod a-w $@@.tmp
2754         mv $@@.tmp $@@
2755 @end group
2757 @group
2758 autoheader: $(srcdir)/autoheader.in
2759 autom4te: $(srcdir)/autom4te.in
2760 @end group
2761 @end example
2763 Some details are noteworthy:
2765 @table @asis
2766 @item @samp{@@bindir[@@]}
2767 The brackets prevent @command{configure} from replacing
2768 @samp{@@bindir@@} in the Sed expression itself.
2769 Brackets are preferable to a backslash here, since
2770 Posix says @samp{\@@} is not portable.
2772 @item @samp{$(bindir)}
2773 Don't use @samp{@@bindir@@}!  Use the matching makefile variable
2774 instead.
2776 @item @samp{$(pkgdatadir)}
2777 The example takes advantage of the variable @samp{$(pkgdatadir)}
2778 provided by Automake; it is equivalent to @samp{$(datadir)/$(PACKAGE)}.
2780 @item @samp{/}
2781 Don't use @samp{/} in the Sed expressions that replace file names since
2782 most likely the
2783 variables you use, such as @samp{$(bindir)}, contain @samp{/}.
2784 Use a shell metacharacter instead, such as @samp{|}.
2786 @item special characters
2787 File names, file name components, and the value of @code{VPATH} should
2788 not contain shell metacharacters or white
2789 space.  @xref{Special Chars in Variables}.
2791 @item dependency on @file{Makefile}
2792 Since @code{edit} uses values that depend on the configuration specific
2793 values (@code{prefix}, etc.)@: and not only on @code{VERSION} and so forth,
2794 the output depends on @file{Makefile}, not @file{configure.ac}.
2796 @item @samp{$@@}
2797 The main rule is generic, and uses @samp{$@@} extensively to
2798 avoid the need for multiple copies of the rule.
2800 @item Separated dependencies and single suffix rules
2801 You can't use them!  The above snippet cannot be (portably) rewritten
2804 @example
2805 autoconf autoheader: Makefile
2806 @group
2807 .in:
2808         rm -f $@@ $@@.tmp
2809         $(edit) $< >$@@.tmp
2810         chmod +x $@@.tmp
2811         mv $@@.tmp $@@
2812 @end group
2813 @end example
2815 @xref{Single Suffix Rules}, for details.
2817 @item @samp{$(srcdir)}
2818 Be sure to specify the name of the source directory,
2819 otherwise the package won't support separated builds.
2820 @end table
2822 For the more specific installation of Erlang libraries, the following variables
2823 are defined:
2825 @defvar ERLANG_INSTALL_LIB_DIR
2826 @ovindex ERLANG_INSTALL_LIB_DIR
2827 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
2828 The common parent directory of Erlang library installation directories.
2829 This variable is set by calling the @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR}
2830 macro in @file{configure.ac}.
2831 @end defvar
2833 @defvar ERLANG_INSTALL_LIB_DIR_@var{library}
2834 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
2835 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2836 The installation directory for Erlang library @var{library}.
2837 This variable is set by using the
2838 @samp{AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR}
2839 macro in @file{configure.ac}.
2840 @end defvar
2842 @xref{Erlang Libraries}, for details.
2845 @node Changed Directory Variables
2846 @subsection Changed Directory Variables
2847 @cindex @file{datarootdir}
2849 In Autoconf 2.60, the set of directory variables has changed, and the
2850 defaults of some variables have been adjusted
2851 (@pxref{Installation Directory Variables}) to changes in the
2852 @acronym{GNU} Coding Standards.  Notably, @file{datadir}, @file{infodir}, and
2853 @file{mandir} are now expressed in terms of @file{datarootdir}.  If you are
2854 upgrading from an earlier Autoconf version, you may need to adjust your files
2855 to ensure that the directory variables are substituted correctly
2856 (@pxref{Defining Directories}), and that a definition of @file{datarootdir} is
2857 in place.  For example, in a @file{Makefile.in}, adding
2859 @example
2860 datarootdir = @@datarootdir@@
2861 @end example
2863 @noindent
2864 is usually sufficient.  If you use Automake to create @file{Makefile.in},
2865 it will add this for you.
2867 To help with the transition, Autoconf warns about files that seem to use
2868 @code{datarootdir} without defining it.  In some cases, it then expands
2869 the value of @code{$datarootdir} in substitutions of the directory
2870 variables.  The following example shows such a warning:
2872 @example
2873 $ @kbd{cat configure.ac}
2874 AC_INIT
2875 AC_CONFIG_FILES([Makefile])
2876 AC_OUTPUT
2877 $ @kbd{cat Makefile.in}
2878 prefix = @@prefix@@
2879 datadir = @@datadir@@
2880 $ @kbd{autoconf}
2881 $ @kbd{configure}
2882 configure: creating ./config.status
2883 config.status: creating Makefile
2884 config.status: WARNING:
2885                Makefile.in seems to ignore the --datarootdir setting
2886 $ @kbd{cat Makefile}
2887 prefix = /usr/local
2888 datadir = $@{prefix@}/share
2889 @end example
2891 Usually one can easily change the file to accommodate both older and newer
2892 Autoconf releases:
2894 @example
2895 $ @kbd{cat Makefile.in}
2896 prefix = @@prefix@@
2897 datarootdir = @@datarootdir@@
2898 datadir = @@datadir@@
2899 $ @kbd{configure}
2900 configure: creating ./config.status
2901 config.status: creating Makefile
2902 $ @kbd{cat Makefile}
2903 prefix = /usr/local
2904 datarootdir = $@{prefix@}/share
2905 datadir = $@{datarootdir@}
2906 @end example
2908 @acindex{DATAROOTDIR_CHECKED}
2909 In some cases, however, the checks may not be able to detect that a suitable
2910 initialization of @code{datarootdir} is in place, or they may fail to detect
2911 that such an initialization is necessary in the output file.  If, after
2912 auditing your package, there are still spurious @file{configure} warnings about
2913 @code{datarootdir}, you may add the line
2915 @example
2916 AC_DEFUN([AC_DATAROOTDIR_CHECKED])
2917 @end example
2919 @noindent
2920 to your @file{configure.ac} to disable the warnings.  This is an exception
2921 to the usual rule that you should not define a macro whose name begins with
2922 @code{AC_} (@pxref{Macro Names}).
2926 @node Build Directories
2927 @subsection Build Directories
2928 @cindex Build directories
2929 @cindex Directories, build
2931 You can support compiling a software package for several architectures
2932 simultaneously from the same copy of the source code.  The object files
2933 for each architecture are kept in their own directory.
2935 To support doing this, @command{make} uses the @code{VPATH} variable to
2936 find the files that are in the source directory.  @acronym{GNU} Make
2937 can do this.  Most other recent @command{make} programs can do this as
2938 well, though they may have difficulties and it is often simpler to
2939 recommend @acronym{GNU} @command{make} (@pxref{VPATH and Make}).  Older
2940 @command{make} programs do not support @code{VPATH}; when using them, the
2941 source code must be in the same directory as the object files.
2943 If you are using @acronym{GNU} Automake, the remaining details in this
2944 section are already covered for you, based on the contents of your
2945 @file{Makefile.am}.  But if you are using Autoconf in isolation, then
2946 supporting @code{VPATH} requires the following in your
2947 @file{Makefile.in}:
2949 @example
2950 srcdir = @@srcdir@@
2951 VPATH = @@srcdir@@
2952 @end example
2954 Do not set @code{VPATH} to the value of another variable, for example
2955 @samp{VPATH = $(srcdir)}, because some versions of @command{make} do not do
2956 variable substitutions on the value of @code{VPATH}.
2958 @command{configure} substitutes the correct value for @code{srcdir} when
2959 it produces @file{Makefile}.
2961 Do not use the @command{make} variable @code{$<}, which expands to the
2962 file name of the file in the source directory (found with @code{VPATH}),
2963 except in implicit rules.  (An implicit rule is one such as @samp{.c.o},
2964 which tells how to create a @file{.o} file from a @file{.c} file.)  Some
2965 versions of @command{make} do not set @code{$<} in explicit rules; they
2966 expand it to an empty value.
2968 Instead, Make command lines should always refer to source
2969 files by prefixing them with @samp{$(srcdir)/}.  For example:
2971 @example
2972 time.info: time.texinfo
2973         $(MAKEINFO) '$(srcdir)/time.texinfo'
2974 @end example
2976 @node Automatic Remaking
2977 @subsection Automatic Remaking
2978 @cindex Automatic remaking
2979 @cindex Remaking automatically
2981 You can put rules like the following in the top-level @file{Makefile.in}
2982 for a package to automatically update the configuration information when
2983 you change the configuration files.  This example includes all of the
2984 optional files, such as @file{aclocal.m4} and those related to
2985 configuration header files.  Omit from the @file{Makefile.in} rules for
2986 any of these files that your package does not use.
2988 The @samp{$(srcdir)/} prefix is included because of limitations in the
2989 @code{VPATH} mechanism.
2991 The @file{stamp-} files are necessary because the timestamps of
2992 @file{config.h.in} and @file{config.h} are not changed if remaking
2993 them does not change their contents.  This feature avoids unnecessary
2994 recompilation.  You should include the file @file{stamp-h.in} in your
2995 package's distribution, so that @command{make} considers
2996 @file{config.h.in} up to date.  Don't use @command{touch}
2997 (@pxref{touch, , Limitations of Usual Tools}); instead, use
2998 @command{echo} (using
2999 @command{date} would cause needless differences, hence @acronym{CVS}
3000 conflicts, etc.).
3002 @example
3003 @group
3004 $(srcdir)/configure: configure.ac aclocal.m4
3005         cd '$(srcdir)' && autoconf
3007 # autoheader might not change config.h.in, so touch a stamp file.
3008 $(srcdir)/config.h.in: stamp-h.in
3009 $(srcdir)/stamp-h.in: configure.ac aclocal.m4
3010         cd '$(srcdir)' && autoheader
3011         echo timestamp > '$(srcdir)/stamp-h.in'
3013 config.h: stamp-h
3014 stamp-h: config.h.in config.status
3015         ./config.status
3017 Makefile: Makefile.in config.status
3018         ./config.status
3020 config.status: configure
3021         ./config.status --recheck
3022 @end group
3023 @end example
3025 @noindent
3026 (Be careful if you copy these lines directly into your makefile, as you
3027 need to convert the indented lines to start with the tab character.)
3029 In addition, you should use
3031 @example
3032 AC_CONFIG_FILES([stamp-h], [echo timestamp > stamp-h])
3033 @end example
3035 @noindent
3036 so @file{config.status} ensures that @file{config.h} is considered up to
3037 date.  @xref{Output}, for more information about @code{AC_OUTPUT}.
3039 @xref{config.status Invocation}, for more examples of handling
3040 configuration-related dependencies.
3042 @node Configuration Headers
3043 @section Configuration Header Files
3044 @cindex Configuration Header
3045 @cindex @file{config.h}
3047 When a package contains more than a few tests that define C preprocessor
3048 symbols, the command lines to pass @option{-D} options to the compiler
3049 can get quite long.  This causes two problems.  One is that the
3050 @command{make} output is hard to visually scan for errors.  More
3051 seriously, the command lines can exceed the length limits of some
3052 operating systems.  As an alternative to passing @option{-D} options to
3053 the compiler, @command{configure} scripts can create a C header file
3054 containing @samp{#define} directives.  The @code{AC_CONFIG_HEADERS}
3055 macro selects this kind of output.  Though it can be called anywhere
3056 between @code{AC_INIT} and @code{AC_OUTPUT}, it is customary to call
3057 it right after @code{AC_INIT}.
3059 The package should @samp{#include} the configuration header file before
3060 any other header files, to prevent inconsistencies in declarations (for
3061 example, if it redefines @code{const}).
3063 To provide for VPATH builds, remember to pass the C compiler a @option{-I.}
3064 option (or @option{-I..}; whichever directory contains @file{config.h}).
3065 Even if you use @samp{#include "config.h"}, the preprocessor searches only
3066 the directory of the currently read file, i.e., the source directory, not
3067 the build directory.
3069 With the appropriate @option{-I} option, you can use
3070 @samp{#include <config.h>}.  Actually, it's a good habit to use it,
3071 because in the rare case when the source directory contains another
3072 @file{config.h}, the build directory should be searched first.
3075 @defmac AC_CONFIG_HEADERS (@var{header} @dots{}, @ovar{cmds}, @ovar{init-cmds})
3076 @acindex{CONFIG_HEADERS}
3077 @cvindex HAVE_CONFIG_H
3078 This macro is one of the instantiating macros; see @ref{Configuration
3079 Actions}.  Make @code{AC_OUTPUT} create the file(s) in the
3080 blank-or-newline-separated list @var{header} containing C preprocessor
3081 @code{#define} statements, and replace @samp{@@DEFS@@} in generated
3082 files with @option{-DHAVE_CONFIG_H} instead of the value of @code{DEFS}.
3083 The usual name for @var{header} is @file{config.h}.
3085 If @var{header} already exists and its contents are identical to what
3086 @code{AC_OUTPUT} would put in it, it is left alone.  Doing this allows
3087 making some changes in the configuration without needlessly causing
3088 object files that depend on the header file to be recompiled.
3090 Usually the input file is named @file{@var{header}.in}; however, you can
3091 override the input file name by appending to @var{header} a
3092 colon-separated list of input files.  For example, you might need to make
3093 the input file name acceptable to @acronym{DOS} variants:
3095 @example
3096 AC_CONFIG_HEADERS([config.h:config.hin])
3097 @end example
3099 @end defmac
3101 @defmac AH_HEADER
3102 @ahindex{HEADER}
3103 This macro is defined as the name of the first declared config header
3104 and undefined if no config headers have been declared up to this point.
3105 A third-party macro may, for example, require use of a config header
3106 without invoking AC_CONFIG_HEADERS twice, like this:
3108 @example
3109 AC_CONFIG_COMMANDS_PRE(
3110         [m4_ifndef([AH_HEADER], [AC_CONFIG_HEADERS([config.h])])])
3111 @end example
3113 @end defmac
3115 @xref{Configuration Actions}, for more details on @var{header}.
3117 @menu
3118 * Header Templates::            Input for the configuration headers
3119 * autoheader Invocation::       How to create configuration templates
3120 * Autoheader Macros::           How to specify CPP templates
3121 @end menu
3123 @node Header Templates
3124 @subsection Configuration Header Templates
3125 @cindex Configuration Header Template
3126 @cindex Header templates
3127 @cindex @file{config.h.in}
3129 Your distribution should contain a template file that looks as you want
3130 the final header file to look, including comments, with @code{#undef}
3131 statements which are used as hooks.  For example, suppose your
3132 @file{configure.ac} makes these calls:
3134 @example
3135 AC_CONFIG_HEADERS([conf.h])
3136 AC_CHECK_HEADERS([unistd.h])
3137 @end example
3139 @noindent
3140 Then you could have code like the following in @file{conf.h.in}.
3141 The @file{conf.h} created by @command{configure} defines @samp{HAVE_UNISTD_H}
3142 to 1, if and only if the system has @file{unistd.h}.
3144 @example
3145 @group
3146 /* Define as 1 if you have unistd.h.  */
3147 #undef HAVE_UNISTD_H
3148 @end group
3149 @end example
3151 The format of the template file is stricter than what the C preprocessor
3152 is required to accept.  A directive line should contain only whitespace,
3153 @samp{#undef}, and @samp{HAVE_UNISTD_H}.  The use of @samp{#define}
3154 instead of @samp{#undef}, or of comments on the same line as
3155 @samp{#undef}, is strongly discouraged.  Each hook should only be listed
3156 once.  Other preprocessor lines, such as @samp{#ifdef} or
3157 @samp{#include}, are copied verbatim from the template into the
3158 generated header.
3160 Since it is a tedious task to keep a template header up to date, you may
3161 use @command{autoheader} to generate it, see @ref{autoheader Invocation}.
3163 During the instantiation of the header, each @samp{#undef} line in the
3164 template file for each symbol defined by @samp{AC_DEFINE} is changed to an
3165 appropriate @samp{#define}. If the corresponding @samp{AC_DEFINE} has not
3166 been executed during the @command{configure} run, the @samp{#undef} line is
3167 commented out.  (This is important, e.g., for @samp{_POSIX_SOURCE}:
3168 on many systems, it can be implicitly defined by the compiler, and
3169 undefining it in the header would then break compilation of subsequent
3170 headers.)
3172 Currently, @emph{all} remaining @samp{#undef} lines in the header
3173 template are commented out, whether or not there was a corresponding
3174 @samp{AC_DEFINE} for the macro name; but this behavior is not guaranteed
3175 for future releases of Autoconf.
3177 Generally speaking, since you should not use @samp{#define}, and you
3178 cannot guarantee whether a @samp{#undef} directive in the header
3179 template will be converted to a @samp{#define} or commented out in the
3180 generated header file, the template file cannot be used for conditional
3181 definition effects.  Consequently, if you need to use the construct
3183 @example
3184 @group
3185 #ifdef THIS
3186 # define THAT
3187 #endif
3188 @end group
3189 @end example
3191 @noindent
3192 you must place it outside of the template.
3193 If you absolutely need to hook it to the config header itself, please put
3194 the directives to a separate file, and @samp{#include} that file from the
3195 config header template.  If you are using @command{autoheader}, you would
3196 probably use @samp{AH_BOTTOM} to append the @samp{#include} directive.
3199 @node autoheader Invocation
3200 @subsection Using @command{autoheader} to Create @file{config.h.in}
3201 @cindex @command{autoheader}
3203 The @command{autoheader} program can create a template file of C
3204 @samp{#define} statements for @command{configure} to use.
3205 It searches for the first invocation of @code{AC_CONFIG_HEADERS} in
3206 @file{configure} sources to determine the name of the template.
3207 (If the first call of @code{AC_CONFIG_HEADERS} specifies more than one
3208 input file name, @command{autoheader} uses the first one.)
3210 It is recommended that only one input file is used.  If you want to append
3211 a boilerplate code, it is preferable to use
3212 @samp{AH_BOTTOM([#include <conf_post.h>])}.
3213 File @file{conf_post.h} is not processed during the configuration then,
3214 which make things clearer.  Analogically, @code{AH_TOP} can be used to
3215 prepend a boilerplate code.
3217 In order to do its job, @command{autoheader} needs you to document all
3218 of the symbols that you might use.  Typically this is done via an
3219 @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED} call whose first argument
3220 is a literal symbol and whose third argument describes the symbol
3221 (@pxref{Defining Symbols}).  Alternatively, you can use
3222 @code{AH_TEMPLATE} (@pxref{Autoheader Macros}), or you can supply a
3223 suitable input file for a subsequent configuration header file.
3224 Symbols defined by Autoconf's builtin tests are already documented properly;
3225 you need to document only those that you
3226 define yourself.
3228 You might wonder why @command{autoheader} is needed: after all, why
3229 would @command{configure} need to ``patch'' a @file{config.h.in} to
3230 produce a @file{config.h} instead of just creating @file{config.h} from
3231 scratch?  Well, when everything rocks, the answer is just that we are
3232 wasting our time maintaining @command{autoheader}: generating
3233 @file{config.h} directly is all that is needed.  When things go wrong,
3234 however, you'll be thankful for the existence of @command{autoheader}.
3236 The fact that the symbols are documented is important in order to
3237 @emph{check} that @file{config.h} makes sense.  The fact that there is a
3238 well-defined list of symbols that should be defined (or not) is
3239 also important for people who are porting packages to environments where
3240 @command{configure} cannot be run: they just have to @emph{fill in the
3241 blanks}.
3243 But let's come back to the point: the invocation of @command{autoheader}@dots{}
3245 If you give @command{autoheader} an argument, it uses that file instead
3246 of @file{configure.ac} and writes the header file to the standard output
3247 instead of to @file{config.h.in}.  If you give @command{autoheader} an
3248 argument of @option{-}, it reads the standard input instead of
3249 @file{configure.ac} and writes the header file to the standard output.
3251 @command{autoheader} accepts the following options:
3253 @table @option
3254 @item --help
3255 @itemx -h
3256 Print a summary of the command line options and exit.
3258 @item --version
3259 @itemx -V
3260 Print the version number of Autoconf and exit.
3262 @item --verbose
3263 @itemx -v
3264 Report processing steps.
3266 @item --debug
3267 @itemx -d
3268 Don't remove the temporary files.
3270 @item --force
3271 @itemx -f
3272 Remake the template file even if newer than its input files.
3274 @item --include=@var{dir}
3275 @itemx -I @var{dir}
3276 Append @var{dir} to the include path.  Multiple invocations accumulate.
3278 @item --prepend-include=@var{dir}
3279 @itemx -B @var{dir}
3280 Prepend @var{dir} to the include path.  Multiple invocations accumulate.
3282 @item --warnings=@var{category}
3283 @itemx -W @var{category}
3284 @evindex WARNINGS
3285 Report the warnings related to @var{category} (which can actually be a
3286 comma separated list).  Current categories include:
3288 @table @samp
3289 @item obsolete
3290 report the uses of obsolete constructs
3292 @item all
3293 report all the warnings
3295 @item none
3296 report none
3298 @item error
3299 treats warnings as errors
3301 @item no-@var{category}
3302 disable warnings falling into @var{category}
3303 @end table
3305 @end table
3309 @node Autoheader Macros
3310 @subsection Autoheader Macros
3311 @cindex Autoheader macros
3313 @command{autoheader} scans @file{configure.ac} and figures out which C
3314 preprocessor symbols it might define.  It knows how to generate
3315 templates for symbols defined by @code{AC_CHECK_HEADERS},
3316 @code{AC_CHECK_FUNCS} etc., but if you @code{AC_DEFINE} any additional
3317 symbol, you must define a template for it.  If there are missing
3318 templates, @command{autoheader} fails with an error message.
3320 The template for a @var{symbol} is created
3321 by @command{autoheader} from
3322 the @var{description} argument to an @code{AC_DEFINE};
3323 see @ref{Defining Symbols}.
3325 For special needs, you can use the following macros.
3328 @defmac AH_TEMPLATE (@var{key}, @var{description})
3329 @ahindex{TEMPLATE}
3330 Tell @command{autoheader} to generate a template for @var{key}.  This macro
3331 generates standard templates just like @code{AC_DEFINE} when a
3332 @var{description} is given.
3334 For example:
3336 @example
3337 AH_TEMPLATE([CRAY_STACKSEG_END],
3338             [Define to one of _getb67, GETB67, getb67
3339              for Cray-2 and Cray-YMP systems.  This
3340              function is required for alloca.c support
3341              on those systems.])
3342 @end example
3344 @noindent
3345 generates the following template, with the description properly
3346 justified.
3348 @example
3349 /* Define to one of _getb67, GETB67, getb67 for Cray-2 and
3350    Cray-YMP systems.  This function is required for alloca.c
3351    support on those systems.  */
3352 #undef CRAY_STACKSEG_END
3353 @end example
3354 @end defmac
3357 @defmac AH_VERBATIM (@var{key}, @var{template})
3358 @ahindex{VERBATIM}
3359 Tell @command{autoheader} to include the @var{template} as-is in the header
3360 template file.  This @var{template} is associated with the @var{key},
3361 which is used to sort all the different templates and guarantee their
3362 uniqueness.  It should be a symbol that can be defined via @code{AC_DEFINE}.
3363 @end defmac
3366 @defmac AH_TOP (@var{text})
3367 @ahindex{TOP}
3368 Include @var{text} at the top of the header template file.
3369 @end defmac
3372 @defmac AH_BOTTOM (@var{text})
3373 @ahindex{BOTTOM}
3374 Include @var{text} at the bottom of the header template file.
3375 @end defmac
3378 Please note that @var{text} gets included ``verbatim'' to the template file,
3379 not to the resulting config header, so it can easily get mangled when the
3380 template is processed.  There is rarely a need for something other than
3382 @example
3383 AH_BOTTOM([#include <custom.h>])
3384 @end example
3388 @node Configuration Commands
3389 @section Running Arbitrary Configuration Commands
3390 @cindex Configuration commands
3391 @cindex Commands for configuration
3393 You can execute arbitrary commands before, during, and after
3394 @file{config.status} is run.  The three following macros accumulate the
3395 commands to run when they are called multiple times.
3396 @code{AC_CONFIG_COMMANDS} replaces the obsolete macro
3397 @code{AC_OUTPUT_COMMANDS}; see @ref{Obsolete Macros}, for details.
3399 @anchor{AC_CONFIG_COMMANDS}
3400 @defmac AC_CONFIG_COMMANDS (@var{tag}@dots{}, @ovar{cmds}, @ovar{init-cmds})
3401 @acindex{CONFIG_COMMANDS}
3402 Specify additional shell commands to run at the end of
3403 @file{config.status}, and shell commands to initialize any variables
3404 from @command{configure}.  Associate the commands with @var{tag}.
3405 Since typically the @var{cmds} create a file, @var{tag} should
3406 naturally be the name of that file.  If needed, the directory hosting
3407 @var{tag} is created.  This macro is one of the instantiating macros;
3408 see @ref{Configuration Actions}.
3410 Here is an unrealistic example:
3411 @example
3412 fubar=42
3413 AC_CONFIG_COMMANDS([fubar],
3414                    [echo this is extra $fubar, and so on.],
3415                    [fubar=$fubar])
3416 @end example
3418 Here is a better one:
3419 @example
3420 AC_CONFIG_COMMANDS([timestamp], [date >timestamp])
3421 @end example
3422 @end defmac
3424 The following two macros look similar, but in fact they are not of the same
3425 breed: they are executed directly by @file{configure}, so you cannot use
3426 @file{config.status} to rerun them.
3428 @c Yet it is good to leave them here.  The user sees them together and
3429 @c decides which best fits their needs.
3431 @defmac AC_CONFIG_COMMANDS_PRE (@var{cmds})
3432 @acindex{CONFIG_COMMANDS_PRE}
3433 Execute the @var{cmds} right before creating @file{config.status}.
3435 This macro presents the last opportunity to call @code{AC_SUBST},
3436 @code{AC_DEFINE}, or @code{AC_CONFIG_FOOS} macros.
3437 @end defmac
3439 @defmac AC_CONFIG_COMMANDS_POST (@var{cmds})
3440 @acindex{CONFIG_COMMANDS_POST}
3441 Execute the @var{cmds} right after creating @file{config.status}.
3442 @end defmac
3447 @node Configuration Links
3448 @section Creating Configuration Links
3449 @cindex Configuration links
3450 @cindex Links for configuration
3452 You may find it convenient to create links whose destinations depend upon
3453 results of tests.  One can use @code{AC_CONFIG_COMMANDS} but the
3454 creation of relative symbolic links can be delicate when the package is
3455 built in a directory different from the source directory.
3457 @anchor{AC_CONFIG_LINKS}
3458 @defmac AC_CONFIG_LINKS (@var{dest}:@var{source}@dots{}, @ovar{cmds}, @
3459   @ovar{init-cmds})
3460 @acindex{CONFIG_LINKS}
3461 @cindex Links
3462 Make @code{AC_OUTPUT} link each of the existing files @var{source} to
3463 the corresponding link name @var{dest}.  Makes a symbolic link if
3464 possible, otherwise a hard link if possible, otherwise a copy.  The
3465 @var{dest} and @var{source} names should be relative to the top level
3466 source or build directory.  This macro is one of the instantiating
3467 macros; see @ref{Configuration Actions}.
3469 For example, this call:
3471 @example
3472 AC_CONFIG_LINKS([host.h:config/$machine.h
3473                 object.h:config/$obj_format.h])
3474 @end example
3476 @noindent
3477 creates in the current directory @file{host.h} as a link to
3478 @file{@var{srcdir}/config/$machine.h}, and @file{object.h} as a
3479 link to @file{@var{srcdir}/config/$obj_format.h}.
3481 The tempting value @samp{.} for @var{dest} is invalid: it makes it
3482 impossible for @samp{config.status} to guess the links to establish.
3484 One can then run:
3485 @example
3486 ./config.status host.h object.h
3487 @end example
3488 @noindent
3489 to create the links.
3490 @end defmac
3494 @node Subdirectories
3495 @section Configuring Other Packages in Subdirectories
3496 @cindex Configure subdirectories
3497 @cindex Subdirectory configure
3499 In most situations, calling @code{AC_OUTPUT} is sufficient to produce
3500 makefiles in subdirectories.  However, @command{configure} scripts
3501 that control more than one independent package can use
3502 @code{AC_CONFIG_SUBDIRS} to run @command{configure} scripts for other
3503 packages in subdirectories.
3505 @defmac AC_CONFIG_SUBDIRS (@var{dir} @dots{})
3506 @acindex{CONFIG_SUBDIRS}
3507 @ovindex subdirs
3508 Make @code{AC_OUTPUT} run @command{configure} in each subdirectory
3509 @var{dir} in the given blank-or-newline-separated list.  Each @var{dir} should
3510 be a literal, i.e., please do not use:
3512 @example
3513 if test "$package_foo_enabled" = yes; then
3514   $my_subdirs="$my_subdirs foo"
3516 AC_CONFIG_SUBDIRS([$my_subdirs])
3517 @end example
3519 @noindent
3520 because this prevents @samp{./configure --help=recursive} from
3521 displaying the options of the package @code{foo}.  Instead, you should
3522 write:
3524 @example
3525 if test "$package_foo_enabled" = yes; then
3526   AC_CONFIG_SUBDIRS([foo])
3528 @end example
3530 If a given @var{dir} is not found, an error is reported: if the
3531 subdirectory is optional, write:
3533 @example
3534 if test -d "$srcdir/foo"; then
3535   AC_CONFIG_SUBDIRS([foo])
3537 @end example
3539 @c NB: Yes, below we mean configure.in, not configure.ac.
3540 If a given @var{dir} contains @command{configure.gnu}, it is run instead
3541 of @command{configure}.  This is for packages that might use a
3542 non-Autoconf script @command{Configure}, which can't be called through a
3543 wrapper @command{configure} since it would be the same file on
3544 case-insensitive file systems.  Likewise, if a @var{dir} contains
3545 @file{configure.in} but no @command{configure}, the Cygnus
3546 @command{configure} script found by @code{AC_CONFIG_AUX_DIR} is used.
3548 The subdirectory @command{configure} scripts are given the same command
3549 line options that were given to this @command{configure} script, with minor
3550 changes if needed, which include:
3552 @itemize @minus
3553 @item
3554 adjusting a relative name for the cache file;
3556 @item
3557 adjusting a relative name for the source directory;
3559 @item
3560 propagating the current value of @code{$prefix}, including if it was
3561 defaulted, and if the default values of the top level and of the subdirectory
3562 @file{configure} differ.
3563 @end itemize
3565 This macro also sets the output variable @code{subdirs} to the list of
3566 directories @samp{@var{dir} @dots{}}.  Make rules can use
3567 this variable to determine which subdirectories to recurse into.
3569 This macro may be called multiple times.
3570 @end defmac
3572 @node Default Prefix
3573 @section Default Prefix
3574 @cindex Install prefix
3575 @cindex Prefix for install
3577 By default, @command{configure} sets the prefix for files it installs to
3578 @file{/usr/local}.  The user of @command{configure} can select a different
3579 prefix using the @option{--prefix} and @option{--exec-prefix} options.
3580 There are two ways to change the default: when creating
3581 @command{configure}, and when running it.
3583 Some software packages might want to install in a directory other than
3584 @file{/usr/local} by default.  To accomplish that, use the
3585 @code{AC_PREFIX_DEFAULT} macro.
3587 @defmac AC_PREFIX_DEFAULT (@var{prefix})
3588 @acindex{PREFIX_DEFAULT}
3589 Set the default installation prefix to @var{prefix} instead of
3590 @file{/usr/local}.
3591 @end defmac
3593 It may be convenient for users to have @command{configure} guess the
3594 installation prefix from the location of a related program that they
3595 have already installed.  If you wish to do that, you can call
3596 @code{AC_PREFIX_PROGRAM}.
3598 @anchor{AC_PREFIX_PROGRAM}
3599 @defmac AC_PREFIX_PROGRAM (@var{program})
3600 @acindex{PREFIX_PROGRAM}
3601 If the user did not specify an installation prefix (using the
3602 @option{--prefix} option), guess a value for it by looking for
3603 @var{program} in @env{PATH}, the way the shell does.  If @var{program}
3604 is found, set the prefix to the parent of the directory containing
3605 @var{program}, else default the prefix as described above
3606 (@file{/usr/local} or @code{AC_PREFIX_DEFAULT}).  For example, if
3607 @var{program} is @code{gcc} and the @env{PATH} contains
3608 @file{/usr/local/gnu/bin/gcc}, set the prefix to @file{/usr/local/gnu}.
3609 @end defmac
3613 @c ======================================================== Existing tests
3615 @node Existing Tests
3616 @chapter Existing Tests
3618 These macros test for particular system features that packages might
3619 need or want to use.  If you need to test for a kind of feature that
3620 none of these macros check for, you can probably do it by calling
3621 primitive test macros with appropriate arguments (@pxref{Writing
3622 Tests}).
3624 These tests print messages telling the user which feature they're
3625 checking for, and what they find.  They cache their results for future
3626 @command{configure} runs (@pxref{Caching Results}).
3628 Some of these macros set output variables.  @xref{Makefile
3629 Substitutions}, for how to get their values.  The phrase ``define
3630 @var{name}'' is used below as a shorthand to mean ``define the C
3631 preprocessor symbol @var{name} to the value 1''.  @xref{Defining
3632 Symbols}, for how to get those symbol definitions into your program.
3634 @menu
3635 * Common Behavior::             Macros' standard schemes
3636 * Alternative Programs::        Selecting between alternative programs
3637 * Files::                       Checking for the existence of files
3638 * Libraries::                   Library archives that might be missing
3639 * Library Functions::           C library functions that might be missing
3640 * Header Files::                Header files that might be missing
3641 * Declarations::                Declarations that may be missing
3642 * Structures::                  Structures or members that might be missing
3643 * Types::                       Types that might be missing
3644 * Compilers and Preprocessors::  Checking for compiling programs
3645 * System Services::             Operating system services
3646 * Posix Variants::              Special kludges for specific Posix variants
3647 * Erlang Libraries::            Checking for the existence of Erlang libraries
3648 @end menu
3650 @node Common Behavior
3651 @section Common Behavior
3652 @cindex Common autoconf behavior
3654 Much effort has been expended to make Autoconf easy to learn.  The most
3655 obvious way to reach this goal is simply to enforce standard interfaces
3656 and behaviors, avoiding exceptions as much as possible.  Because of
3657 history and inertia, unfortunately, there are still too many exceptions
3658 in Autoconf; nevertheless, this section describes some of the common
3659 rules.
3661 @menu
3662 * Standard Symbols::            Symbols defined by the macros
3663 * Default Includes::            Includes used by the generic macros
3664 @end menu
3666 @node Standard Symbols
3667 @subsection Standard Symbols
3668 @cindex Standard symbols
3670 All the generic macros that @code{AC_DEFINE} a symbol as a result of
3671 their test transform their @var{argument} values to a standard alphabet.
3672 First, @var{argument} is converted to upper case and any asterisks
3673 (@samp{*}) are each converted to @samp{P}.  Any remaining characters
3674 that are not alphanumeric are converted to underscores.
3676 For instance,
3678 @example
3679 AC_CHECK_TYPES([struct $Expensive*])
3680 @end example
3682 @noindent
3683 defines the symbol @samp{HAVE_STRUCT__EXPENSIVEP} if the check
3684 succeeds.
3687 @node Default Includes
3688 @subsection Default Includes
3689 @cindex Default includes
3690 @cindex Includes, default
3692 Several tests depend upon a set of header files.  Since these headers
3693 are not universally available, tests actually have to provide a set of
3694 protected includes, such as:
3696 @example
3697 @group
3698 #ifdef TIME_WITH_SYS_TIME
3699 # include <sys/time.h>
3700 # include <time.h>
3701 #else
3702 # ifdef HAVE_SYS_TIME_H
3703 #  include <sys/time.h>
3704 # else
3705 #  include <time.h>
3706 # endif
3707 #endif
3708 @end group
3709 @end example
3711 @noindent
3712 Unless you know exactly what you are doing, you should avoid using
3713 unconditional includes, and check the existence of the headers you
3714 include beforehand (@pxref{Header Files}).
3716 Most generic macros use the following macro to provide the default set
3717 of includes:
3719 @defmac AC_INCLUDES_DEFAULT (@ovar{include-directives})
3720 @acindex{INCLUDES_DEFAULT}
3721 Expand to @var{include-directives} if defined, otherwise to:
3723 @example
3724 @group
3725 #include <stdio.h>
3726 #ifdef HAVE_SYS_TYPES_H
3727 # include <sys/types.h>
3728 #endif
3729 #ifdef HAVE_SYS_STAT_H
3730 # include <sys/stat.h>
3731 #endif
3732 #ifdef STDC_HEADERS
3733 # include <stdlib.h>
3734 # include <stddef.h>
3735 #else
3736 # ifdef HAVE_STDLIB_H
3737 #  include <stdlib.h>
3738 # endif
3739 #endif
3740 #ifdef HAVE_STRING_H
3741 # if !defined STDC_HEADERS && defined HAVE_MEMORY_H
3742 #  include <memory.h>
3743 # endif
3744 # include <string.h>
3745 #endif
3746 #ifdef HAVE_STRINGS_H
3747 # include <strings.h>
3748 #endif
3749 #ifdef HAVE_INTTYPES_H
3750 # include <inttypes.h>
3751 #endif
3752 #ifdef HAVE_STDINT_H
3753 # include <stdint.h>
3754 #endif
3755 #ifdef HAVE_UNISTD_H
3756 # include <unistd.h>
3757 #endif
3758 @end group
3759 @end example
3761 If the default includes are used, then check for the presence of these
3762 headers and their compatibility, i.e., you don't need to run
3763 @code{AC_HEADER_STDC}, nor check for @file{stdlib.h} etc.
3765 These headers are checked for in the same order as they are included.
3766 For instance, on some systems @file{string.h} and @file{strings.h} both
3767 exist, but conflict.  Then @code{HAVE_STRING_H} is defined, not
3768 @code{HAVE_STRINGS_H}.
3769 @end defmac
3771 @node Alternative Programs
3772 @section Alternative Programs
3773 @cindex Programs, checking
3775 These macros check for the presence or behavior of particular programs.
3776 They are used to choose between several alternative programs and to
3777 decide what to do once one has been chosen.  If there is no macro
3778 specifically defined to check for a program you need, and you don't need
3779 to check for any special properties of it, then you can use one of the
3780 general program-check macros.
3782 @menu
3783 * Particular Programs::         Special handling to find certain programs
3784 * Generic Programs::            How to find other programs
3785 @end menu
3787 @node Particular Programs
3788 @subsection Particular Program Checks
3790 These macros check for particular programs---whether they exist, and
3791 in some cases whether they support certain features.
3793 @defmac AC_PROG_AWK
3794 @acindex{PROG_AWK}
3795 @ovindex AWK
3796 Check for @code{gawk}, @code{mawk}, @code{nawk}, and @code{awk}, in that
3797 order, and set output variable @code{AWK} to the first one that is found.
3798 It tries @code{gawk} first because that is reported to be the
3799 best implementation.
3800 @end defmac
3802 @defmac AC_PROG_GREP
3803 @acindex{PROG_GREP}
3804 @ovindex GREP
3805 Look for the best available @code{grep} or @code{ggrep} that accepts the
3806 longest input lines possible, and that supports multiple @option{-e} options.
3807 Set the output variable @code{GREP} to whatever is chosen.
3808 @xref{grep, , Limitations of Usual Tools}, for more information about
3809 portability problems with the @command{grep} command family.
3810 @end defmac
3812 @defmac AC_PROG_EGREP
3813 @acindex{PROG_EGREP}
3814 @ovindex EGREP
3815 Check whether @code{$GREP -E} works, or else look for the best available
3816 @code{egrep} or @code{gegrep} that accepts the longest input lines possible.
3817 Set the output variable @code{EGREP} to whatever is chosen.
3818 @end defmac
3820 @defmac AC_PROG_FGREP
3821 @acindex{PROG_FGREP}
3822 @ovindex FGREP
3823 Check whether @code{$GREP -F} works, or else look for the best available
3824 @code{fgrep} or @code{gfgrep} that accepts the longest input lines possible.
3825 Set the output variable @code{FGREP} to whatever is chosen.
3826 @end defmac
3828 @defmac AC_PROG_INSTALL
3829 @acindex{PROG_INSTALL}
3830 @ovindex INSTALL
3831 @ovindex INSTALL_PROGRAM
3832 @ovindex INSTALL_DATA
3833 @ovindex INSTALL_SCRIPT
3834 Set output variable @code{INSTALL} to the name of a @acronym{BSD}-compatible
3835 @command{install} program, if one is found in the current @env{PATH}.
3836 Otherwise, set @code{INSTALL} to @samp{@var{dir}/install-sh -c},
3837 checking the directories specified to @code{AC_CONFIG_AUX_DIR} (or its
3838 default directories) to determine @var{dir} (@pxref{Output}).  Also set
3839 the variables @code{INSTALL_PROGRAM} and @code{INSTALL_SCRIPT} to
3840 @samp{$@{INSTALL@}} and @code{INSTALL_DATA} to @samp{$@{INSTALL@} -m 644}.
3842 @samp{@@INSTALL@@} is special, as its value may vary for different
3843 configuration files.
3845 This macro screens out various instances of @command{install} known not to
3846 work.  It prefers to find a C program rather than a shell script, for
3847 speed.  Instead of @file{install-sh}, it can also use @file{install.sh},
3848 but that name is obsolete because some @command{make} programs have a rule
3849 that creates @file{install} from it if there is no makefile.  Further, this
3850 macro requires @command{install} to be able to install multiple files into a
3851 target directory in a single invocation.
3853 Autoconf comes with a copy of @file{install-sh} that you can use.  If
3854 you use @code{AC_PROG_INSTALL}, you must include either
3855 @file{install-sh} or @file{install.sh} in your distribution; otherwise
3856 @command{configure} produces an error message saying it can't find
3857 them---even if the system you're on has a good @command{install} program.
3858 This check is a safety measure to prevent you from accidentally leaving
3859 that file out, which would prevent your package from installing on
3860 systems that don't have a @acronym{BSD}-compatible @command{install} program.
3862 If you need to use your own installation program because it has features
3863 not found in standard @command{install} programs, there is no reason to use
3864 @code{AC_PROG_INSTALL}; just put the file name of your program into your
3865 @file{Makefile.in} files.
3866 @end defmac
3868 @defmac AC_PROG_MKDIR_P
3869 @acindex{PROG_MKDIR_P}
3870 @ovindex MKDIR_P
3871 Set output variable @code{MKDIR_P} to a program that ensures that for
3872 each argument, a directory named by this argument exists, creating it
3873 and its parent directories if needed, and without race conditions when
3874 two instances of the program attempt to make the same directory at
3875 nearly the same time.
3877 This macro uses the @samp{mkdir -p} command if possible.  Otherwise, it
3878 falls back on invoking @command{install-sh} with the @option{-d} option,
3879 so your package should
3880 contain @file{install-sh} as described under @code{AC_PROG_INSTALL}.
3881 An @file{install-sh} file that predates Autoconf 2.60 or Automake 1.10
3882 is vulnerable to race conditions, so if you want to support parallel
3883 installs from
3884 different packages into the same directory you need to make sure you
3885 have an up-to-date @file{install-sh}.  In particular, be careful about
3886 using @samp{autoreconf -if} if your Automake predates Automake 1.10.
3888 This macro is related to the @code{AS_MKDIR_P} macro (@pxref{Programming
3889 in M4sh}), but it sets an output variable intended for use in other
3890 files, whereas @code{AS_MKDIR_P} is intended for use in scripts like
3891 @command{configure}.  Also, @code{AS_MKDIR_P} does not accept options,
3892 but @code{MKDIR_P} supports the @option{-m} option, e.g., a makefile
3893 might invoke @code{$(MKDIR_P) -m 0 dir} to create an inaccessible
3894 directory, and conversely a makefile should use @code{$(MKDIR_P) --
3895 $(FOO)} if @var{FOO} might yield a value that begins with @samp{-}.
3896 Finally, @code{AS_MKDIR_P} does not check for race condition
3897 vulnerability, whereas @code{AC_PROG_MKDIR_P} does.
3899 @samp{@@MKDIR_P@@} is special, as its value may vary for different
3900 configuration files.
3901 @end defmac
3903 @anchor{AC_PROG_LEX}
3904 @defmac AC_PROG_LEX
3905 @acindex{PROG_LEX}
3906 @ovindex LEX
3907 @ovindex LEXLIB
3908 @cvindex YYTEXT_POINTER
3909 @ovindex LEX_OUTPUT_ROOT
3910 If @code{flex} is found, set output variable @code{LEX} to @samp{flex}
3911 and @code{LEXLIB} to @option{-lfl}, if that library is in a standard
3912 place.  Otherwise set @code{LEX} to @samp{lex} and @code{LEXLIB} to
3913 @option{-ll}.
3915 Define @code{YYTEXT_POINTER} if @code{yytext} defaults to @samp{char *} instead
3916 of to @samp{char []}.  Also set output variable @code{LEX_OUTPUT_ROOT} to
3917 the base of the file name that the lexer generates; usually
3918 @file{lex.yy}, but sometimes something else.  These results vary
3919 according to whether @code{lex} or @code{flex} is being used.
3921 You are encouraged to use Flex in your sources, since it is both more
3922 pleasant to use than plain Lex and the C source it produces is portable.
3923 In order to ensure portability, however, you must either provide a
3924 function @code{yywrap} or, if you don't use it (e.g., your scanner has
3925 no @samp{#include}-like feature), simply include a @samp{%noyywrap}
3926 statement in the scanner's source.  Once this done, the scanner is
3927 portable (unless @emph{you} felt free to use nonportable constructs) and
3928 does not depend on any library.  In this case, and in this case only, it
3929 is suggested that you use this Autoconf snippet:
3931 @example
3932 AC_PROG_LEX
3933 if test "$LEX" != flex; then
3934   LEX="$SHELL $missing_dir/missing flex"
3935   AC_SUBST([LEX_OUTPUT_ROOT], [lex.yy])
3936   AC_SUBST([LEXLIB], [''])
3938 @end example
3940 The shell script @command{missing} can be found in the Automake
3941 distribution.
3943 To ensure backward compatibility, Automake's @code{AM_PROG_LEX} invokes
3944 (indirectly) this macro twice, which causes an annoying but benign
3945 ``@code{AC_PROG_LEX} invoked multiple times'' warning.  Future versions
3946 of Automake will fix this issue; meanwhile, just ignore this message.
3948 As part of running the test, this macro may delete any file in the
3949 configuration directory named @file{lex.yy.c} or @file{lexyy.c}.
3950 @end defmac
3952 @anchor{AC_PROG_LN_S}
3953 @defmac AC_PROG_LN_S
3954 @acindex{PROG_LN_S}
3955 @ovindex LN_S
3956 If @samp{ln -s} works on the current file system (the operating system
3957 and file system support symbolic links), set the output variable
3958 @code{LN_S} to @samp{ln -s}; otherwise, if @samp{ln} works, set
3959 @code{LN_S} to @samp{ln}, and otherwise set it to @samp{cp -p}.
3961 If you make a link in a directory other than the current directory, its
3962 meaning depends on whether @samp{ln} or @samp{ln -s} is used.  To safely
3963 create links using @samp{$(LN_S)}, either find out which form is used
3964 and adjust the arguments, or always invoke @code{ln} in the directory
3965 where the link is to be created.
3967 In other words, it does not work to do:
3968 @example
3969 $(LN_S) foo /x/bar
3970 @end example
3972 Instead, do:
3974 @example
3975 (cd /x && $(LN_S) foo bar)
3976 @end example
3977 @end defmac
3979 @defmac AC_PROG_RANLIB
3980 @acindex{PROG_RANLIB}
3981 @ovindex RANLIB
3982 Set output variable @code{RANLIB} to @samp{ranlib} if @code{ranlib}
3983 is found, and otherwise to @samp{:} (do nothing).
3984 @end defmac
3986 @defmac AC_PROG_SED
3987 @acindex{PROG_SED}
3988 @ovindex SED
3989 Set output variable @code{SED} to a Sed implementation that conforms to
3990 Posix and does not have arbitrary length limits.  Report an error if no
3991 acceptable Sed is found.  @xref{sed, , Limitations of Usual Tools}, for more
3992 information about portability problems with Sed.
3993 @end defmac
3995 @defmac AC_PROG_YACC
3996 @acindex{PROG_YACC}
3997 @ovindex YACC
3998 If @code{bison} is found, set output variable @code{YACC} to @samp{bison
3999 -y}.  Otherwise, if @code{byacc} is found, set @code{YACC} to
4000 @samp{byacc}.  Otherwise set @code{YACC} to @samp{yacc}.
4001 @end defmac
4003 @node Generic Programs
4004 @subsection Generic Program and File Checks
4006 These macros are used to find programs not covered by the ``particular''
4007 test macros.  If you need to check the behavior of a program as well as
4008 find out whether it is present, you have to write your own test for it
4009 (@pxref{Writing Tests}).  By default, these macros use the environment
4010 variable @env{PATH}.  If you need to check for a program that might not
4011 be in the user's @env{PATH}, you can pass a modified path to use
4012 instead, like this:
4014 @example
4015 AC_PATH_PROG([INETD], [inetd], [/usr/libexec/inetd],
4016              [$PATH$PATH_SEPARATOR/usr/libexec$PATH_SEPARATOR]dnl
4017 [/usr/sbin$PATH_SEPARATOR/usr/etc$PATH_SEPARATOR/etc])
4018 @end example
4020 You are strongly encouraged to declare the @var{variable} passed to
4021 @code{AC_CHECK_PROG} etc.@: as precious, @xref{Setting Output Variables},
4022 @code{AC_ARG_VAR}, for more details.
4024 @anchor{AC_CHECK_PROG}
4025 @defmac AC_CHECK_PROG (@var{variable}, @var{prog-to-check-for}, @
4026   @var{value-if-found}, @ovar{value-if-not-found}, @dvar{path, $PATH}, @
4027   @ovar{reject})
4028 @acindex{CHECK_PROG}
4029 Check whether program @var{prog-to-check-for} exists in @var{path}.  If
4030 it is found, set @var{variable} to @var{value-if-found}, otherwise to
4031 @var{value-if-not-found}, if given.  Always pass over @var{reject} (an
4032 absolute file name) even if it is the first found in the search path; in
4033 that case, set @var{variable} using the absolute file name of the
4034 @var{prog-to-check-for} found that is not @var{reject}.  If
4035 @var{variable} was already set, do nothing.  Calls @code{AC_SUBST} for
4036 @var{variable}.
4037 @end defmac
4039 @anchor{AC_CHECK_PROGS}
4040 @defmac AC_CHECK_PROGS (@var{variable}, @var{progs-to-check-for}, @
4041   @ovar{value-if-not-found}, @dvar{path, $PATH})
4042 @acindex{CHECK_PROGS}
4043 Check for each program in the blank-separated list
4044 @var{progs-to-check-for} existing in the @var{path}.  If one is found, set
4045 @var{variable} to the name of that program.  Otherwise, continue
4046 checking the next program in the list.  If none of the programs in the
4047 list are found, set @var{variable} to @var{value-if-not-found}; if
4048 @var{value-if-not-found} is not specified, the value of @var{variable}
4049 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4050 @end defmac
4052 @defmac AC_CHECK_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4053   @ovar{value-if-not-found}, @dvar{path, $PATH})
4054 @acindex{CHECK_TARGET_TOOL}
4055 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4056 with a prefix of the target type as determined by
4057 @code{AC_CANONICAL_TARGET}, followed by a dash (@pxref{Canonicalizing}).
4058 If the tool cannot be found with a prefix, and if the build and target
4059 types are equal, then it is also searched for without a prefix.
4061 As noted in @ref{Specifying Names, , Specifying the system type}, the
4062 target is rarely specified, because most of the time it is the same
4063 as the host: it is the type of system for which any compiler tool in
4064 the package produces code.  What this macro looks for is,
4065 for example, @emph{a tool @r{(assembler, linker, etc.)}@: that the
4066 compiler driver @r{(@command{gcc} for the @acronym{GNU} C Compiler)}
4067 uses to produce objects, archives or executables}.
4068 @end defmac
4070 @defmac AC_CHECK_TOOL (@var{variable}, @var{prog-to-check-for}, @
4071   @ovar{value-if-not-found}, @dvar{path, $PATH})
4072 @acindex{CHECK_TOOL}
4073 Like @code{AC_CHECK_PROG}, but first looks for @var{prog-to-check-for}
4074 with a prefix of the host type as specified by @option{--host}, followed by a
4075 dash.  For example, if the user runs
4076 @samp{configure --build=x86_64-gnu --host=i386-gnu}, then this call:
4077 @example
4078 AC_CHECK_TOOL([RANLIB], [ranlib], [:])
4079 @end example
4080 @noindent
4081 sets @code{RANLIB} to @file{i386-gnu-ranlib} if that program exists in
4082 @var{path}, or otherwise to @samp{ranlib} if that program exists in
4083 @var{path}, or to @samp{:} if neither program exists.
4085 When cross-compiling, this macro will issue a warning if no program
4086 prefixed with the host type could be found.
4087 For more information, see @ref{Specifying Names, , Specifying the
4088 system type}.
4089 @end defmac
4091 @defmac AC_CHECK_TARGET_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4092   @ovar{value-if-not-found}, @dvar{path, $PATH})
4093 @acindex{CHECK_TARGET_TOOLS}
4094 Like @code{AC_CHECK_TARGET_TOOL}, each of the tools in the list
4095 @var{progs-to-check-for} are checked with a prefix of the target type as
4096 determined by @code{AC_CANONICAL_TARGET}, followed by a dash
4097 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4098 prefix, and if the build and target types are equal, then the first one
4099 without a prefix is used.  If a tool is found, set @var{variable} to
4100 the name of that program.  If none of the tools in the list are found,
4101 set @var{variable} to @var{value-if-not-found}; if @var{value-if-not-found}
4102 is not specified, the value of @var{variable} is not changed.  Calls
4103 @code{AC_SUBST} for @var{variable}.
4104 @end defmac
4106 @defmac AC_CHECK_TOOLS (@var{variable}, @var{progs-to-check-for}, @
4107   @ovar{value-if-not-found}, @dvar{path, $PATH})
4108 @acindex{CHECK_TOOLS}
4109 Like @code{AC_CHECK_TOOL}, each of the tools in the list
4110 @var{progs-to-check-for} are checked with a prefix of the host type as
4111 determined by @code{AC_CANONICAL_HOST}, followed by a dash
4112 (@pxref{Canonicalizing}).  If none of the tools can be found with a
4113 prefix, then the first one without a prefix is used.  If a tool is found,
4114 set @var{variable} to the name of that program.  If none of the tools in
4115 the list are found, set @var{variable} to @var{value-if-not-found}; if
4116 @var{value-if-not-found} is not specified, the value of @var{variable}
4117 is not changed.  Calls @code{AC_SUBST} for @var{variable}.
4119 When cross-compiling, this macro will issue a warning if no program
4120 prefixed with the host type could be found.
4121 For more information, see @ref{Specifying Names, , Specifying the
4122 system type}.
4123 @end defmac
4125 @anchor{AC_PATH_PROG}
4126 @defmac AC_PATH_PROG (@var{variable}, @var{prog-to-check-for}, @
4127   @ovar{value-if-not-found}, @dvar{path, $PATH})
4128 @acindex{PATH_PROG}
4129 Like @code{AC_CHECK_PROG}, but set @var{variable} to the absolute
4130 name of @var{prog-to-check-for} if found.
4131 @end defmac
4133 @anchor{AC_PATH_PROGS}
4134 @defmac AC_PATH_PROGS (@var{variable}, @var{progs-to-check-for}, @
4135   @ovar{value-if-not-found}, @dvar{path, $PATH})
4136 @acindex{PATH_PROGS}
4137 Like @code{AC_CHECK_PROGS}, but if any of @var{progs-to-check-for}
4138 are found, set @var{variable} to the absolute name of the program
4139 found.
4140 @end defmac
4142 @defmac AC_PATH_PROGS_FEATURE_CHECK (@var{variable}, @
4143   @var{progs-to-check-for}, @var{feature-test}, @
4144   @ovar{action-if-not-found}, @dvar{path, $PATH})
4145 @acindex{PATH_PROGS_FEATURE_CHECK}
4146 This macro was introduced in Autoconf 2.62.  If @var{variable} is not
4147 empty, then set the cache variable @code{$ac_cv_path_@var{variable}} to
4148 its value.  Otherwise, check for each program in the blank-separated
4149 list @var{progs-to-check-for} existing in @var{path}.  For each program
4150 found, execute @var{feature-test} with @code{$ac_path_@var{variable}}
4151 set to the absolute name of the candidate program.  If no invocation of
4152 @var{feature-test} sets the shell variable
4153 @code{$ac_cv_path_@var{variable}}, then @var{action-if-not-found} is
4154 executed.  @var{feature-test} will be run even when
4155 @code{ac_cv_path_@var{variable}} is set, to provide the ability to
4156 choose a better candidate found later in @var{path}; to accept the
4157 current setting and bypass all futher checks, @var{feature-test} can
4158 execute @code{ac_path_@var{variable}_found=:}.
4160 Note that this macro has some subtle differences from
4161 @code{AC_CHECK_PROGS}.  It is designed to be run inside
4162 @code{AC_CACHE_VAL}, therefore, it should have no side effects.  In
4163 particular, @var{variable} is not set to the final value of
4164 @code{ac_cv_path_@var{variable}}, nor is @code{AC_SUBST} automatically
4165 run.  Also, on failure, any action can be performed, whereas
4166 @code{AC_CHECK_PROGS} only performs
4167 @code{@var{variable}=@var{value-if-not-found}}.
4169 Here is an example, similar to what Autoconf uses in its own configure
4170 script.  It will search for an implementation of @command{m4} that
4171 supports the @code{indir} builtin, even if it goes by the name
4172 @command{gm4} or is not the first implementation on @env{PATH}.
4174 @example
4175 AC_CACHE_CHECK([for m4 that supports indir], [ac_cv_path_M4],
4176   [AC_PATH_PROGS_FEATURE_CHECK([M4], [m4 gm4],
4177     [[m4out=`echo 'changequote([,])indir([divnum])' | $ac_path_M4`
4178       test "x$m4out" = x0 \
4179       && ac_cv_path_M4=$ac_path_M4 ac_path_M4_found=:]],
4180     [AC_MSG_ERROR([could not find m4 that supports indir])])])
4181 AC_SUBST([M4], [$ac_cv_path_M4])
4182 @end example
4183 @end defmac
4185 @defmac AC_PATH_TARGET_TOOL (@var{variable}, @var{prog-to-check-for}, @
4186   @ovar{value-if-not-found}, @dvar{path, $PATH})
4187 @acindex{PATH_TARGET_TOOL}
4188 Like @code{AC_CHECK_TARGET_TOOL}, but set @var{variable} to the absolute
4189 name of the program if it is found.
4190 @end defmac
4192 @defmac AC_PATH_TOOL (@var{variable}, @var{prog-to-check-for}, @
4193   @ovar{value-if-not-found}, @dvar{path, $PATH})
4194 @acindex{PATH_TOOL}
4195 Like @code{AC_CHECK_TOOL}, but set @var{variable} to the absolute
4196 name of the program if it is found.
4198 When cross-compiling, this macro will issue a warning if no program
4199 prefixed with the host type could be found.
4200 For more information, see @ref{Specifying Names, , Specifying the
4201 system type}.
4202 @end defmac
4205 @node Files
4206 @section Files
4207 @cindex File, checking
4209 You might also need to check for the existence of files.  Before using
4210 these macros, ask yourself whether a runtime test might not be a better
4211 solution.  Be aware that, like most Autoconf macros, they test a feature
4212 of the host machine, and therefore, they die when cross-compiling.
4214 @defmac AC_CHECK_FILE (@var{file}, @ovar{action-if-found}, @
4215   @ovar{action-if-not-found})
4216 @acindex{CHECK_FILE}
4217 Check whether file @var{file} exists on the native system.  If it is
4218 found, execute @var{action-if-found}, otherwise do
4219 @var{action-if-not-found}, if given.
4220 @end defmac
4222 @defmac AC_CHECK_FILES (@var{files}, @ovar{action-if-found}, @
4223   @ovar{action-if-not-found})
4224 @acindex{CHECK_FILES}
4225 Executes @code{AC_CHECK_FILE} once for each file listed in @var{files}.
4226 Additionally, defines @samp{HAVE_@var{file}} (@pxref{Standard Symbols})
4227 for each file found.
4228 @end defmac
4231 @node Libraries
4232 @section Library Files
4233 @cindex Library, checking
4235 The following macros check for the presence of certain C, C++, or Fortran
4236 library archive files.
4238 @anchor{AC_CHECK_LIB}
4239 @defmac AC_CHECK_LIB (@var{library}, @var{function}, @
4240   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4241 @acindex{CHECK_LIB}
4242 Test whether the library @var{library} is available by trying to link
4243 a test program that calls function @var{function} with the library.
4244 @var{function} should be a function provided by the library.
4245 Use the base
4246 name of the library; e.g., to check for @option{-lmp}, use @samp{mp} as
4247 the @var{library} argument.
4249 @var{action-if-found} is a list of shell commands to run if the link
4250 with the library succeeds; @var{action-if-not-found} is a list of shell
4251 commands to run if the link fails.  If @var{action-if-found} is not
4252 specified, the default action prepends @option{-l@var{library}} to
4253 @code{LIBS} and defines @samp{HAVE_LIB@var{library}} (in all
4254 capitals).  This macro is intended to support building @code{LIBS} in
4255 a right-to-left (least-dependent to most-dependent) fashion such that
4256 library dependencies are satisfied as a natural side effect of
4257 consecutive tests.  Linkers are sensitive to library ordering
4258 so the order in which @code{LIBS} is generated is important to reliable
4259 detection of libraries.
4261 If linking with @var{library} results in unresolved symbols that would
4262 be resolved by linking with additional libraries, give those libraries
4263 as the @var{other-libraries} argument, separated by spaces:
4264 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4265 that @var{library} is present, because linking the test program
4266 always fails with unresolved symbols.  The @var{other-libraries} argument
4267 should be limited to cases where it is desirable to test for one library
4268 in the presence of another that is not already in @code{LIBS}.
4270 @code{AC_CHECK_LIB} requires some care in usage, and should be avoided
4271 in some common cases.  Many standard functions like @code{gethostbyname}
4272 appear in the standard C library on some hosts, and in special libraries
4273 like @code{nsl} on other hosts.  On some hosts the special libraries
4274 contain variant implementations that you may not want to use.  These
4275 days it is normally better to use @code{AC_SEARCH_LIBS([gethostbyname],
4276 [nsl])} instead of @code{AC_CHECK_LIB([nsl], [gethostbyname])}.
4277 @end defmac
4279 @anchor{AC_SEARCH_LIBS}
4280 @defmac AC_SEARCH_LIBS (@var{function}, @var{search-libs}, @
4281   @ovar{action-if-found}, @ovar{action-if-not-found}, @ovar{other-libraries})
4282 @acindex{SEARCH_LIBS}
4283 Search for a library defining @var{function} if it's not already
4284 available.  This equates to calling
4285 @samp{AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])])} first with
4286 no libraries, then for each library listed in @var{search-libs}.
4288 Add @option{-l@var{library}} to @code{LIBS} for the first library found
4289 to contain @var{function}, and run @var{action-if-found}.  If the
4290 function is not found, run @var{action-if-not-found}.
4292 If linking with @var{library} results in unresolved symbols that would
4293 be resolved by linking with additional libraries, give those libraries
4294 as the @var{other-libraries} argument, separated by spaces:
4295 e.g., @option{-lXt -lX11}.  Otherwise, this macro fails to detect
4296 that @var{function} is present, because linking the test program
4297 always fails with unresolved symbols.
4298 @end defmac
4302 @node Library Functions
4303 @section Library Functions
4305 The following macros check for particular C library functions.
4306 If there is no macro specifically defined to check for a function you need,
4307 and you don't need to check for any special properties of
4308 it, then you can use one of the general function-check macros.
4310 @menu
4311 * Function Portability::        Pitfalls with usual functions
4312 * Particular Functions::        Special handling to find certain functions
4313 * Generic Functions::           How to find other functions
4314 @end menu
4316 @node Function Portability
4317 @subsection Portability of C Functions
4318 @cindex Portability of C functions
4319 @cindex C function portability
4321 Most usual functions can either be missing, or be buggy, or be limited
4322 on some architectures.  This section tries to make an inventory of these
4323 portability issues.  By definition, this list always requires
4324 additions.  Please help us keeping it as complete as possible.
4326 @table @asis
4327 @item @code{exit}
4328 @c @fuindex exit
4329 @prindex @code{exit}
4330 On ancient hosts, @code{exit} returned @code{int}.
4331 This is because @code{exit} predates @code{void}, and there was a long
4332 tradition of it returning @code{int}.
4334 On current hosts, the problem more likely is that @code{exit} is not
4335 declared, due to C++ problems of some sort or another.  For this reason
4336 we suggest that test programs not invoke @code{exit}, but return from
4337 @code{main} instead.
4339 @item @code{free}
4340 @c @fuindex free
4341 @prindex @code{free}
4342 The C standard says a call @code{free (NULL)} does nothing, but
4343 some old systems don't support this (e.g., NextStep).
4345 @item @code{isinf}
4346 @itemx @code{isnan}
4347 @c @fuindex isinf
4348 @c @fuindex isnan
4349 @prindex @code{isinf}
4350 @prindex @code{isnan}
4351 The C99 standard says that @code{isinf} and @code{isnan} are
4352 macros.  On some systems just macros are available
4353 (e.g., @acronym{HP-UX} and Solaris 10), on
4354 some systems both macros and functions (e.g., glibc 2.3.2), and on some
4355 systems only functions (e.g., IRIX 6 and Solaris 9).  In some cases
4356 these functions are declared in nonstandard headers like
4357 @code{<sunmath.h>} and defined in non-default libraries like
4358 @option{-lm} or @option{-lsunmath}.
4360 The C99 @code{isinf} and @code{isnan} macros work correctly with
4361 @code{long double} arguments, but pre-C99 systems that use functions
4362 typically assume @code{double} arguments.  On such a system,
4363 @code{isinf} incorrectly returns true for a finite @code{long double}
4364 argument that is outside the range of @code{double}.
4366 The best workaround for these issues is to use gnulib modules
4367 @code{isinf} and @code{isnan} (@pxref{Gnulib}).  But a lighter weight
4368 solution involves code like the following.
4370 @smallexample
4371 #include <math.h>
4373 #ifndef isnan
4374 # define isnan(x) \
4375     (sizeof (x) == sizeof (long double) ? isnan_ld (x) \
4376      : sizeof (x) == sizeof (double) ? isnan_d (x) \
4377      : isnan_f (x))
4378 static inline int isnan_f  (float       x) @{ return x != x; @}
4379 static inline int isnan_d  (double      x) @{ return x != x; @}
4380 static inline int isnan_ld (long double x) @{ return x != x; @}
4381 #endif
4383 #ifndef isinf
4384 # define isinf(x) \
4385     (sizeof (x) == sizeof (long double) ? isinf_ld (x) \
4386      : sizeof (x) == sizeof (double) ? isinf_d (x) \
4387      : isinf_f (x))
4388 static inline int isinf_f  (float       x)
4389 @{ return !isnan (x) && isnan (x - x); @}
4390 static inline int isinf_d  (double      x)
4391 @{ return !isnan (x) && isnan (x - x); @}
4392 static inline int isinf_ld (long double x)
4393 @{ return !isnan (x) && isnan (x - x); @}
4394 #endif
4395 @end smallexample
4397 Use @code{AC_C_INLINE} (@pxref{C Compiler}) so that this code works on
4398 compilers that lack the @code{inline} keyword.  Some optimizing
4399 compilers mishandle these definitions, but systems with that bug
4400 typically have many other floating point corner-case compliance problems
4401 anyway, so it's probably not worth worrying about.
4403 @item @code{malloc}
4404 @c @fuindex malloc
4405 @prindex @code{malloc}
4406 The C standard says a call @code{malloc (0)} is implementation
4407 dependent.  It can return either @code{NULL} or a new non-null pointer.
4408 The latter is more common (e.g., the @acronym{GNU} C Library) but is by
4409 no means universal.  @code{AC_FUNC_MALLOC}
4410 can be used to insist on non-@code{NULL} (@pxref{Particular Functions}).
4412 @item @code{putenv}
4413 @c @fuindex putenv
4414 @prindex @code{putenv}
4415 Posix prefers @code{setenv} to @code{putenv}; among other things,
4416 @code{putenv} is not required of all Posix implementations, but
4417 @code{setenv} is.
4419 Posix specifies that @code{putenv} puts the given string directly in
4420 @code{environ}, but some systems make a copy of it instead (e.g.,
4421 glibc 2.0, or @acronym{BSD}).  And when a copy is made, @code{unsetenv} might
4422 not free it, causing a memory leak (e.g., Free@acronym{BSD} 4).
4424 On some systems @code{putenv ("FOO")} removes @samp{FOO} from the
4425 environment, but this is not standard usage and it dumps core
4426 on some systems (e.g., AIX).
4428 On MinGW, a call @code{putenv ("FOO=")} removes @samp{FOO} from the
4429 environment, rather than inserting it with an empty value.
4431 @item @code{realloc}
4432 @c @fuindex realloc
4433 @prindex @code{realloc}
4434 The C standard says a call @code{realloc (NULL, size)} is equivalent
4435 to @code{malloc (size)}, but some old systems don't support this (e.g.,
4436 NextStep).
4438 @item @code{signal} handler
4439 @c @fuindex signal
4440 @prindex @code{signal}
4441 @prindex @code{sigaction}
4442 Normally @code{signal} takes a handler function with a return type of
4443 @code{void}, but some old systems required @code{int} instead.  Any
4444 actual @code{int} value returned is not used; this is only a
4445 difference in the function prototype demanded.
4447 All systems we know of in current use return @code{void}.  The
4448 @code{int} was to support K&R C, where of course @code{void} is not
4449 available.  The obsolete macro @code{AC_TYPE_SIGNAL}
4450 (@pxref{AC_TYPE_SIGNAL}) can be used to establish the correct type in
4451 all cases.
4453 In most cases, it is more robust to use @code{sigaction} when it is
4454 available, rather than @code{signal}.
4456 @item @code{snprintf}
4457 @c @fuindex snprintf
4458 @prindex @code{snprintf}
4459 @c @fuindex vsnprintf
4460 @prindex @code{vsnprintf}
4461 The C99 standard says that if the output array isn't big enough
4462 and if no other errors occur, @code{snprintf} and @code{vsnprintf}
4463 truncate the output and return the number of bytes that ought to have
4464 been produced.  Some older systems return the truncated length (e.g.,
4465 @acronym{GNU} C Library 2.0.x or @sc{irix} 6.5), some a negative value
4466 (e.g., earlier @acronym{GNU} C Library versions), and some the buffer
4467 length without truncation (e.g., 32-bit Solaris 7).  Also, some buggy
4468 older systems ignore the length and overrun the buffer (e.g., 64-bit
4469 Solaris 7).
4471 @item @code{sprintf}
4472 @c @fuindex sprintf
4473 @prindex @code{sprintf}
4474 @c @fuindex vsprintf
4475 @prindex @code{vsprintf}
4476 The C standard says @code{sprintf} and @code{vsprintf} return the
4477 number of bytes written.  On some ancient systems (SunOS 4 for
4478 instance) they return the buffer pointer instead, but these no
4479 longer need to be worried about.
4481 @item @code{sscanf}
4482 @c @fuindex sscanf
4483 @prindex @code{sscanf}
4484 On various old systems, e.g., @acronym{HP-UX} 9, @code{sscanf} requires
4485 that its
4486 input string be writable (though it doesn't actually change it).  This
4487 can be a problem when using @command{gcc} since it normally puts
4488 constant strings in read-only memory (@pxref{Incompatibilities,
4489 Incompatibilities of @acronym{GCC}, , gcc, Using and
4490 Porting the @acronym{GNU} Compiler Collection}).  Apparently in some cases even
4491 having format strings read-only can be a problem.
4493 @item @code{strerror_r}
4494 @c @fuindex strerror_r
4495 @prindex @code{strerror_r}
4496 Posix specifies that @code{strerror_r} returns an @code{int}, but many
4497 systems (e.g., @acronym{GNU} C Library version 2.2.4) provide a
4498 different version returning a @code{char *}.  @code{AC_FUNC_STRERROR_R}
4499 can detect which is in use (@pxref{Particular Functions}).
4501 @item @code{strnlen}
4502 @c @fuindex strnlen
4503 @prindex @code{strnlen}
4504 @acronym{AIX} 4.3 provides a broken version which produces the
4505 following results:
4507 @example
4508 strnlen ("foobar", 0) = 0
4509 strnlen ("foobar", 1) = 3
4510 strnlen ("foobar", 2) = 2
4511 strnlen ("foobar", 3) = 1
4512 strnlen ("foobar", 4) = 0
4513 strnlen ("foobar", 5) = 6
4514 strnlen ("foobar", 6) = 6
4515 strnlen ("foobar", 7) = 6
4516 strnlen ("foobar", 8) = 6
4517 strnlen ("foobar", 9) = 6
4518 @end example
4520 @item @code{sysconf}
4521 @c @fuindex sysconf
4522 @prindex @code{sysconf}
4523 @code{_SC_PAGESIZE} is standard, but some older systems (e.g., @acronym{HP-UX}
4524 9) have @code{_SC_PAGE_SIZE} instead.  This can be tested with
4525 @code{#ifdef}.
4527 @item @code{unlink}
4528 @c @fuindex unlink
4529 @prindex @code{unlink}
4530 The Posix spec says that @code{unlink} causes the given file to be
4531 removed only after there are no more open file handles for it.  Some
4532 non-Posix hosts have trouble with this requirement, though,
4533 and some @acronym{DOS} variants even corrupt the file system.
4535 @item @code{unsetenv}
4536 @c @fuindex unsetenv
4537 @prindex @code{unsetenv}
4538 On MinGW, @code{unsetenv} is not available, but a variable @samp{FOO}
4539 can be removed with a call @code{putenv ("FOO=")}, as described under
4540 @code{putenv} above.
4542 @item @code{va_copy}
4543 @c @fuindex va_copy
4544 @prindex @code{va_copy}
4545 The C99 standard provides @code{va_copy} for copying
4546 @code{va_list} variables.  It may be available in older environments
4547 too, though possibly as @code{__va_copy} (e.g., @command{gcc} in strict
4548 pre-C99 mode).  These can be tested with @code{#ifdef}.  A fallback to
4549 @code{memcpy (&dst, &src, sizeof (va_list))} gives maximum
4550 portability.
4552 @item @code{va_list}
4553 @c @fuindex va_list
4554 @prindex @code{va_list}
4555 @code{va_list} is not necessarily just a pointer.  It can be a
4556 @code{struct} (e.g., @command{gcc} on Alpha), which means @code{NULL} is
4557 not portable.  Or it can be an array (e.g., @command{gcc} in some
4558 PowerPC configurations), which means as a function parameter it can be
4559 effectively call-by-reference and library routines might modify the
4560 value back in the caller (e.g., @code{vsnprintf} in the @acronym{GNU} C Library
4561 2.1).
4563 @item Signed @code{>>}
4564 Normally the C @code{>>} right shift of a signed type replicates the
4565 high bit, giving a so-called ``arithmetic'' shift.  But care should be
4566 taken since Standard C doesn't require that behavior.  On those
4567 few processors without a native arithmetic shift (for instance Cray
4568 vector systems) zero bits may be shifted in, the same as a shift of an
4569 unsigned type.
4571 @item Integer @code{/}
4572 C divides signed integers by truncating their quotient toward zero,
4573 yielding the same result as Fortran.  However, before C99 the standard
4574 allowed C implementations to take the floor or ceiling of the quotient
4575 in some cases.  Hardly any implementations took advantage of this
4576 freedom, though, and it's probably not worth worrying about this issue
4577 nowadays.
4578 @end table
4581 @node Particular Functions
4582 @subsection Particular Function Checks
4583 @cindex Function, checking
4585 These macros check for particular C functions---whether they exist, and
4586 in some cases how they respond when given certain arguments.
4588 @anchor{AC_FUNC_ALLOCA}
4589 @defmac AC_FUNC_ALLOCA
4590 @acindex{FUNC_ALLOCA}
4591 @cvindex C_ALLOCA
4592 @cvindex HAVE_ALLOCA_H
4593 @ovindex ALLOCA
4594 @c @fuindex alloca
4595 @prindex @code{alloca}
4596 @hdrindex{alloca.h}
4597 Check how to get @code{alloca}.  Tries to get a builtin version by
4598 checking for @file{alloca.h} or the predefined C preprocessor macros
4599 @code{__GNUC__} and @code{_AIX}.  If this macro finds @file{alloca.h},
4600 it defines @code{HAVE_ALLOCA_H}.
4602 If those attempts fail, it looks for the function in the standard C
4603 library.  If any of those methods succeed, it defines
4604 @code{HAVE_ALLOCA}.  Otherwise, it sets the output variable
4605 @code{ALLOCA} to @samp{$@{LIBOBJDIR@}alloca.o} and defines
4606 @code{C_ALLOCA} (so programs can periodically call @samp{alloca (0)} to
4607 garbage collect).  This variable is separate from @code{LIBOBJS} so
4608 multiple programs can share the value of @code{ALLOCA} without needing
4609 to create an actual library, in case only some of them use the code in
4610 @code{LIBOBJS}.  The @samp{$@{LIBOBJDIR@}} prefix serves the same
4611 purpose as in @code{LIBOBJS} (@pxref{AC_LIBOBJ vs LIBOBJS}).
4613 This macro does not try to get @code{alloca} from the System V R3
4614 @file{libPW} or the System V R4 @file{libucb} because those libraries
4615 contain some incompatible functions that cause trouble.  Some versions
4616 do not even contain @code{alloca} or contain a buggy version.  If you
4617 still want to use their @code{alloca}, use @code{ar} to extract
4618 @file{alloca.o} from them instead of compiling @file{alloca.c}.
4620 Source files that use @code{alloca} should start with a piece of code
4621 like the following, to declare it properly.
4623 @example
4624 @group
4625 #ifdef HAVE_ALLOCA_H
4626 # include <alloca.h>
4627 #elif defined __GNUC__
4628 # define alloca __builtin_alloca
4629 #elif defined _AIX
4630 # define alloca __alloca
4631 #elif defined _MSC_VER
4632 # include <malloc.h>
4633 # define alloca _alloca
4634 #else
4635 # include <stddef.h>
4636 # ifdef  __cplusplus
4637 extern "C"
4638 # endif
4639 void *alloca (size_t);
4640 #endif
4641 @end group
4642 @end example
4643 @end defmac
4645 @defmac AC_FUNC_CHOWN
4646 @acindex{FUNC_CHOWN}
4647 @cvindex HAVE_CHOWN
4648 @c @fuindex chown
4649 @prindex @code{chown}
4650 If the @code{chown} function is available and works (in particular, it
4651 should accept @option{-1} for @code{uid} and @code{gid}), define
4652 @code{HAVE_CHOWN}.
4653 @end defmac
4655 @anchor{AC_FUNC_CLOSEDIR_VOID}
4656 @defmac AC_FUNC_CLOSEDIR_VOID
4657 @acindex{FUNC_CLOSEDIR_VOID}
4658 @cvindex CLOSEDIR_VOID
4659 @c @fuindex closedir
4660 @prindex @code{closedir}
4661 If the @code{closedir} function does not return a meaningful value,
4662 define @code{CLOSEDIR_VOID}.  Otherwise, callers ought to check its
4663 return value for an error indicator.
4665 Currently this test is implemented by running a test program.  When
4666 cross compiling the pessimistic assumption that @code{closedir} does not
4667 return a meaningful value is made.
4669 This macro is obsolescent, as @code{closedir} returns a meaningful value
4670 on current systems.  New programs need not use this macro.
4671 @end defmac
4673 @defmac AC_FUNC_ERROR_AT_LINE
4674 @acindex{FUNC_ERROR_AT_LINE}
4675 @c @fuindex error_at_line
4676 @prindex @code{error_at_line}
4677 If the @code{error_at_line} function is not found, require an
4678 @code{AC_LIBOBJ} replacement of @samp{error}.
4679 @end defmac
4681 @defmac AC_FUNC_FNMATCH
4682 @acindex{FUNC_FNMATCH}
4683 @c @fuindex fnmatch
4684 @prindex @code{fnmatch}
4685 If the @code{fnmatch} function conforms to Posix, define
4686 @code{HAVE_FNMATCH}.  Detect common implementation bugs, for example,
4687 the bugs in Solaris 2.4.
4689 Unlike the other specific
4690 @code{AC_FUNC} macros, @code{AC_FUNC_FNMATCH} does not replace a
4691 broken/missing @code{fnmatch}.  This is for historical reasons.
4692 See @code{AC_REPLACE_FNMATCH} below.
4694 This macro is obsolescent.  New programs should use Gnulib's
4695 @code{fnmatch-posix} module.  @xref{Gnulib}.
4696 @end defmac
4698 @defmac AC_FUNC_FNMATCH_GNU
4699 @acindex{FUNC_FNMATCH_GNU}
4700 @c @fuindex fnmatch
4701 @prindex @code{fnmatch}
4702 Behave like @code{AC_REPLACE_FNMATCH} (@emph{replace}) but also test
4703 whether @code{fnmatch} supports @acronym{GNU} extensions.  Detect common
4704 implementation bugs, for example, the bugs in the @acronym{GNU} C
4705 Library 2.1.
4707 This macro is obsolescent.  New programs should use Gnulib's
4708 @code{fnmatch-gnu} module.  @xref{Gnulib}.
4709 @end defmac
4711 @anchor{AC_FUNC_FORK}
4712 @defmac AC_FUNC_FORK
4713 @acindex{FUNC_FORK}
4714 @cvindex HAVE_VFORK_H
4715 @cvindex HAVE_WORKING_FORK
4716 @cvindex HAVE_WORKING_VFORK
4717 @cvindex vfork
4718 @c @fuindex fork
4719 @prindex @code{fork}
4720 @c @fuindex vfork
4721 @prindex @code{vfork}
4722 @hdrindex{vfork.h}
4723 This macro checks for the @code{fork} and @code{vfork} functions.  If a
4724 working @code{fork} is found, define @code{HAVE_WORKING_FORK}.  This macro
4725 checks whether @code{fork} is just a stub by trying to run it.
4727 If @file{vfork.h} is found, define @code{HAVE_VFORK_H}.  If a working
4728 @code{vfork} is found, define @code{HAVE_WORKING_VFORK}.  Otherwise,
4729 define @code{vfork} to be @code{fork} for backward compatibility with
4730 previous versions of @command{autoconf}.  This macro checks for several known
4731 errors in implementations of @code{vfork} and considers the system to not
4732 have a working @code{vfork} if it detects any of them.  It is not considered
4733 to be an implementation error if a child's invocation of @code{signal}
4734 modifies the parent's signal handler, since child processes rarely change
4735 their signal handlers.
4737 Since this macro defines @code{vfork} only for backward compatibility with
4738 previous versions of @command{autoconf} you're encouraged to define it
4739 yourself in new code:
4740 @example
4741 @group
4742 #ifndef HAVE_WORKING_VFORK
4743 # define vfork fork
4744 #endif
4745 @end group
4746 @end example
4747 @end defmac
4749 @defmac AC_FUNC_FSEEKO
4750 @acindex{FUNC_FSEEKO}
4751 @cvindex _LARGEFILE_SOURCE
4752 @cvindex HAVE_FSEEKO
4753 @c @fuindex fseeko
4754 @prindex @code{fseeko}
4755 @c @fuindex ftello
4756 @prindex @code{ftello}
4757 If the @code{fseeko} function is available, define @code{HAVE_FSEEKO}.
4758 Define @code{_LARGEFILE_SOURCE} if necessary to make the prototype
4759 visible on some systems (e.g., glibc 2.2).  Otherwise linkage problems
4760 may occur when compiling with @code{AC_SYS_LARGEFILE} on
4761 largefile-sensitive systems where @code{off_t} does not default to a
4762 64bit entity.  All systems with @code{fseeko} also supply @code{ftello}.
4763 @end defmac
4765 @defmac AC_FUNC_GETGROUPS
4766 @acindex{FUNC_GETGROUPS}
4767 @cvindex HAVE_GETGROUPS
4768 @ovindex GETGROUPS_LIBS
4769 @c @fuindex getgroups
4770 @prindex @code{getgroups}
4771 If the @code{getgroups} function is available and works (unlike on
4772 Ultrix 4.3, where @samp{getgroups (0, 0)} always fails), define
4773 @code{HAVE_GETGROUPS}.  Set @code{GETGROUPS_LIBS} to any libraries
4774 needed to get that function.  This macro runs @code{AC_TYPE_GETGROUPS}.
4775 @end defmac
4777 @anchor{AC_FUNC_GETLOADAVG}
4778 @defmac AC_FUNC_GETLOADAVG
4779 @acindex{FUNC_GETLOADAVG}
4780 @cvindex SVR4
4781 @cvindex DGUX
4782 @cvindex UMAX
4783 @cvindex UMAX4_3
4784 @cvindex HAVE_NLIST_H
4785 @cvindex NLIST_NAME_UNION
4786 @cvindex GETLOADAVG_PRIVILEGED
4787 @cvindex NEED_SETGID
4788 @cvindex C_GETLOADAVG
4789 @ovindex LIBOBJS
4790 @ovindex NEED_SETGID
4791 @ovindex KMEM_GROUP
4792 @ovindex GETLOADAVG_LIBS
4793 @c @fuindex getloadavg
4794 @prindex @code{getloadavg}
4795 Check how to get the system load averages.  To perform its tests
4796 properly, this macro needs the file @file{getloadavg.c}; therefore, be
4797 sure to set the @code{AC_LIBOBJ} replacement directory properly (see
4798 @ref{Generic Functions}, @code{AC_CONFIG_LIBOBJ_DIR}).
4800 If the system has the @code{getloadavg} function, define
4801 @code{HAVE_GETLOADAVG}, and set @code{GETLOADAVG_LIBS} to any libraries
4802 necessary to get that function.  Also add @code{GETLOADAVG_LIBS} to
4803 @code{LIBS}.  Otherwise, require an @code{AC_LIBOBJ} replacement for
4804 @samp{getloadavg} with source code in @file{@var{dir}/getloadavg.c}, and
4805 possibly define several other C preprocessor macros and output
4806 variables:
4808 @enumerate
4809 @item
4810 Define @code{C_GETLOADAVG}.
4812 @item
4813 Define @code{SVR4}, @code{DGUX}, @code{UMAX}, or @code{UMAX4_3} if on
4814 those systems.
4816 @item
4817 @hdrindex{nlist.h}
4818 If @file{nlist.h} is found, define @code{HAVE_NLIST_H}.
4820 @item
4821 If @samp{struct nlist} has an @samp{n_un.n_name} member, define
4822 @code{HAVE_STRUCT_NLIST_N_UN_N_NAME}.  The obsolete symbol
4823 @code{NLIST_NAME_UNION} is still defined, but do not depend upon it.
4825 @item
4826 Programs may need to be installed set-group-ID (or set-user-ID) for
4827 @code{getloadavg} to work.  In this case, define
4828 @code{GETLOADAVG_PRIVILEGED}, set the output variable @code{NEED_SETGID}
4829 to @samp{true} (and otherwise to @samp{false}), and set
4830 @code{KMEM_GROUP} to the name of the group that should own the installed
4831 program.
4832 @end enumerate
4834 The @code{AC_FUNC_GETLOADAVG} macro is obsolescent.  New programs should
4835 use Gnulib's @code{getloadavg} module.  @xref{Gnulib}.
4836 @end defmac
4838 @anchor{AC_FUNC_GETMNTENT}
4839 @defmac AC_FUNC_GETMNTENT
4840 @acindex{FUNC_GETMNTENT}
4841 @cvindex HAVE_GETMNTENT
4842 @c @fuindex getmntent
4843 @prindex @code{getmntent}
4844 Check for @code{getmntent} in the standard C library, and then in the
4845 @file{sun}, @file{seq}, and @file{gen} libraries, for @sc{unicos},
4846 @sc{irix} 4, @sc{ptx}, and UnixWare, respectively.  Then, if
4847 @code{getmntent} is available, define @code{HAVE_GETMNTENT}.
4848 @end defmac
4850 @defmac AC_FUNC_GETPGRP
4851 @acindex{FUNC_GETPGRP}
4852 @cvindex GETPGRP_VOID
4853 @c @fuindex getpgid
4854 @c @fuindex getpgrp
4855 @prindex @code{getpgid}
4856 @prindex @code{getpgrp}
4857 Define @code{GETPGRP_VOID} if it is an error to pass 0 to
4858 @code{getpgrp}; this is the Posix behavior.  On older @acronym{BSD}
4859 systems, you must pass 0 to @code{getpgrp}, as it takes an argument and
4860 behaves like Posix's @code{getpgid}.
4862 @example
4863 #ifdef GETPGRP_VOID
4864   pid = getpgrp ();
4865 #else
4866   pid = getpgrp (0);
4867 #endif
4868 @end example
4870 This macro does not check whether
4871 @code{getpgrp} exists at all; if you need to work in that situation,
4872 first call @code{AC_CHECK_FUNC} for @code{getpgrp}.
4874 This macro is obsolescent, as current systems have a @code{getpgrp}
4875 whose signature conforms to Posix.  New programs need not use this macro.
4876 @end defmac
4878 @defmac AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK
4879 @acindex{FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK}
4880 @cvindex LSTAT_FOLLOWS_SLASHED_SYMLINK
4881 @c @fuindex lstat
4882 @prindex @code{lstat}
4883 If @file{link} is a symbolic link, then @code{lstat} should treat
4884 @file{link/} the same as @file{link/.}.  However, many older
4885 @code{lstat} implementations incorrectly ignore trailing slashes.
4887 It is safe to assume that if @code{lstat} incorrectly ignores
4888 trailing slashes, then other symbolic-link-aware functions like
4889 @code{unlink} also incorrectly ignore trailing slashes.
4891 If @code{lstat} behaves properly, define
4892 @code{LSTAT_FOLLOWS_SLASHED_SYMLINK}, otherwise require an
4893 @code{AC_LIBOBJ} replacement of @code{lstat}.
4894 @end defmac
4896 @defmac AC_FUNC_MALLOC
4897 @acindex{FUNC_MALLOC}
4898 @cvindex HAVE_MALLOC
4899 @cvindex malloc
4900 @c @fuindex malloc
4901 @prindex @code{malloc}
4902 If the @code{malloc} function is compatible with the @acronym{GNU} C
4903 library @code{malloc} (i.e., @samp{malloc (0)} returns a valid
4904 pointer), define @code{HAVE_MALLOC} to 1.  Otherwise define
4905 @code{HAVE_MALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4906 @samp{malloc}, and define @code{malloc} to @code{rpl_malloc} so that the
4907 native @code{malloc} is not used in the main project.
4909 Typically, the replacement file @file{malloc.c} should look like (note
4910 the @samp{#undef malloc}):
4912 @verbatim
4913 #include <config.h>
4914 #undef malloc
4916 #include <sys/types.h>
4918 void *malloc ();
4920 /* Allocate an N-byte block of memory from the heap.
4921    If N is zero, allocate a 1-byte block.  */
4923 void *
4924 rpl_malloc (size_t n)
4926   if (n == 0)
4927     n = 1;
4928   return malloc (n);
4930 @end verbatim
4931 @end defmac
4933 @defmac AC_FUNC_MEMCMP
4934 @acindex{FUNC_MEMCMP}
4935 @ovindex LIBOBJS
4936 @c @fuindex memcmp
4937 @prindex @code{memcmp}
4938 If the @code{memcmp} function is not available, or does not work on
4939 8-bit data (like the one on SunOS 4.1.3), or fails when comparing 16
4940 bytes or more and with at least one buffer not starting on a 4-byte
4941 boundary (such as the one on NeXT x86 OpenStep), require an
4942 @code{AC_LIBOBJ} replacement for @samp{memcmp}.
4944 This macro is obsolescent, as current systems have a working
4945 @code{memcmp}.  New programs need not use this macro.
4946 @end defmac
4948 @defmac AC_FUNC_MBRTOWC
4949 @acindex{FUNC_MBRTOWC}
4950 @cvindex HAVE_MBRTOWC
4951 @c @fuindex mbrtowc
4952 @prindex @code{mbrtowc}
4953 Define @code{HAVE_MBRTOWC} to 1 if the function @code{mbrtowc} and the
4954 type @code{mbstate_t} are properly declared.
4955 @end defmac
4957 @defmac AC_FUNC_MKTIME
4958 @acindex{FUNC_MKTIME}
4959 @ovindex LIBOBJS
4960 @c @fuindex mktime
4961 @prindex @code{mktime}
4962 If the @code{mktime} function is not available, or does not work
4963 correctly, require an @code{AC_LIBOBJ} replacement for @samp{mktime}.
4964 For the purposes of this test, @code{mktime} should conform to the
4965 Posix standard and should be the inverse of
4966 @code{localtime}.
4967 @end defmac
4969 @anchor{AC_FUNC_MMAP}
4970 @defmac AC_FUNC_MMAP
4971 @acindex{FUNC_MMAP}
4972 @cvindex HAVE_MMAP
4973 @c @fuindex mmap
4974 @prindex @code{mmap}
4975 If the @code{mmap} function exists and works correctly, define
4976 @code{HAVE_MMAP}.  This checks only private fixed mapping of already-mapped
4977 memory.
4978 @end defmac
4980 @defmac AC_FUNC_OBSTACK
4981 @acindex{FUNC_OBSTACK}
4982 @cvindex HAVE_OBSTACK
4983 @cindex obstack
4984 If the obstacks are found, define @code{HAVE_OBSTACK}, else require an
4985 @code{AC_LIBOBJ} replacement for @samp{obstack}.
4986 @end defmac
4988 @defmac AC_FUNC_REALLOC
4989 @acindex{FUNC_REALLOC}
4990 @cvindex HAVE_REALLOC
4991 @cvindex realloc
4992 @c @fuindex realloc
4993 @prindex @code{realloc}
4994 If the @code{realloc} function is compatible with the @acronym{GNU} C
4995 library @code{realloc} (i.e., @samp{realloc (NULL, 0)} returns a
4996 valid pointer), define @code{HAVE_REALLOC} to 1.  Otherwise define
4997 @code{HAVE_REALLOC} to 0, ask for an @code{AC_LIBOBJ} replacement for
4998 @samp{realloc}, and define @code{realloc} to @code{rpl_realloc} so that
4999 the native @code{realloc} is not used in the main project.  See
5000 @code{AC_FUNC_MALLOC} for details.
5001 @end defmac
5003 @defmac AC_FUNC_SELECT_ARGTYPES
5004 @acindex{FUNC_SELECT_ARGTYPES}
5005 @cvindex SELECT_TYPE_ARG1
5006 @cvindex SELECT_TYPE_ARG234
5007 @cvindex SELECT_TYPE_ARG5
5008 @c @fuindex select
5009 @prindex @code{select}
5010 Determines the correct type to be passed for each of the
5011 @code{select} function's arguments, and defines those types
5012 in @code{SELECT_TYPE_ARG1}, @code{SELECT_TYPE_ARG234}, and
5013 @code{SELECT_TYPE_ARG5} respectively.  @code{SELECT_TYPE_ARG1} defaults
5014 to @samp{int}, @code{SELECT_TYPE_ARG234} defaults to @samp{int *},
5015 and @code{SELECT_TYPE_ARG5} defaults to @samp{struct timeval *}.
5017 This macro is obsolescent, as current systems have a @code{select} whose
5018 signature conforms to Posix.  New programs need not use this macro.
5019 @end defmac
5021 @defmac AC_FUNC_SETPGRP
5022 @acindex{FUNC_SETPGRP}
5023 @cvindex SETPGRP_VOID
5024 @c @fuindex setpgrp
5025 @prindex @code{setpgrp}
5026 If @code{setpgrp} takes no argument (the Posix version), define
5027 @code{SETPGRP_VOID}.  Otherwise, it is the @acronym{BSD} version, which takes
5028 two process IDs as arguments.  This macro does not check whether
5029 @code{setpgrp} exists at all; if you need to work in that situation,
5030 first call @code{AC_CHECK_FUNC} for @code{setpgrp}.
5032 This macro is obsolescent, as current systems have a @code{setpgrp}
5033 whose signature conforms to Posix.  New programs need not use this macro.
5034 @end defmac
5036 @defmac AC_FUNC_STAT
5037 @defmacx AC_FUNC_LSTAT
5038 @acindex{FUNC_STAT}
5039 @acindex{FUNC_LSTAT}
5040 @cvindex HAVE_STAT_EMPTY_STRING_BUG
5041 @cvindex HAVE_LSTAT_EMPTY_STRING_BUG
5042 @c @fuindex stat
5043 @prindex @code{stat}
5044 @c @fuindex lstat
5045 @prindex @code{lstat}
5046 Determine whether @code{stat} or @code{lstat} have the bug that it
5047 succeeds when given the zero-length file name as argument.  The @code{stat}
5048 and @code{lstat} from SunOS 4.1.4 and the Hurd (as of 1998-11-01) do
5049 this.
5051 If it does, then define @code{HAVE_STAT_EMPTY_STRING_BUG} (or
5052 @code{HAVE_LSTAT_EMPTY_STRING_BUG}) and ask for an @code{AC_LIBOBJ}
5053 replacement of it.
5055 These macros are obsolescent, as no current systems have the bug.
5056 New programs need not use these macros.
5057 @end defmac
5059 @anchor{AC_FUNC_STRCOLL}
5060 @defmac AC_FUNC_STRCOLL
5061 @acindex{FUNC_STRCOLL}
5062 @cvindex HAVE_STRCOLL
5063 @c @fuindex strcoll
5064 @prindex @code{strcoll}
5065 If the @code{strcoll} function exists and works correctly, define
5066 @code{HAVE_STRCOLL}.  This does a bit more than
5067 @samp{AC_CHECK_FUNCS(strcoll)}, because some systems have incorrect
5068 definitions of @code{strcoll} that should not be used.
5069 @end defmac
5071 @defmac AC_FUNC_STRERROR_R
5072 @acindex{FUNC_STRERROR_R}
5073 @cvindex HAVE_STRERROR_R
5074 @cvindex HAVE_DECL_STRERROR_R
5075 @cvindex STRERROR_R_CHAR_P
5076 @c @fuindex strerror_r
5077 @prindex @code{strerror_r}
5078 If @code{strerror_r} is available, define @code{HAVE_STRERROR_R}, and if
5079 it is declared, define @code{HAVE_DECL_STRERROR_R}.  If it returns a
5080 @code{char *} message, define @code{STRERROR_R_CHAR_P}; otherwise it
5081 returns an @code{int} error number.  The Thread-Safe Functions option of
5082 Posix requires @code{strerror_r} to return @code{int}, but
5083 many systems (including, for example, version 2.2.4 of the @acronym{GNU} C
5084 Library) return a @code{char *} value that is not necessarily equal to
5085 the buffer argument.
5086 @end defmac
5088 @anchor{AC_FUNC_STRFTIME}
5089 @defmac AC_FUNC_STRFTIME
5090 @acindex{FUNC_STRFTIME}
5091 @cvindex HAVE_STRFTIME
5092 @c @fuindex strftime
5093 @prindex @code{strftime}
5094 Check for @code{strftime} in the @file{intl} library, for SCO Unix.
5095 Then, if @code{strftime} is available, define @code{HAVE_STRFTIME}.
5097 This macro is obsolescent, as no current systems require the @file{intl}
5098 library for @code{strftime}.  New programs need not use this macro.
5099 @end defmac
5101 @defmac AC_FUNC_STRTOD
5102 @acindex{FUNC_STRTOD}
5103 @ovindex POW_LIB
5104 @c @fuindex strtod
5105 @prindex @code{strtod}
5106 If the @code{strtod} function does not exist or doesn't work correctly,
5107 ask for an @code{AC_LIBOBJ} replacement of @samp{strtod}.  In this case,
5108 because @file{strtod.c} is likely to need @samp{pow}, set the output
5109 variable @code{POW_LIB} to the extra library needed.
5110 @end defmac
5112 @defmac AC_FUNC_STRTOLD
5113 @acindex{FUNC_STRTOLD}
5114 @cvindex HAVE_STRTOLD
5115 @prindex @code{strtold}
5116 If the @code{strtold} function exists and conforms to C99, define
5117 @code{HAVE_STRTOLD}.
5118 @end defmac
5120 @defmac AC_FUNC_STRNLEN
5121 @acindex{FUNC_STRNLEN}
5122 @cvindex HAVE_STRNLEN
5123 @c @fuindex strnlen
5124 @prindex @code{strnlen}
5125 If the @code{strnlen} function is not available, or is buggy (like the one
5126 from @acronym{AIX} 4.3), require an @code{AC_LIBOBJ} replacement for it.
5127 @end defmac
5129 @anchor{AC_FUNC_UTIME_NULL}
5130 @defmac AC_FUNC_UTIME_NULL
5131 @acindex{FUNC_UTIME_NULL}
5132 @cvindex HAVE_UTIME_NULL
5133 @c @fuindex utime
5134 @prindex @code{utime}
5135 If @samp{utime (@var{file}, NULL)} sets @var{file}'s timestamp to
5136 the present, define @code{HAVE_UTIME_NULL}.
5138 This macro is obsolescent, as all current systems have a @code{utime}
5139 that behaves this way.  New programs need not use this macro.
5140 @end defmac
5142 @anchor{AC_FUNC_VPRINTF}
5143 @defmac AC_FUNC_VPRINTF
5144 @acindex{FUNC_VPRINTF}
5145 @cvindex HAVE_VPRINTF
5146 @cvindex HAVE_DOPRNT
5147 @c @fuindex vprintf
5148 @prindex @code{vprintf}
5149 @c @fuindex vsprintf
5150 @prindex @code{vsprintf}
5151 If @code{vprintf} is found, define @code{HAVE_VPRINTF}.  Otherwise, if
5152 @code{_doprnt} is found, define @code{HAVE_DOPRNT}.  (If @code{vprintf}
5153 is available, you may assume that @code{vfprintf} and @code{vsprintf}
5154 are also available.)
5156 This macro is obsolescent, as all current systems have @code{vprintf}.
5157 New programs need not use this macro.
5158 @end defmac
5160 @defmac AC_REPLACE_FNMATCH
5161 @acindex{REPLACE_FNMATCH}
5162 @c @fuindex fnmatch
5163 @prindex @code{fnmatch}
5164 @hdrindex{fnmatch.h}
5165 If the @code{fnmatch} function does not conform to Posix (see
5166 @code{AC_FUNC_FNMATCH}), ask for its @code{AC_LIBOBJ} replacement.
5168 The files @file{fnmatch.c}, @file{fnmatch_loop.c}, and @file{fnmatch_.h}
5169 in the @code{AC_LIBOBJ} replacement directory are assumed to contain a
5170 copy of the source code of @acronym{GNU} @code{fnmatch}.  If necessary,
5171 this source code is compiled as an @code{AC_LIBOBJ} replacement, and the
5172 @file{fnmatch_.h} file is linked to @file{fnmatch.h} so that it can be
5173 included in place of the system @code{<fnmatch.h>}.
5175 This macro is obsolescent, as it assumes the use of particular source
5176 files.  New programs should use Gnulib's @code{fnmatch-posix} module,
5177 which provides this macro along with the source files.  @xref{Gnulib}.
5178 @end defmac
5182 @node Generic Functions
5183 @subsection Generic Function Checks
5185 These macros are used to find functions not covered by the ``particular''
5186 test macros.  If the functions might be in libraries other than the
5187 default C library, first call @code{AC_CHECK_LIB} for those libraries.
5188 If you need to check the behavior of a function as well as find out
5189 whether it is present, you have to write your own test for
5190 it (@pxref{Writing Tests}).
5192 @anchor{AC_CHECK_FUNC}
5193 @defmac AC_CHECK_FUNC (@var{function}, @ovar{action-if-found}, @
5194   @ovar{action-if-not-found})
5195 @acindex{CHECK_FUNC}
5196 If C function @var{function} is available, run shell commands
5197 @var{action-if-found}, otherwise @var{action-if-not-found}.  If you just
5198 want to define a symbol if the function is available, consider using
5199 @code{AC_CHECK_FUNCS} instead.  This macro checks for functions with C
5200 linkage even when @code{AC_LANG(C++)} has been called, since C is more
5201 standardized than C++.  (@pxref{Language Choice}, for more information
5202 about selecting the language for checks.)
5203 @end defmac
5205 @anchor{AC_CHECK_FUNCS}
5206 @defmac AC_CHECK_FUNCS (@var{function}@dots{}, @ovar{action-if-found}, @
5207   @ovar{action-if-not-found})
5208 @acindex{CHECK_FUNCS}
5209 @cvindex HAVE_@var{function}
5210 For each @var{function} enumerated in the blank-or-newline-separated argument
5211 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5212 If @var{action-if-found} is given, it is additional shell code to
5213 execute when one of the functions is found.  You can give it a value of
5214 @samp{break} to break out of the loop on the first match.  If
5215 @var{action-if-not-found} is given, it is executed when one of the
5216 functions is not found.
5217 @end defmac
5219 @defmac AC_CHECK_FUNCS_ONCE (@var{function}@dots{})
5220 @acindex{CHECK_FUNCS_ONCE}
5221 @cvindex HAVE_@var{function}
5222 For each @var{function} enumerated in the blank-or-newline-separated argument
5223 list, define @code{HAVE_@var{function}} (in all capitals) if it is available.
5224 This is a once-only variant of @code{AC_CHECK_FUNCS}.  It generates the
5225 checking code at most once, so that @command{configure} is smaller and
5226 faster; but the checks cannot be conditionalized and are always done once,
5227 early during the @command{configure} run.
5228 @end defmac
5230 @sp 1
5232 Autoconf follows a philosophy that was formed over the years by those
5233 who have struggled for portability: isolate the portability issues in
5234 specific files, and then program as if you were in a Posix
5235 environment.  Some functions may be missing or unfixable, and your
5236 package must be ready to replace them.
5238 Suitable replacements for many such problem functions are available from
5239 Gnulib (@pxref{Gnulib}).
5241 @defmac AC_LIBOBJ (@var{function})
5242 @acindex{LIBOBJ}
5243 @ovindex LIBOBJS
5244 Specify that @samp{@var{function}.c} must be included in the executables
5245 to replace a missing or broken implementation of @var{function}.
5247 Technically, it adds @samp{@var{function}.$ac_objext} to the output
5248 variable @code{LIBOBJS} if it is not already in, and calls
5249 @code{AC_LIBSOURCE} for @samp{@var{function}.c}.  You should not
5250 directly change @code{LIBOBJS}, since this is not traceable.
5251 @end defmac
5253 @defmac AC_LIBSOURCE (@var{file})
5254 @acindex{LIBSOURCE}
5255 Specify that @var{file} might be needed to compile the project.  If you
5256 need to know what files might be needed by a @file{configure.ac}, you
5257 should trace @code{AC_LIBSOURCE}.  @var{file} must be a literal.
5259 This macro is called automatically from @code{AC_LIBOBJ}, but you must
5260 call it explicitly if you pass a shell variable to @code{AC_LIBOBJ}.  In
5261 that case, since shell variables cannot be traced statically, you must
5262 pass to @code{AC_LIBSOURCE} any possible files that the shell variable
5263 might cause @code{AC_LIBOBJ} to need.  For example, if you want to pass
5264 a variable @code{$foo_or_bar} to @code{AC_LIBOBJ} that holds either
5265 @code{"foo"} or @code{"bar"}, you should do:
5267 @example
5268 AC_LIBSOURCE([foo.c])
5269 AC_LIBSOURCE([bar.c])
5270 AC_LIBOBJ([$foo_or_bar])
5271 @end example
5273 @noindent
5274 There is usually a way to avoid this, however, and you are encouraged to
5275 simply call @code{AC_LIBOBJ} with literal arguments.
5277 Note that this macro replaces the obsolete @code{AC_LIBOBJ_DECL}, with
5278 slightly different semantics: the old macro took the function name,
5279 e.g., @code{foo}, as its argument rather than the file name.
5280 @end defmac
5282 @defmac AC_LIBSOURCES (@var{files})
5283 @acindex{LIBSOURCES}
5284 Like @code{AC_LIBSOURCE}, but accepts one or more @var{files} in a
5285 comma-separated M4 list.  Thus, the above example might be rewritten:
5287 @example
5288 AC_LIBSOURCES([foo.c, bar.c])
5289 AC_LIBOBJ([$foo_or_bar])
5290 @end example
5291 @end defmac
5293 @defmac AC_CONFIG_LIBOBJ_DIR (@var{directory})
5294 @acindex{CONFIG_LIBOBJ_DIR}
5295 Specify that @code{AC_LIBOBJ} replacement files are to be found in
5296 @var{directory}, a name relative to the top level of the
5297 source tree.  The replacement directory defaults to @file{.}, the top
5298 level directory, and the most typical value is @file{lib}, corresponding
5299 to @samp{AC_CONFIG_LIBOBJ_DIR([lib])}.
5301 @command{configure} might need to know the replacement directory for the
5302 following reasons: (i) some checks use the replacement files, (ii) some
5303 macros bypass broken system headers by installing links to the
5304 replacement headers (iii) when used in conjunction with Automake,
5305 within each makefile, @var{directory} is used as a relative path
5306 from @code{$(top_srcdir)} to each object named in @code{LIBOBJS} and
5307 @code{LTLIBOBJS}, etc.
5308 @end defmac
5310 @sp 1
5312 It is common to merely check for the existence of a function, and ask
5313 for its @code{AC_LIBOBJ} replacement if missing.  The following macro is
5314 a convenient shorthand.
5316 @defmac AC_REPLACE_FUNCS (@var{function}@dots{})
5317 @acindex{REPLACE_FUNCS}
5318 @cvindex HAVE_@var{function}
5319 @ovindex LIBOBJS
5320 Like @code{AC_CHECK_FUNCS}, but uses @samp{AC_LIBOBJ(@var{function})} as
5321 @var{action-if-not-found}.  You can declare your replacement function by
5322 enclosing the prototype in @samp{#ifndef HAVE_@var{function}}.  If the
5323 system has the function, it probably declares it in a header file you
5324 should be including, so you shouldn't redeclare it lest your declaration
5325 conflict.
5326 @end defmac
5328 @node Header Files
5329 @section Header Files
5330 @cindex Header, checking
5332 The following macros check for the presence of certain C header files.
5333 If there is no macro specifically defined to check for a header file you need,
5334 and you don't need to check for any special properties of
5335 it, then you can use one of the general header-file check macros.
5337 @menu
5338 * Header Portability::          Collected knowledge on common headers
5339 * Particular Headers::          Special handling to find certain headers
5340 * Generic Headers::             How to find other headers
5341 @end menu
5343 @node Header Portability
5344 @subsection Portability of Headers
5345 @cindex Portability of headers
5346 @cindex Header portability
5348 This section tries to collect knowledge about common headers, and the
5349 problems they cause.  By definition, this list always requires
5350 additions.  Please help us keeping it as complete as possible.
5352 @table @asis
5354 @item @file{limits.h}
5355 C99 says that @file{limits.h} defines @code{LLONG_MIN},
5356 @code{LLONG_MAX}, and @code{ULLONG_MAX}, but many almost-C99
5357 environments (e.g., default @acronym{GCC} 4.0.2 + glibc 2.4) do not
5358 define them.
5360 @item @file{inttypes.h} vs.@: @file{stdint.h}
5361 @hdrindex{inttypes.h}
5362 @hdrindex{stdint.h}
5363 The C99 standard says that @file{inttypes.h} includes
5364 @file{stdint.h}, so there's no need to include @file{stdint.h}
5365 separately in a standard environment.  Some implementations have
5366 @file{inttypes.h} but not @file{stdint.h} (e.g., Solaris 7), but we don't
5367 know of any implementation that has @file{stdint.h} but not
5368 @file{inttypes.h}.
5370 @item @file{linux/irda.h}
5371 @hdrindex{linux/irda.h}
5372 It requires @file{linux/types.h} and @file{sys/socket.h}.
5374 @item @file{linux/random.h}
5375 @hdrindex{linux/random.h}
5376 It requires @file{linux/types.h}.
5378 @item @file{net/if.h}
5379 @hdrindex{net/if.h}
5380 On Darwin, this file requires that @file{sys/socket.h} be included
5381 beforehand.  One should run:
5383 @example
5384 AC_CHECK_HEADERS([sys/socket.h])
5385 AC_CHECK_HEADERS([net/if.h], [], [],
5386 [#include <stdio.h>
5387 #ifdef STDC_HEADERS
5388 # include <stdlib.h>
5389 # include <stddef.h>
5390 #else
5391 # ifdef HAVE_STDLIB_H
5392 #  include <stdlib.h>
5393 # endif
5394 #endif
5395 #ifdef HAVE_SYS_SOCKET_H
5396 # include <sys/socket.h>
5397 #endif
5399 @end example
5401 @item @file{netinet/if_ether.h}
5402 @hdrindex{netinet/if_ether.h}
5403 On Darwin, this file requires that @file{stdio.h} and
5404 @file{sys/socket.h} be included beforehand.  One should run:
5406 @example
5407 AC_CHECK_HEADERS([sys/socket.h])
5408 AC_CHECK_HEADERS([netinet/if_ether.h], [], [],
5409 [#include <stdio.h>
5410 #ifdef STDC_HEADERS
5411 # include <stdlib.h>
5412 # include <stddef.h>
5413 #else
5414 # ifdef HAVE_STDLIB_H
5415 #  include <stdlib.h>
5416 # endif
5417 #endif
5418 #ifdef HAVE_SYS_SOCKET_H
5419 # include <sys/socket.h>
5420 #endif
5422 @end example
5424 @item @file{stdint.h}
5425 See above, item @file{inttypes.h} vs.@: @file{stdint.h}.
5427 @item @file{stdlib.h}
5428 @hdrindex{stdlib.h}
5429 On many systems (e.g., Darwin), @file{stdio.h} is a prerequisite.
5431 @item @file{sys/mount.h}
5432 @hdrindex{sys/mount.h}
5433 On Free@acronym{BSD} 4.8 on ia32 and using gcc version 2.95.4,
5434 @file{sys/params.h} is a prerequisite.
5436 @item @file{sys/ptem.h}
5437 @hdrindex{sys/ptem.h}
5438 On Solaris 8, @file{sys/stream.h} is a prerequisite.
5440 @item @file{sys/socket.h}
5441 @hdrindex{sys/socket.h}
5442 On Darwin, @file{stdlib.h} is a prerequisite.
5444 @item @file{sys/ucred.h}
5445 @hdrindex{sys/ucred.h}
5446 On Tru64 5.1, @file{sys/types.h} is a prerequisite.
5448 @item @file{X11/extensions/scrnsaver.h}
5449 @hdrindex{X11/extensions/scrnsaver.h}
5450 Using XFree86, this header requires @file{X11/Xlib.h}, which is probably
5451 so required that you might not even consider looking for it.
5453 @example
5454 AC_CHECK_HEADERS([X11/extensions/scrnsaver.h], [], [],
5455 [[#include <X11/Xlib.h>
5457 @end example
5458 @end table
5461 @node Particular Headers
5462 @subsection Particular Header Checks
5464 These macros check for particular system header files---whether they
5465 exist, and in some cases whether they declare certain symbols.
5467 @defmac AC_HEADER_ASSERT
5468 @acindex{HEADER_ASSERT}
5469 @cvindex NDEBUG
5470 @hdrindex{assert.h}
5471 Check whether to enable assertions in the style of @file{assert.h}.
5472 Assertions are enabled by default, but the user can override this by
5473 invoking @command{configure} with the @option{--disable-assert} option.
5474 @end defmac
5476 @anchor{AC_HEADER_DIRENT}
5477 @defmac AC_HEADER_DIRENT
5478 @acindex{HEADER_DIRENT}
5479 @cvindex HAVE_DIRENT_H
5480 @cvindex HAVE_NDIR_H
5481 @cvindex HAVE_SYS_DIR_H
5482 @cvindex HAVE_SYS_NDIR_H
5483 @hdrindex{dirent.h}
5484 @hdrindex{sys/ndir.h}
5485 @hdrindex{sys/dir.h}
5486 @hdrindex{ndir.h}
5487 Check for the following header files.  For the first one that is
5488 found and defines @samp{DIR}, define the listed C preprocessor macro:
5490 @multitable {@file{sys/ndir.h}} {@code{HAVE_SYS_NDIR_H}}
5491 @item @file{dirent.h}   @tab @code{HAVE_DIRENT_H}
5492 @item @file{sys/ndir.h} @tab @code{HAVE_SYS_NDIR_H}
5493 @item @file{sys/dir.h}  @tab @code{HAVE_SYS_DIR_H}
5494 @item @file{ndir.h}     @tab @code{HAVE_NDIR_H}
5495 @end multitable
5497 The directory-library declarations in your source code should look
5498 something like the following:
5500 @example
5501 @group
5502 #include <sys/types.h>
5503 #ifdef HAVE_DIRENT_H
5504 # include <dirent.h>
5505 # define NAMLEN(dirent) strlen ((dirent)->d_name)
5506 #else
5507 # define dirent direct
5508 # define NAMLEN(dirent) ((dirent)->d_namlen)
5509 # ifdef HAVE_SYS_NDIR_H
5510 #  include <sys/ndir.h>
5511 # endif
5512 # ifdef HAVE_SYS_DIR_H
5513 #  include <sys/dir.h>
5514 # endif
5515 # ifdef HAVE_NDIR_H
5516 #  include <ndir.h>
5517 # endif
5518 #endif
5519 @end group
5520 @end example
5522 Using the above declarations, the program would declare variables to be
5523 of type @code{struct dirent}, not @code{struct direct}, and would access
5524 the length of a directory entry name by passing a pointer to a
5525 @code{struct dirent} to the @code{NAMLEN} macro.
5527 This macro also checks for the SCO Xenix @file{dir} and @file{x} libraries.
5529 This macro is obsolescent, as all current systems with directory
5530 libraries have @code{<dirent.h>}.  New programs need not use this macro.
5532 Also see @code{AC_STRUCT_DIRENT_D_INO} and
5533 @code{AC_STRUCT_DIRENT_D_TYPE} (@pxref{Particular Structures}).
5534 @end defmac
5536 @anchor{AC_HEADER_MAJOR}
5537 @defmac AC_HEADER_MAJOR
5538 @acindex{HEADER_MAJOR}
5539 @cvindex MAJOR_IN_MKDEV
5540 @cvindex MAJOR_IN_SYSMACROS
5541 @hdrindex{sys/mkdev.h}
5542 @hdrindex{sys/sysmacros.h}
5543 If @file{sys/types.h} does not define @code{major}, @code{minor}, and
5544 @code{makedev}, but @file{sys/mkdev.h} does, define
5545 @code{MAJOR_IN_MKDEV}; otherwise, if @file{sys/sysmacros.h} does, define
5546 @code{MAJOR_IN_SYSMACROS}.
5547 @end defmac
5549 @defmac AC_HEADER_RESOLV
5550 @acindex{HEADER_RESOLV}
5551 @cvindex HAVE_RESOLV_H
5552 @hdrindex{resolv.h}
5553 Checks for header @file{resolv.h}, checking for prerequisites first.
5554 To properly use @file{resolv.h}, your code should contain something like
5555 the following:
5557 @verbatim
5558 #ifdef HAVE_SYS_TYPES_H
5559 #  include <sys/types.h>
5560 #endif
5561 #ifdef HAVE_NETINET_IN_H
5562 #  include <netinet/in.h>   /* inet_ functions / structs */
5563 #endif
5564 #ifdef HAVE_ARPA_NAMESER_H
5565 #  include <arpa/nameser.h> /* DNS HEADER struct */
5566 #endif
5567 #ifdef HAVE_NETDB_H
5568 #  include <netdb.h>
5569 #endif
5570 #include <resolv.h>
5571 @end verbatim
5572 @end defmac
5574 @anchor{AC_HEADER_STAT}
5575 @defmac AC_HEADER_STAT
5576 @acindex{HEADER_STAT}
5577 @cvindex STAT_MACROS_BROKEN
5578 @hdrindex{sys/stat.h}
5579 If the macros @code{S_ISDIR}, @code{S_ISREG}, etc.@: defined in
5580 @file{sys/stat.h} do not work properly (returning false positives),
5581 define @code{STAT_MACROS_BROKEN}.  This is the case on Tektronix UTekV,
5582 Amdahl UTS and Motorola System V/88.
5584 This macro is obsolescent, as no current systems have the bug.
5585 New programs need not use this macro.
5586 @end defmac
5588 @defmac AC_HEADER_STDBOOL
5589 @acindex{HEADER_STDBOOL}
5590 @cvindex HAVE_STDBOOL_H
5591 @cvindex HAVE__BOOL
5592 @hdrindex{stdbool.h}
5593 @hdrindex{system.h}
5594 If @file{stdbool.h} exists and conforms to C99, define
5595 @code{HAVE_STDBOOL_H} to 1; if the type @code{_Bool} is defined, define
5596 @code{HAVE__BOOL} to 1.  To fulfill the C99 requirements, your
5597 @file{system.h} could contain the following code:
5599 @verbatim
5600 #ifdef HAVE_STDBOOL_H
5601 # include <stdbool.h>
5602 #else
5603 # ifndef HAVE__BOOL
5604 #  ifdef __cplusplus
5605 typedef bool _Bool;
5606 #  else
5607 #   define _Bool signed char
5608 #  endif
5609 # endif
5610 # define bool _Bool
5611 # define false 0
5612 # define true 1
5613 # define __bool_true_false_are_defined 1
5614 #endif
5615 @end verbatim
5617 Alternatively you can use the @samp{stdbool} package of Gnulib
5618 (@pxref{Gnulib}); it packages the above code into a replacement header
5619 and contains a few other bells and whistles.
5621 @end defmac
5623 @anchor{AC_HEADER_STDC}
5624 @defmac AC_HEADER_STDC
5625 @acindex{HEADER_STDC}
5626 @cvindex STDC_HEADERS
5627 @hdrindex{stdlib.h}
5628 @hdrindex{stdarg.h}
5629 @hdrindex{string.h}
5630 @hdrindex{float.h}
5631 @hdrindex{ctype.h}
5632 Define @code{STDC_HEADERS} if the system has C header files
5633 conforming to @acronym{ANSI} C89 (@acronym{ISO} C90).
5634 Specifically, this macro checks for @file{stdlib.h}, @file{stdarg.h},
5635 @file{string.h}, and @file{float.h}; if the system has those, it
5636 probably has the rest of the C89 header files.  This macro also
5637 checks whether @file{string.h} declares @code{memchr} (and thus
5638 presumably the other @code{mem} functions), whether @file{stdlib.h}
5639 declare @code{free} (and thus presumably @code{malloc} and other related
5640 functions), and whether the @file{ctype.h} macros work on characters
5641 with the high bit set, as the C standard requires.
5643 If you use this macro, your code can refer to @code{STDC_HEADERS} to
5644 determine whether the system has conforming header files (and probably C
5645 library functions).
5647 This macro is obsolescent, as current systems have conforming header
5648 files.  New programs need not use this macro.
5650 @hdrindex{string.h}
5651 @hdrindex{strings.h}
5652 Nowadays @file{string.h} is part of the C standard and declares functions like
5653 @code{strcpy}, and @file{strings.h} is standardized by Posix and declares
5654 @acronym{BSD} functions like @code{bcopy}; but
5655 historically, string functions were a major sticking point in this area.
5656 If you still want to worry about portability to ancient systems without
5657 standard headers, there is so much variation
5658 that it is probably easier to declare the functions you use than to
5659 figure out exactly what the system header files declare.  Some ancient systems
5660 contained a mix of functions from the C standard and from @acronym{BSD};
5661 some were mostly standard but lacked @samp{memmove}; some defined the
5662 @acronym{BSD} functions as macros in @file{string.h} or
5663 @file{strings.h}; some had only the @acronym{BSD} functions but
5664 @file{string.h}; some declared the memory functions in @file{memory.h},
5665 some in @file{string.h}; etc.  It is probably sufficient to check for
5666 one string function and one memory function; if the library had the
5667 standard versions of those then it probably had most of the others.
5668 If you put the following in @file{configure.ac}:
5670 @example
5671 # This example is obsolescent.
5672 # Nowadays you can omit these macro calls.
5673 AC_HEADER_STDC
5674 AC_CHECK_FUNCS([strchr memcpy])
5675 @end example
5677 @noindent
5678 then, in your code, you can use declarations like this:
5680 @example
5681 @group
5682 /* This example is obsolescent.
5683    Nowadays you can just #include <string.h>.  */
5684 #ifdef STDC_HEADERS
5685 # include <string.h>
5686 #else
5687 # ifndef HAVE_STRCHR
5688 #  define strchr index
5689 #  define strrchr rindex
5690 # endif
5691 char *strchr (), *strrchr ();
5692 # ifndef HAVE_MEMCPY
5693 #  define memcpy(d, s, n) bcopy ((s), (d), (n))
5694 #  define memmove(d, s, n) bcopy ((s), (d), (n))
5695 # endif
5696 #endif
5697 @end group
5698 @end example
5700 @noindent
5701 If you use a function like @code{memchr}, @code{memset}, @code{strtok},
5702 or @code{strspn}, which have no @acronym{BSD} equivalent, then macros don't
5703 suffice to port to ancient hosts; you must provide an implementation of
5704 each function.  An easy
5705 way to incorporate your implementations only when needed (since the ones
5706 in system C libraries may be hand optimized) is to, taking @code{memchr}
5707 for example, put it in @file{memchr.c} and use
5708 @samp{AC_REPLACE_FUNCS([memchr])}.
5709 @end defmac
5711 @defmac AC_HEADER_SYS_WAIT
5712 @acindex{HEADER_SYS_WAIT}
5713 @cvindex HAVE_SYS_WAIT_H
5714 @hdrindex{sys/wait.h}
5715 If @file{sys/wait.h} exists and is compatible with Posix, define
5716 @code{HAVE_SYS_WAIT_H}.  Incompatibility can occur if @file{sys/wait.h}
5717 does not exist, or if it uses the old @acronym{BSD} @code{union wait} instead
5718 of @code{int} to store a status value.  If @file{sys/wait.h} is not
5719 Posix compatible, then instead of including it, define the
5720 Posix macros with their usual interpretations.  Here is an
5721 example:
5723 @example
5724 @group
5725 #include <sys/types.h>
5726 #ifdef HAVE_SYS_WAIT_H
5727 # include <sys/wait.h>
5728 #endif
5729 #ifndef WEXITSTATUS
5730 # define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8)
5731 #endif
5732 #ifndef WIFEXITED
5733 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
5734 #endif
5735 @end group
5736 @end example
5738 @noindent
5739 This macro is obsolescent, as current systems are compatible with Posix.
5740 New programs need not use this macro.
5741 @end defmac
5743 @cvindex _POSIX_VERSION
5744 @hdrindex{unistd.h}
5745 @code{_POSIX_VERSION} is defined when @file{unistd.h} is included on
5746 Posix systems.  If there is no @file{unistd.h}, it is definitely
5747 not a Posix system.  However, some non-Posix systems do
5748 have @file{unistd.h}.
5750 The way to check whether the system supports Posix is:
5752 @example
5753 @group
5754 #ifdef HAVE_UNISTD_H
5755 # include <sys/types.h>
5756 # include <unistd.h>
5757 #endif
5759 #ifdef _POSIX_VERSION
5760 /* Code for Posix systems.  */
5761 #endif
5762 @end group
5763 @end example
5765 @anchor{AC_HEADER_TIME}
5766 @defmac AC_HEADER_TIME
5767 @acindex{HEADER_TIME}
5768 @cvindex TIME_WITH_SYS_TIME
5769 @hdrindex{time.h}
5770 @hdrindex{sys/time.h}
5771 If a program may include both @file{time.h} and @file{sys/time.h},
5772 define @code{TIME_WITH_SYS_TIME}.  On some ancient systems,
5773 @file{sys/time.h} included @file{time.h}, but @file{time.h} was not
5774 protected against multiple inclusion, so programs could not explicitly
5775 include both files.  This macro is useful in programs that use, for
5776 example, @code{struct timeval} as well as
5777 @code{struct tm}.  It is best used in conjunction with
5778 @code{HAVE_SYS_TIME_H}, which can be checked for using
5779 @code{AC_CHECK_HEADERS([sys/time.h])}.
5781 @example
5782 @group
5783 #ifdef TIME_WITH_SYS_TIME
5784 # include <sys/time.h>
5785 # include <time.h>
5786 #else
5787 # ifdef HAVE_SYS_TIME_H
5788 #  include <sys/time.h>
5789 # else
5790 #  include <time.h>
5791 # endif
5792 #endif
5793 @end group
5794 @end example
5796 @noindent
5797 This macro is obsolescent, as current systems can include both files
5798 when they exist.  New programs need not use this macro.
5799 @end defmac
5802 @defmac AC_HEADER_TIOCGWINSZ
5803 @acindex{HEADER_TIOCGWINSZ}
5804 @cvindex GWINSZ_IN_SYS_IOCTL
5805 @hdrindex{sys/ioctl.h}
5806 @hdrindex{termios.h}
5807 @c FIXME: I need clarifications from Jim.
5808 If the use of @code{TIOCGWINSZ} requires @file{<sys/ioctl.h>}, then
5809 define @code{GWINSZ_IN_SYS_IOCTL}.  Otherwise @code{TIOCGWINSZ} can be
5810 found in @file{<termios.h>}.
5812 Use:
5814 @example
5815 @group
5816 #ifdef HAVE_TERMIOS_H
5817 # include <termios.h>
5818 #endif
5820 #ifdef GWINSZ_IN_SYS_IOCTL
5821 # include <sys/ioctl.h>
5822 #endif
5823 @end group
5824 @end example
5825 @end defmac
5827 @node Generic Headers
5828 @subsection Generic Header Checks
5830 These macros are used to find system header files not covered by the
5831 ``particular'' test macros.  If you need to check the contents of a header
5832 as well as find out whether it is present, you have to write your own
5833 test for it (@pxref{Writing Tests}).
5835 @anchor{AC_CHECK_HEADER}
5836 @defmac AC_CHECK_HEADER (@var{header-file}, @ovar{action-if-found}, @
5837   @ovar{action-if-not-found}, @ovar{includes})
5838 @acindex{CHECK_HEADER}
5839 If the system header file @var{header-file} is compilable, execute shell
5840 commands @var{action-if-found}, otherwise execute
5841 @var{action-if-not-found}.  If you just want to define a symbol if the
5842 header file is available, consider using @code{AC_CHECK_HEADERS}
5843 instead.
5845 @var{includes} is decoded to determine the appropriate include
5846 directives.  If omitted or empty, @file{configure} will check for both header
5847 existence (with the preprocessor) and usability (with the compiler),
5848 using @code{AC_INCLUDES_DEFAULT} for the compile test.  If
5849 there is a discrepancy between the results, a warning is issued to the
5850 user, and the compiler results are favored (@pxref{Present But
5851 Cannot Be Compiled}).  In general, favoring the compiler results means
5852 that a header will be treated as not found even though the file exists,
5853 because you did not provide enough prerequisites.
5855 Providing a non-empty @var{includes} argument allows the code to provide
5856 any prerequisites prior to including the header under test; it is common
5857 to use the argument @code{AC_INCLUDES_DEFAULT} (@pxref{Default
5858 Includes}).  With an explicit fourth argument, no preprocessor test is
5859 needed.  As a special case, an @var{includes} of exactly @samp{-}
5860 triggers the older preprocessor check, which merely determines existence
5861 of the file in the preprocessor search path; this should only be used as
5862 a last resort (it is safer to determine the actual prerequisites and
5863 perform a compiler check, or else use @code{AC_PREPROC_IFELSE} to make
5864 it obvious that only a preprocessor check is desired).
5865 @end defmac
5867 @anchor{AC_CHECK_HEADERS}
5868 @defmac AC_CHECK_HEADERS (@var{header-file}@dots{}, @
5869   @ovar{action-if-found}, @ovar{action-if-not-found}, @
5870   @ovar{includes})
5871 @acindex{CHECK_HEADERS}
5872 @cvindex HAVE_@var{header}
5873 For each given system header file @var{header-file} in the
5874 blank-separated argument list that exists, define
5875 @code{HAVE_@var{header-file}} (in all capitals).  If @var{action-if-found}
5876 is given, it is additional shell code to execute when one of the header
5877 files is found.  You can give it a value of @samp{break} to break out of
5878 the loop on the first match.  If @var{action-if-not-found} is given, it
5879 is executed when one of the header files is not found.
5881 @var{includes} is interpreted as in @code{AC_CHECK_HEADER}, in order to
5882 choose the set of preprocessor directives supplied before the header
5883 under test.
5884 @end defmac
5886 Previous versions of Autoconf merely checked whether the header was
5887 accepted by the preprocessor.  This was changed because the old test was
5888 inappropriate for typical uses.  Headers are typically used to compile,
5889 not merely to preprocess, and the old behavior sometimes accepted
5890 headers that clashed at compile-time (@pxref{Present But Cannot Be
5891 Compiled}).  If you need to check whether a header is preprocessable,
5892 you can use @code{AC_PREPROC_IFELSE} (@pxref{Running the Preprocessor}).
5894 Actually requiring a header to compile improves the robustness of the
5895 test, but it also requires
5896 that you make sure that headers that must be included before the
5897 @var{header-file} be part of the @var{includes}, (@pxref{Default
5898 Includes}).  If looking for @file{bar.h}, which requires that
5899 @file{foo.h} be included before if it exists, we suggest the following
5900 scheme:
5902 @verbatim
5903 AC_CHECK_HEADERS([foo.h])
5904 AC_CHECK_HEADERS([bar.h], [], [],
5905 [#ifdef HAVE_FOO_H
5906 # include <foo.h>
5907 #endif
5909 @end verbatim
5911 The following variant generates smaller, faster @command{configure}
5912 files if you do not need the full power of @code{AC_CHECK_HEADERS}.
5914 @defmac AC_CHECK_HEADERS_ONCE (@var{header-file}@dots{})
5915 @acindex{CHECK_HEADERS_ONCE}
5916 @cvindex HAVE_@var{header}
5917 For each given system header file @var{header-file} in the
5918 blank-separated argument list that exists, define
5919 @code{HAVE_@var{header-file}} (in all capitals).
5920 This is a once-only variant of @code{AC_CHECK_HEADERS}.  It generates the
5921 checking code at most once, so that @command{configure} is smaller and
5922 faster; but the checks cannot be conditionalized and are always done once,
5923 early during the @command{configure} run.  Thus, this macro is only safe
5924 for checking headers that do not have prerequisites beyond what
5925 @code{AC_INCLUDES_DEFAULT} provides.
5926 @end defmac
5928 @node Declarations
5929 @section Declarations
5930 @cindex Declaration, checking
5932 The following macros check for the declaration of variables and
5933 functions.  If there is no macro specifically defined to check for a
5934 symbol you need, then you can use the general macros (@pxref{Generic
5935 Declarations}) or, for more complex tests, you may use
5936 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
5938 @menu
5939 * Particular Declarations::     Macros to check for certain declarations
5940 * Generic Declarations::        How to find other declarations
5941 @end menu
5943 @node Particular Declarations
5944 @subsection Particular Declaration Checks
5946 There are no specific macros for declarations.
5948 @node Generic Declarations
5949 @subsection Generic Declaration Checks
5951 These macros are used to find declarations not covered by the ``particular''
5952 test macros.
5954 @defmac AC_CHECK_DECL (@var{symbol}, @ovar{action-if-found}, @
5955   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5956 @acindex{CHECK_DECL}
5957 If @var{symbol} (a function, variable, or constant) is not declared in
5958 @var{includes} and a declaration is needed, run the shell commands
5959 @var{action-if-not-found}, otherwise @var{action-if-found}.
5960 @var{includes} is a series of include directives, defaulting to
5961 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5962 prior to the declaration under test.
5964 This macro actually tests whether @var{symbol} is defined as a macro or
5965 can be used as an r-value, not whether it is really declared, because it
5966 is much safer to avoid
5967 introducing extra declarations when they are not needed.
5968 @end defmac
5970 @anchor{AC_CHECK_DECLS}
5971 @defmac AC_CHECK_DECLS (@var{symbols}, @ovar{action-if-found}, @
5972   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
5973 @acindex{CHECK_DECLS}
5974 @cvindex HAVE_DECL_@var{symbol}
5975 For each of the @var{symbols} (@emph{comma}-separated list), define
5976 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
5977 @var{symbol} is declared, otherwise to @samp{0}.  If
5978 @var{action-if-not-found} is given, it is additional shell code to
5979 execute when one of the function declarations is needed, otherwise
5980 @var{action-if-found} is executed.
5982 @var{includes} is a series of include directives, defaulting to
5983 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
5984 prior to the declarations under test.
5986 This macro uses an M4 list as first argument:
5987 @example
5988 AC_CHECK_DECLS([strdup])
5989 AC_CHECK_DECLS([strlen])
5990 AC_CHECK_DECLS([malloc, realloc, calloc, free])
5991 AC_CHECK_DECLS([j0], [], [], [[#include <math.h>]])
5992 @end example
5994 Unlike the other @samp{AC_CHECK_*S} macros, when a @var{symbol} is not
5995 declared, @code{HAVE_DECL_@var{symbol}} is defined to @samp{0} instead
5996 of leaving @code{HAVE_DECL_@var{symbol}} undeclared.  When you are
5997 @emph{sure} that the check was performed, use
5998 @code{HAVE_DECL_@var{symbol}} in @code{#if}:
6000 @example
6001 #if !HAVE_DECL_SYMBOL
6002 extern char *symbol;
6003 #endif
6004 @end example
6006 @noindent
6007 If the test may have not been performed, however, because it is safer
6008 @emph{not} to declare a symbol than to use a declaration that conflicts
6009 with the system's one, you should use:
6011 @example
6012 #if defined HAVE_DECL_MALLOC && !HAVE_DECL_MALLOC
6013 void *malloc (size_t *s);
6014 #endif
6015 @end example
6017 @noindent
6018 You fall into the second category only in extreme situations: either
6019 your files may be used without being configured, or they are used during
6020 the configuration.  In most cases the traditional approach is enough.
6021 @end defmac
6023 @defmac AC_CHECK_DECLS_ONCE (@var{symbols})
6024 @acindex{CHECK_DECLS_ONCE}
6025 @cvindex HAVE_DECL_@var{symbol}
6026 For each of the @var{symbols} (@emph{comma}-separated list), define
6027 @code{HAVE_DECL_@var{symbol}} (in all capitals) to @samp{1} if
6028 @var{symbol} is declared in the default include files, otherwise to
6029 @samp{0}.  This is a once-only variant of @code{AC_CHECK_DECLS}.  It
6030 generates the checking code at most once, so that @command{configure} is
6031 smaller and faster; but the checks cannot be conditionalized and are
6032 always done once, early during the @command{configure} run.
6033 @end defmac
6036 @node Structures
6037 @section Structures
6038 @cindex Structure, checking
6040 The following macros check for the presence of certain members in C
6041 structures.  If there is no macro specifically defined to check for a
6042 member you need, then you can use the general structure-member macros
6043 (@pxref{Generic Structures}) or, for more complex tests, you may use
6044 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}).
6046 @menu
6047 * Particular Structures::       Macros to check for certain structure members
6048 * Generic Structures::          How to find other structure members
6049 @end menu
6051 @node Particular Structures
6052 @subsection Particular Structure Checks
6054 The following macros check for certain structures or structure members.
6056 @defmac AC_STRUCT_DIRENT_D_INO
6057 @acindex{STRUCT_DIRENT_D_INO}
6058 @cvindex HAVE_STRUCT_DIRENT_D_INO
6059 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6060 Headers}).  Then, if @code{struct dirent} contains a @code{d_ino}
6061 member, define @code{HAVE_STRUCT_DIRENT_D_INO}.
6063 @code{HAVE_STRUCT_DIRENT_D_INO} indicates only the presence of
6064 @code{d_ino}, not whether its contents are always reliable.
6065 Traditionally, a zero @code{d_ino} indicated a deleted directory entry,
6066 though current systems hide this detail from the user and never return
6067 zero @code{d_ino} values.
6068 Many current systems report an incorrect @code{d_ino} for a directory
6069 entry that is a mount point.
6070 @end defmac
6072 @defmac AC_STRUCT_DIRENT_D_TYPE
6073 @acindex{STRUCT_DIRENT_D_TYPE}
6074 @cvindex HAVE_STRUCT_DIRENT_D_TYPE
6075 Perform all the actions of @code{AC_HEADER_DIRENT} (@pxref{Particular
6076 Headers}).  Then, if @code{struct dirent} contains a @code{d_type}
6077 member, define @code{HAVE_STRUCT_DIRENT_D_TYPE}.
6078 @end defmac
6080 @anchor{AC_STRUCT_ST_BLOCKS}
6081 @defmac AC_STRUCT_ST_BLOCKS
6082 @acindex{STRUCT_ST_BLOCKS}
6083 @cvindex HAVE_STRUCT_STAT_ST_BLOCKS
6084 @cvindex HAVE_ST_BLOCKS
6085 @ovindex LIBOBJS
6086 If @code{struct stat} contains an @code{st_blocks} member, define
6087 @code{HAVE_STRUCT_STAT_ST_BLOCKS}.  Otherwise, require an
6088 @code{AC_LIBOBJ} replacement of @samp{fileblocks}.  The former name,
6089 @code{HAVE_ST_BLOCKS} is to be avoided, as its support will cease in the
6090 future.
6091 @end defmac
6093 @defmac AC_STRUCT_TM
6094 @acindex{STRUCT_TM}
6095 @cvindex TM_IN_SYS_TIME
6096 @hdrindex{time.h}
6097 @hdrindex{sys/time.h}
6098 If @file{time.h} does not define @code{struct tm}, define
6099 @code{TM_IN_SYS_TIME}, which means that including @file{sys/time.h}
6100 had better define @code{struct tm}.
6102 This macro is obsolescent, as @file{time.h} defines @code{struct tm} in
6103 current systems.  New programs need not use this macro.
6104 @end defmac
6106 @anchor{AC_STRUCT_TIMEZONE}
6107 @defmac AC_STRUCT_TIMEZONE
6108 @acindex{STRUCT_TIMEZONE}
6109 @cvindex HAVE_DECL_TZNAME
6110 @cvindex HAVE_STRUCT_TM_TM_ZONE
6111 @cvindex HAVE_TM_ZONE
6112 @cvindex HAVE_TZNAME
6113 Figure out how to get the current timezone.  If @code{struct tm} has a
6114 @code{tm_zone} member, define @code{HAVE_STRUCT_TM_TM_ZONE} (and the
6115 obsoleted @code{HAVE_TM_ZONE}).  Otherwise, if the external array
6116 @code{tzname} is found, define @code{HAVE_TZNAME}; if it is declared,
6117 define @code{HAVE_DECL_TZNAME}.
6118 @end defmac
6120 @node Generic Structures
6121 @subsection Generic Structure Checks
6123 These macros are used to find structure members not covered by the
6124 ``particular'' test macros.
6126 @defmac AC_CHECK_MEMBER (@var{aggregate}.@var{member}, @
6127   @ovar{action-if-found}, @ovar{action-if-not-found}, @
6128   @dvar{includes, AC_INCLUDES_DEFAULT})
6129 @acindex{CHECK_MEMBER}
6130 Check whether @var{member} is a member of the aggregate @var{aggregate}.
6131 If no @var{includes} are specified, the default includes are used
6132 (@pxref{Default Includes}).
6134 @example
6135 AC_CHECK_MEMBER([struct passwd.pw_gecos], [],
6136                 [AC_MSG_ERROR([We need `passwd.pw_gecos'!])],
6137                 [[#include <pwd.h>]])
6138 @end example
6140 You can use this macro for submembers:
6142 @example
6143 AC_CHECK_MEMBER(struct top.middle.bot)
6144 @end example
6145 @end defmac
6147 @anchor{AC_CHECK_MEMBERS}
6148 @defmac AC_CHECK_MEMBERS (@var{members}, @ovar{action-if-found}, @
6149   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6150 @acindex{CHECK_MEMBERS}
6151 @cvindex HAVE_@var{aggregate}_@var{member}
6152 Check for the existence of each @samp{@var{aggregate}.@var{member}} of
6153 @var{members} using the previous macro.  When @var{member} belongs to
6154 @var{aggregate}, define @code{HAVE_@var{aggregate}_@var{member}} (in all
6155 capitals, with spaces and dots replaced by underscores).  If
6156 @var{action-if-found} is given, it is executed for each of the found
6157 members.  If @var{action-if-not-found} is given, it is executed for each
6158 of the members that could not be found.
6160 @var{includes} is a series of include directives, defaulting to
6161 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6162 prior to the members under test.
6164 This macro uses M4 lists:
6165 @example
6166 AC_CHECK_MEMBERS([struct stat.st_rdev, struct stat.st_blksize])
6167 @end example
6168 @end defmac
6171 @node Types
6172 @section Types
6173 @cindex Types
6174 @cindex C types
6176 The following macros check for C types, either builtin or typedefs.  If
6177 there is no macro specifically defined to check for a type you need, and
6178 you don't need to check for any special properties of it, then you can
6179 use a general type-check macro.
6181 @menu
6182 * Particular Types::            Special handling to find certain types
6183 * Generic Types::               How to find other types
6184 @end menu
6186 @node Particular Types
6187 @subsection Particular Type Checks
6189 @hdrindex{sys/types.h}
6190 @hdrindex{stdlib.h}
6191 @hdrindex{stdint.h}
6192 @hdrindex{inttypes.h}
6193 These macros check for particular C types in @file{sys/types.h},
6194 @file{stdlib.h}, @file{stdint.h}, @file{inttypes.h} and others, if they
6195 exist.
6197 The Gnulib @code{stdint} module is an alternate way to define many of
6198 these symbols; it is useful if you prefer your code to assume a
6199 C99-or-better environment.  @xref{Gnulib}.
6201 @anchor{AC_TYPE_GETGROUPS}
6202 @defmac AC_TYPE_GETGROUPS
6203 @acindex{TYPE_GETGROUPS}
6204 @cvindex GETGROUPS_T
6205 Define @code{GETGROUPS_T} to be whichever of @code{gid_t} or @code{int}
6206 is the base type of the array argument to @code{getgroups}.
6207 @end defmac
6209 @defmac AC_TYPE_INT8_T
6210 @acindex{TYPE_INT8_T}
6211 @cvindex HAVE_INT8_T
6212 @cvindex int8_t
6213 If @file{stdint.h} or @file{inttypes.h} does not define the type
6214 @code{int8_t}, define @code{int8_t} to a signed
6215 integer type that is exactly 8 bits wide and that uses two's complement
6216 representation, if such a type exists.
6217 If you are worried about porting to hosts that lack such a type, you can
6218 use the results of this macro in C89-or-later code as follows:
6220 @example
6221 #if HAVE_STDINT_H
6222 # include <stdint.h>
6223 #endif
6224 #if defined INT8_MAX || defined int8_t
6225  @emph{code using int8_t}
6226 #else
6227  @emph{complicated alternative using >8-bit 'signed char'}
6228 #endif
6229 @end example
6230 @end defmac
6232 @defmac AC_TYPE_INT16_T
6233 @acindex{TYPE_INT16_T}
6234 @cvindex HAVE_INT16_T
6235 @cvindex int16_t
6236 This is like @code{AC_TYPE_INT8_T}, except for 16-bit integers.
6237 @end defmac
6239 @defmac AC_TYPE_INT32_T
6240 @acindex{TYPE_INT32_T}
6241 @cvindex HAVE_INT32_T
6242 @cvindex int32_t
6243 This is like @code{AC_TYPE_INT8_T}, except for 32-bit integers.
6244 @end defmac
6246 @defmac AC_TYPE_INT64_T
6247 @acindex{TYPE_INT64_T}
6248 @cvindex HAVE_INT64_T
6249 @cvindex int64_t
6250 This is like @code{AC_TYPE_INT8_T}, except for 64-bit integers.
6251 @end defmac
6253 @defmac AC_TYPE_INTMAX_T
6254 @acindex{TYPE_INTMAX_T}
6255 @cvindex HAVE_INTMAX_T
6256 @cvindex intmax_t
6257 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intmax_t},
6258 define @code{HAVE_INTMAX_T}.  Otherwise, define @code{intmax_t} to the
6259 widest signed integer type.
6260 @end defmac
6262 @defmac AC_TYPE_INTPTR_T
6263 @acindex{TYPE_INTPTR_T}
6264 @cvindex HAVE_INTPTR_T
6265 @cvindex intptr_t
6266 If @file{stdint.h} or @file{inttypes.h} defines the type @code{intptr_t},
6267 define @code{HAVE_INTPTR_T}.  Otherwise, define @code{intptr_t} to a
6268 signed integer type wide enough to hold a pointer, if such a type
6269 exists.
6270 @end defmac
6272 @defmac AC_TYPE_LONG_DOUBLE
6273 @acindex{TYPE_LONG_DOUBLE}
6274 @cvindex HAVE_LONG_DOUBLE
6275 If the C compiler supports a working @code{long double} type, define
6276 @code{HAVE_LONG_DOUBLE}.  The @code{long double} type might have the
6277 same range and precision as @code{double}.
6279 This macro is obsolescent, as current C compilers support @code{long
6280 double}.  New programs need not use this macro.
6281 @end defmac
6283 @defmac AC_TYPE_LONG_DOUBLE_WIDER
6284 @acindex{TYPE_LONG_DOUBLE_WIDER}
6285 @cvindex HAVE_LONG_DOUBLE_WIDER
6286 If the C compiler supports a working @code{long double} type with more
6287 range or precision than the @code{double} type, define
6288 @code{HAVE_LONG_DOUBLE_WIDER}.
6289 @end defmac
6291 @defmac AC_TYPE_LONG_LONG_INT
6292 @acindex{TYPE_LONG_LONG_INT}
6293 @cvindex HAVE_LONG_LONG_INT
6294 If the C compiler supports a working @code{long long int} type, define
6295 @code{HAVE_LONG_LONG_INT}.  However, this test does not test
6296 @code{long long int} values in preprocessor @code{#if} expressions,
6297 because too many compilers mishandle such expressions.
6298 @xref{Preprocessor Arithmetic}.
6299 @end defmac
6301 @defmac AC_TYPE_MBSTATE_T
6302 @acindex{TYPE_MBSTATE_T}
6303 @cvindex mbstate_t
6304 @hdrindex{wchar.h}
6305 Define @code{HAVE_MBSTATE_T} if @code{<wchar.h>} declares the
6306 @code{mbstate_t} type.  Also, define @code{mbstate_t} to be a type if
6307 @code{<wchar.h>} does not declare it.
6308 @end defmac
6310 @anchor{AC_TYPE_MODE_T}
6311 @defmac AC_TYPE_MODE_T
6312 @acindex{TYPE_MODE_T}
6313 @cvindex mode_t
6314 Define @code{mode_t} to a suitable type, if standard headers do not
6315 define it.
6316 @end defmac
6318 @anchor{AC_TYPE_OFF_T}
6319 @defmac AC_TYPE_OFF_T
6320 @acindex{TYPE_OFF_T}
6321 @cvindex off_t
6322 Define @code{off_t} to a suitable type, if standard headers do not
6323 define it.
6324 @end defmac
6326 @anchor{AC_TYPE_PID_T}
6327 @defmac AC_TYPE_PID_T
6328 @acindex{TYPE_PID_T}
6329 @cvindex pid_t
6330 Define @code{pid_t} to a suitable type, if standard headers do not
6331 define it.
6332 @end defmac
6334 @anchor{AC_TYPE_SIZE_T}
6335 @defmac AC_TYPE_SIZE_T
6336 @acindex{TYPE_SIZE_T}
6337 @cvindex size_t
6338 Define @code{size_t} to a suitable type, if standard headers do not
6339 define it.
6340 @end defmac
6342 @defmac AC_TYPE_SSIZE_T
6343 @acindex{TYPE_SSIZE_T}
6344 @cvindex ssize_t
6345 Define @code{ssize_t} to a suitable type, if standard headers do not
6346 define it.
6347 @end defmac
6349 @anchor{AC_TYPE_UID_T}
6350 @defmac AC_TYPE_UID_T
6351 @acindex{TYPE_UID_T}
6352 @cvindex uid_t
6353 @cvindex gid_t
6354 Define @code{uid_t} and @code{gid_t} to suitable types, if standard
6355 headers do not define them.
6356 @end defmac
6358 @defmac AC_TYPE_UINT8_T
6359 @acindex{TYPE_UINT8_T}
6360 @cvindex HAVE_UINT8_T
6361 @cvindex uint8_t
6362 If @file{stdint.h} or @file{inttypes.h} does not define the type
6363 @code{uint8_t}, define @code{uint8_t} to an
6364 unsigned integer type that is exactly 8 bits wide, if such a type
6365 exists.
6366 This is like @code{AC_TYPE_INT8_T}, except for unsigned integers.
6367 @end defmac
6369 @defmac AC_TYPE_UINT16_T
6370 @acindex{TYPE_UINT16_T}
6371 @cvindex HAVE_UINT16_T
6372 @cvindex uint16_t
6373 This is like @code{AC_TYPE_UINT8_T}, except for 16-bit integers.
6374 @end defmac
6376 @defmac AC_TYPE_UINT32_T
6377 @acindex{TYPE_UINT32_T}
6378 @cvindex HAVE_UINT32_T
6379 @cvindex uint32_t
6380 This is like @code{AC_TYPE_UINT8_T}, except for 32-bit integers.
6381 @end defmac
6383 @defmac AC_TYPE_UINT64_T
6384 @acindex{TYPE_UINT64_T}
6385 @cvindex HAVE_UINT64_T
6386 @cvindex uint64_t
6387 This is like @code{AC_TYPE_UINT8_T}, except for 64-bit integers.
6388 @end defmac
6390 @defmac AC_TYPE_UINTMAX_T
6391 @acindex{TYPE_UINTMAX_T}
6392 @cvindex HAVE_UINTMAX_T
6393 @cvindex uintmax_t
6394 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintmax_t},
6395 define @code{HAVE_UINTMAX_T}.  Otherwise, define @code{uintmax_t} to the
6396 widest unsigned integer type.
6397 @end defmac
6399 @defmac AC_TYPE_UINTPTR_T
6400 @acindex{TYPE_UINTPTR_T}
6401 @cvindex HAVE_UINTPTR_T
6402 @cvindex uintptr_t
6403 If @file{stdint.h} or @file{inttypes.h} defines the type @code{uintptr_t},
6404 define @code{HAVE_UINTPTR_T}.  Otherwise, define @code{uintptr_t} to an
6405 unsigned integer type wide enough to hold a pointer, if such a type
6406 exists.
6407 @end defmac
6409 @defmac AC_TYPE_UNSIGNED_LONG_LONG_INT
6410 @acindex{TYPE_UNSIGNED_LONG_LONG_INT}
6411 @cvindex HAVE_UNSIGNED_LONG_LONG_INT
6412 If the C compiler supports a working @code{unsigned long long int} type,
6413 define @code{HAVE_UNSIGNED_LONG_LONG_INT}.  However, this test does not test
6414 @code{unsigned long long int} values in preprocessor @code{#if} expressions,
6415 because too many compilers mishandle such expressions.
6416 @xref{Preprocessor Arithmetic}.
6417 @end defmac
6419 @node Generic Types
6420 @subsection Generic Type Checks
6422 These macros are used to check for types not covered by the ``particular''
6423 test macros.
6425 @defmac AC_CHECK_TYPE (@var{type}, @ovar{action-if-found}, @
6426   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6427 @acindex{CHECK_TYPE}
6428 Check whether @var{type} is defined.  It may be a compiler builtin type
6429 or defined by the @var{includes}.  @var{includes} is a series of include
6430 directives, defaulting to @code{AC_INCLUDES_DEFAULT} (@pxref{Default
6431 Includes}), which are used prior to the type under test.
6433 In C, @var{type} must be a type-name, so that the expression @samp{sizeof
6434 (@var{type})} is valid (but @samp{sizeof ((@var{type}))} is not).  The
6435 same test is applied when compiling for C++, which means that in C++
6436 @var{type} should be a type-id and should not be an anonymous
6437 @samp{struct} or @samp{union}.
6438 @end defmac
6441 @defmac AC_CHECK_TYPES (@var{types}, @ovar{action-if-found}, @
6442   @ovar{action-if-not-found}, @dvar{includes, AC_INCLUDES_DEFAULT})
6443 @acindex{CHECK_TYPES}
6444 @cvindex HAVE_@var{type}
6445 For each @var{type} of the @var{types} that is defined, define
6446 @code{HAVE_@var{type}} (in all capitals).  Each @var{type} must follow
6447 the rules of @code{AC_CHECK_TYPE}.  If no @var{includes} are
6448 specified, the default includes are used (@pxref{Default Includes}).  If
6449 @var{action-if-found} is given, it is additional shell code to execute
6450 when one of the types is found.  If @var{action-if-not-found} is given,
6451 it is executed when one of the types is not found.
6453 This macro uses M4 lists:
6454 @example
6455 AC_CHECK_TYPES([ptrdiff_t])
6456 AC_CHECK_TYPES([unsigned long long int, uintmax_t])
6457 AC_CHECK_TYPES([float_t], [], [], [[#include <math.h>]])
6458 @end example
6460 @end defmac
6462 Autoconf, up to 2.13, used to provide to another version of
6463 @code{AC_CHECK_TYPE}, broken by design.  In order to keep backward
6464 compatibility, a simple heuristic, quite safe but not totally, is
6465 implemented.  In case of doubt, read the documentation of the former
6466 @code{AC_CHECK_TYPE}, see @ref{Obsolete Macros}.
6469 @node Compilers and Preprocessors
6470 @section Compilers and Preprocessors
6471 @cindex Compilers
6472 @cindex Preprocessors
6474 @ovindex EXEEXT
6475 All the tests for compilers (@code{AC_PROG_CC}, @code{AC_PROG_CXX},
6476 @code{AC_PROG_F77}) define the output variable @code{EXEEXT} based on
6477 the output of the compiler, typically to the empty string if
6478 Posix and @samp{.exe} if a @acronym{DOS} variant.
6480 @ovindex OBJEXT
6481 They also define the output variable @code{OBJEXT} based on the
6482 output of the compiler, after @file{.c} files have been excluded, typically
6483 to @samp{o} if Posix, @samp{obj} if a @acronym{DOS} variant.
6485 If the compiler being used does not produce executables, the tests fail.  If
6486 the executables can't be run, and cross-compilation is not enabled, they
6487 fail too.  @xref{Manual Configuration}, for more on support for cross
6488 compiling.
6490 @menu
6491 * Specific Compiler Characteristics::  Some portability issues
6492 * Generic Compiler Characteristics::  Language independent tests and features
6493 * C Compiler::                  Checking its characteristics
6494 * C++ Compiler::                Likewise
6495 * Objective C Compiler::        Likewise
6496 * Erlang Compiler and Interpreter::  Likewise
6497 * Fortran Compiler::            Likewise
6498 @end menu
6500 @node Specific Compiler Characteristics
6501 @subsection Specific Compiler Characteristics
6503 Some compilers exhibit different behaviors.
6505 @table @asis
6506 @item Static/Dynamic Expressions
6507 Autoconf relies on a trick to extract one bit of information from the C
6508 compiler: using negative array sizes.  For instance the following
6509 excerpt of a C source demonstrates how to test whether @samp{int} objects are 4
6510 bytes wide:
6512 @example
6513 static int test_array[sizeof (int) == 4 ? 1 : -1];
6514 @end example
6516 @noindent
6517 To our knowledge, there is a single compiler that does not support this
6518 trick: the @acronym{HP} C compilers (the real ones, not only the
6519 ``bundled'') on @acronym{HP-UX} 11.00.
6520 They incorrectly reject the above program with the diagnostic
6521 ``Variable-length arrays cannot have static storage.''
6522 This bug comes from @acronym{HP} compilers' mishandling of @code{sizeof (int)},
6523 not from the @code{? 1 : -1}, and
6524 Autoconf works around this problem by casting @code{sizeof (int)} to
6525 @code{long int} before comparing it.
6526 @end table
6528 @node Generic Compiler Characteristics
6529 @subsection Generic Compiler Characteristics
6531 @anchor{AC_CHECK_SIZEOF}
6532 @defmac AC_CHECK_SIZEOF (@var{type-or-expr}, @ovar{unused}, @
6533   @dvar{includes, AC_INCLUDES_DEFAULT})
6534 @acindex{CHECK_SIZEOF}
6535 @cvindex SIZEOF_@var{type-or-expr}
6536 Define @code{SIZEOF_@var{type-or-expr}} (@pxref{Standard Symbols}) to be
6537 the size in bytes of @var{type-or-expr}, which may be either a type or
6538 an expression returning a value that has a size.  If the expression
6539 @samp{sizeof (@var{type-or-expr})} is invalid, the result is 0.
6540 @var{includes} is a series of include directives, defaulting to
6541 @code{AC_INCLUDES_DEFAULT} (@pxref{Default Includes}), which are used
6542 prior to the expression under test.
6544 This macro now works even when cross-compiling.  The @var{unused}
6545 argument was used when cross-compiling.
6547 For example, the call
6549 @example
6550 AC_CHECK_SIZEOF([int *])
6551 @end example
6553 @noindent
6554 defines @code{SIZEOF_INT_P} to be 8 on DEC Alpha AXP systems.
6555 @end defmac
6557 @defmac AC_CHECK_ALIGNOF (@var{type}, @dvar{includes, AC_INCLUDES_DEFAULT})
6558 @acindex{CHECK_ALIGNOF}
6559 @cvindex ALIGNOF_@var{type}
6560 Define @code{ALIGNOF_@var{type}} (@pxref{Standard Symbols}) to be the
6561 alignment in bytes of @var{type}.  @samp{@var{type} y;} must be valid as
6562 a structure member declaration.  If @samp{type} is unknown, the result
6563 is 0.  If no @var{includes} are specified, the default includes are used
6564 (@pxref{Default Includes}).
6565 @end defmac
6567 @defmac AC_COMPUTE_INT (@var{var}, @var{expression}, @
6568   @dvar{includes, AC_INCLUDES_DEFAULT}, @ovar{action-if-fails})
6569 @acindex{COMPUTE_INT}
6570 Store into the shell variable @var{var} the value of the integer
6571 @var{expression}.  The
6572 value should fit in an initializer in a C variable of type @code{signed
6573 long}.  To support cross compilation (in which case, the macro only works on
6574 hosts that use twos-complement arithmetic), it should be possible to evaluate
6575 the expression at compile-time.  If no @var{includes} are specified, the
6576 default includes are used (@pxref{Default Includes}).
6578 Execute @var{action-if-fails} if the value cannot be determined correctly.
6579 @end defmac
6581 @defmac AC_LANG_WERROR
6582 @acindex{LANG_WERROR}
6583 Normally Autoconf ignores warnings generated by the compiler, linker, and
6584 preprocessor.  If this macro is used, warnings count as fatal
6585 errors for the current language.  This macro is useful when the
6586 results of configuration are used where warnings are unacceptable; for
6587 instance, if parts of a program are built with the @acronym{GCC}
6588 @option{-Werror}
6589 option.  If the whole program is built using @option{-Werror} it is
6590 often simpler to put @option{-Werror} in the compiler flags (@code{CFLAGS},
6591 etc.).
6592 @end defmac
6594 @defmac AC_OPENMP
6595 @acindex{OPENMP}
6596 @cvindex _OPENMP
6597 @ovindex OPENMP_CFLAGS
6598 @ovindex OPENMP_CXXFLAGS
6599 @ovindex OPENMP_FFLAGS
6600 @ovindex OPENMP_FCFLAGS
6601 OpenMP (@url{http://@/www.openmp.org/}) specifies extensions of C, C++,
6602 and Fortran that simplify optimization of shared memory parallelism,
6603 which is a common problem on multicore CPUs.
6605 If the current language is C, the macro @code{AC_OPENMP} sets the
6606 variable @code{OPENMP_CFLAGS} to the C compiler flags needed for
6607 supporting OpenMP@.  @code{OPENMP_CFLAGS} is set to empty if the
6608 compiler already supports OpenMP, if it has no way to activate OpenMP
6609 support, or if the user rejects OpenMP support by invoking
6610 @samp{configure} with the @samp{--disable-openmp} option.
6612 @code{OPENMP_CFLAGS} needs to be used when compiling programs, when
6613 preprocessing program source, and when linking programs.  Therefore you
6614 need to add @code{$(OPENMP_CFLAGS)} to the @code{CFLAGS} of C programs
6615 that use OpenMP@.  If you preprocess OpenMP-specific C code, you also
6616 need to add @code{$(OPENMP_CFLAGS)} to @code{CPPFLAGS}.  The presence of
6617 OpenMP support is revealed at compile time by the preprocessor macro
6618 @code{_OPENMP}.
6620 Linking a program with @code{OPENMP_CFLAGS} typically adds one more
6621 shared library to the program's dependencies, so its use is recommended
6622 only on programs that actually require OpenMP.
6624 If the current language is C++, @code{AC_OPENMP} sets the variable
6625 @code{OPENMP_CXXFLAGS}, suitably for the C++ compiler.  The same remarks
6626 hold as for C.
6628 If the current language is Fortran 77 or Fortran, @code{AC_OPENMP} sets
6629 the variable @code{OPENMP_FFLAGS} or @code{OPENMP_FCFLAGS},
6630 respectively.  Similar remarks as for C hold, except that
6631 @code{CPPFLAGS} is not used for Fortran, and no preprocessor macro
6632 signals OpenMP support.
6634 For portability, it is best to avoid spaces between @samp{#} and
6635 @samp{pragma omp}.  That is, write @samp{#pragma omp}, not
6636 @samp{# pragma omp}.  The Sun WorkShop 6.2 C compiler chokes on the
6637 latter.
6638 @end defmac
6640 @node C Compiler
6641 @subsection C Compiler Characteristics
6643 The following macros provide ways to find and exercise a C Compiler.
6644 There are a few constructs that ought to be avoided, but do not deserve
6645 being checked for, since they can easily be worked around.
6647 @table @asis
6648 @item Don't use lines containing solitary backslashes
6649 They tickle a bug in the @acronym{HP-UX} C compiler (checked on
6650 @acronym{HP-UX} 10.20,
6651 11.00, and 11i).  When given the following source:
6653 @example
6654 #ifdef __STDC__
6656 * A comment with backslash-newlines in it.  %@{ %@} *\
6659 char str[] = "\\
6660 " A string with backslash-newlines in it %@{ %@} \\
6662 char apostrophe = '\\
6666 #endif
6667 @end example
6669 @noindent
6670 the compiler incorrectly fails with the diagnostics ``Non-terminating
6671 comment at end of file'' and ``Missing @samp{#endif} at end of file.''
6672 Removing the lines with solitary backslashes solves the problem.
6674 @item Don't compile several files at once if output matters to you
6675 Some compilers, such as @acronym{HP}'s, report names of files being
6676 compiled when given more than one file operand.  For instance:
6678 @example
6679 $ @kbd{cc a.c b.c}
6680 a.c:
6681 b.c:
6682 @end example
6684 @noindent
6685 This can cause problems if you observe the output of the compiler to
6686 detect failures.  Invoking @samp{cc -c a.c && cc -c b.c && cc -o c a.o
6687 b.o} solves the issue.
6689 @item Don't rely on @code{#error} failing
6690 The @sc{irix} C compiler does not fail when #error is preprocessed; it
6691 simply emits a diagnostic and continues, exiting successfully.  So,
6692 instead of an error directive like @code{#error "Unsupported word size"}
6693 it is more portable to use an invalid directive like @code{#Unsupported
6694 word size} in Autoconf tests.  In ordinary source code, @code{#error} is
6695 OK, since installers with inadequate compilers like @sc{irix} can simply
6696 examine these compilers' diagnostic output.
6698 @item Don't rely on correct @code{#line} support
6699 On Solaris, @command{c89} (at least Sun C 5.3 through 5.8)
6700 diagnoses @code{#line} directives whose line
6701 numbers are greater than 32767.  Nothing in Posix
6702 makes this invalid.  That is why Autoconf stopped issuing
6703 @code{#line} directives.
6704 @end table
6706 @defmac AC_PROG_CC (@ovar{compiler-search-list})
6707 @acindex{PROG_CC}
6708 @ovindex CC
6709 @ovindex CFLAGS
6710 Determine a C compiler to use.  If @code{CC} is not already set in the
6711 environment, check for @code{gcc} and @code{cc}, then for other C
6712 compilers.  Set output variable @code{CC} to the name of the compiler
6713 found.
6715 This macro may, however, be invoked with an optional first argument
6716 which, if specified, must be a blank-separated list of C compilers to
6717 search for.  This just gives the user an opportunity to specify an
6718 alternative search list for the C compiler.  For example, if you didn't
6719 like the default order, then you could invoke @code{AC_PROG_CC} like
6720 this:
6722 @example
6723 AC_PROG_CC([gcc cl cc])
6724 @end example
6726 If the C compiler does not handle function prototypes correctly by
6727 default, try to add an option to output variable @code{CC} to make it
6728 so.  This macro tries various options that select standard-conformance
6729 modes on various systems.
6731 After calling this macro you can check whether the C compiler has been
6732 set to accept @acronym{ANSI} C89 (@acronym{ISO} C90); if not, the shell
6733 variable
6734 @code{ac_cv_prog_cc_c89} is set to @samp{no}.  See also
6735 @code{AC_C_PROTOTYPES} below.
6737 If using the @acronym{GNU} C compiler, set shell variable @code{GCC} to
6738 @samp{yes}.  If output variable @code{CFLAGS} was not already set, set
6739 it to @option{-g -O2} for the @acronym{GNU} C compiler (@option{-O2} on systems
6740 where @acronym{GCC} does not accept @option{-g}), or @option{-g} for
6741 other compilers.
6742 @end defmac
6744 @anchor{AC_PROG_CC_C_O}
6745 @defmac AC_PROG_CC_C_O
6746 @acindex{PROG_CC_C_O}
6747 @cvindex NO_MINUS_C_MINUS_O
6748 If the C compiler does not accept the @option{-c} and @option{-o} options
6749 simultaneously, define @code{NO_MINUS_C_MINUS_O}.  This macro actually
6750 tests both the compiler found by @code{AC_PROG_CC}, and, if different,
6751 the first @code{cc} in the path.  The test fails if one fails.  This
6752 macro was created for @acronym{GNU} Make to choose the default C compilation
6753 rule.
6754 @end defmac
6757 @defmac AC_PROG_CPP
6758 @acindex{PROG_CPP}
6759 @ovindex CPP
6760 Set output variable @code{CPP} to a command that runs the
6761 C preprocessor.  If @samp{$CC -E} doesn't work, @file{/lib/cpp} is used.
6762 It is only portable to run @code{CPP} on files with a @file{.c}
6763 extension.
6765 Some preprocessors don't indicate missing include files by the error
6766 status.  For such preprocessors an internal variable is set that causes
6767 other macros to check the standard error from the preprocessor and
6768 consider the test failed if any warnings have been reported.
6769 For most preprocessors, though, warnings do not cause include-file
6770 tests to fail unless @code{AC_PROG_CPP_WERROR} is also specified.
6771 @end defmac
6773 @defmac AC_PROG_CPP_WERROR
6774 @acindex{PROG_CPP_WERROR}
6775 @ovindex CPP
6776 This acts like @code{AC_PROG_CPP}, except it treats warnings from the
6777 preprocessor as errors even if the preprocessor exit status indicates
6778 success.  This is useful for avoiding headers that generate mandatory
6779 warnings, such as deprecation notices.
6780 @end defmac
6783 The following macros check for C compiler or machine architecture
6784 features.  To check for characteristics not listed here, use
6785 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
6786 @code{AC_RUN_IFELSE} (@pxref{Runtime}).
6788 @defmac AC_PROG_CC_STDC
6789 @acindex{PROG_CC_STDC}
6790 If the C compiler cannot compile @acronym{ISO} Standard C (currently
6791 C99), try to add an option to output variable @code{CC} to make it work.
6792 If the compiler does not support C99, fall back to supporting
6793 @acronym{ANSI} C89 (@acronym{ISO} C90).
6795 After calling this macro you can check whether the C compiler has been
6796 set to accept Standard C; if not, the shell variable
6797 @code{ac_cv_prog_cc_stdc} is set to @samp{no}.
6798 @end defmac
6800 @defmac AC_PROG_CC_C89
6801 @acindex{PROG_CC_C89}
6802 If the C compiler is not in @acronym{ANSI} C89 (@acronym{ISO} C90) mode by
6803 default, try to add an option to output variable @code{CC} to make it
6804 so.  This macro tries various options that select @acronym{ANSI} C89 on
6805 some system or another.  It considers the compiler to be in
6806 @acronym{ANSI} C89 mode if it handles function prototypes correctly.
6808 After calling this macro you can check whether the C compiler has been
6809 set to accept @acronym{ANSI} C89; if not, the shell variable
6810 @code{ac_cv_prog_cc_c89} is set to @samp{no}.
6812 This macro is called automatically by @code{AC_PROG_CC}.
6813 @end defmac
6815 @defmac AC_PROG_CC_C99
6816 @acindex{PROG_CC_C99}
6817 If the C compiler is not in C99 mode by default, try to add an
6818 option to output variable @code{CC} to make it so.  This macro tries
6819 various options that select C99 on some system or another.  It
6820 considers the compiler to be in C99 mode if it handles @code{_Bool},
6821 @code{//} comments, flexible array members, @code{inline}, signed and
6822 unsigned @code{long long int}, mixed code and declarations, named
6823 initialization of structs,
6824 @code{restrict}, @code{va_copy}, varargs macros, variable declarations
6825 in @code{for} loops, and variable length arrays.
6827 After calling this macro you can check whether the C compiler has been
6828 set to accept C99; if not, the shell variable
6829 @code{ac_cv_prog_cc_c99} is set to @samp{no}.
6830 @end defmac
6832 @defmac AC_C_BACKSLASH_A
6833 @acindex{C_BACKSLASH_A}
6834 @cvindex HAVE_C_BACKSLASH_A
6835 Define @samp{HAVE_C_BACKSLASH_A} to 1 if the C compiler understands
6836 @samp{\a}.
6838 This macro is obsolescent, as current C compilers understand @samp{\a}.
6839 New programs need not use this macro.
6840 @end defmac
6842 @anchor{AC_C_BIGENDIAN}
6843 @defmac AC_C_BIGENDIAN (@ovar{action-if-true}, @ovar{action-if-false}, @
6844   @ovar{action-if-unknown}, @ovar{action-if-universal})
6845 @acindex{C_BIGENDIAN}
6846 @cvindex WORDS_BIGENDIAN
6847 @cindex Endianness
6848 If words are stored with the most significant byte first (like Motorola
6849 and SPARC CPUs), execute @var{action-if-true}.  If words are stored with
6850 the least significant byte first (like Intel and VAX CPUs), execute
6851 @var{action-if-false}.
6853 This macro runs a test-case if endianness cannot be determined from the
6854 system header files.  When cross-compiling, the test-case is not run but
6855 grep'ed for some magic values.  @var{action-if-unknown} is executed if
6856 the latter case fails to determine the byte sex of the host system.
6858 In some cases a single run of a compiler can generate code for multiple
6859 architectures.  This can happen, for example, when generating Mac OS X
6860 universal binary files, which work on both PowerPC and Intel
6861 architectures.  In this case, the different variants might be for
6862 different architectures whose endiannesses differ.  If
6863 @command{configure} detects this, it executes @var{action-if-universal}
6864 instead of @var{action-if-unknown}.
6866 The default for @var{action-if-true} is to define
6867 @samp{WORDS_BIGENDIAN}.  The default for @var{action-if-false} is to do
6868 nothing.  The default for @var{action-if-unknown} is to
6869 abort configure and tell the installer how to bypass this test.
6870 And finally, the default for @var{action-if-universal} is to ensure that
6871 @samp{WORDS_BIGENDIAN} is defined if and only if a universal build is
6872 detected and the current code is big-endian; this default works only if
6873 @command{autoheader} is used (@pxref{autoheader Invocation}).
6875 If you use this macro without specifying @var{action-if-universal}, you
6876 should also use @code{AC_CONFIG_HEADERS}; otherwise
6877 @samp{WORDS_BIGENDIAN} may be set incorrectly for Mac OS X universal
6878 binary files.
6879 @end defmac
6881 @anchor{AC_C_CONST}
6882 @defmac AC_C_CONST
6883 @acindex{C_CONST}
6884 @cvindex const
6885 If the C compiler does not fully support the @code{const} keyword,
6886 define @code{const} to be empty.  Some C compilers that do
6887 not define @code{__STDC__} do support @code{const}; some compilers that
6888 define @code{__STDC__} do not completely support @code{const}.  Programs
6889 can simply use @code{const} as if every C compiler supported it; for
6890 those that don't, the makefile or configuration header file
6891 defines it as empty.
6893 Occasionally installers use a C++ compiler to compile C code, typically
6894 because they lack a C compiler.  This causes problems with @code{const},
6895 because C and C++ treat @code{const} differently.  For example:
6897 @example
6898 const int foo;
6899 @end example
6901 @noindent
6902 is valid in C but not in C++.  These differences unfortunately cannot be
6903 papered over by defining @code{const} to be empty.
6905 If @command{autoconf} detects this situation, it leaves @code{const} alone,
6906 as this generally yields better results in practice.  However, using a
6907 C++ compiler to compile C code is not recommended or supported, and
6908 installers who run into trouble in this area should get a C compiler
6909 like @acronym{GCC} to compile their C code.
6911 This macro is obsolescent, as current C compilers support @code{const}.
6912 New programs need not use this macro.
6913 @end defmac
6915 @defmac AC_C_RESTRICT
6916 @acindex{C_RESTRICT}
6917 @cvindex restrict
6918 If the C compiler recognizes a variant spelling for the @code{restrict}
6919 keyword (@code{__restrict}, @code{__restrict__}, or @code{_Restrict}),
6920 then define @code{restrict} to that; this is more likely to do the right
6921 thing with compilers that support language variants where plain
6922 @code{restrict} is not a keyword.  Otherwise, if the C compiler
6923 recognizes the @code{restrict} keyword, don't do anything.
6924 Otherwise, define @code{restrict} to be empty.
6925 Thus, programs may simply use @code{restrict} as if every C compiler
6926 supported it; for those that do not, the makefile
6927 or configuration header defines it away.
6929 Although support in C++ for the @code{restrict} keyword is not
6930 required, several C++ compilers do accept the keyword.
6931 This macro works for them, too.
6932 @end defmac
6934 @defmac AC_C_VOLATILE
6935 @acindex{C_VOLATILE}
6936 @cvindex volatile
6937 If the C compiler does not understand the keyword @code{volatile},
6938 define @code{volatile} to be empty.  Programs can simply use
6939 @code{volatile} as if every C compiler supported it; for those that do
6940 not, the makefile or configuration header defines it as
6941 empty.
6943 If the correctness of your program depends on the semantics of
6944 @code{volatile}, simply defining it to be empty does, in a sense, break
6945 your code.  However, given that the compiler does not support
6946 @code{volatile}, you are at its mercy anyway.  At least your
6947 program compiles, when it wouldn't before.
6948 @xref{Volatile Objects}, for more about @code{volatile}.
6950 In general, the @code{volatile} keyword is a standard C feature, so
6951 you might expect that @code{volatile} is available only when
6952 @code{__STDC__} is defined.  However, Ultrix 4.3's native compiler does
6953 support volatile, but does not define @code{__STDC__}.
6955 This macro is obsolescent, as current C compilers support @code{volatile}.
6956 New programs need not use this macro.
6957 @end defmac
6959 @anchor{AC_C_INLINE}
6960 @defmac AC_C_INLINE
6961 @acindex{C_INLINE}
6962 @cvindex inline
6963 If the C compiler supports the keyword @code{inline}, do nothing.
6964 Otherwise define @code{inline} to @code{__inline__} or @code{__inline}
6965 if it accepts one of those, otherwise define @code{inline} to be empty.
6966 @end defmac
6968 @anchor{AC_C_CHAR_UNSIGNED}
6969 @defmac AC_C_CHAR_UNSIGNED
6970 @acindex{C_CHAR_UNSIGNED}
6971 @cvindex __CHAR_UNSIGNED__
6972 If the C type @code{char} is unsigned, define @code{__CHAR_UNSIGNED__},
6973 unless the C compiler predefines it.
6975 These days, using this macro is not necessary.  The same information can
6976 be determined by this portable alternative, thus avoiding the use of
6977 preprocessor macros in the namespace reserved for the implementation.
6979 @example
6980 #include <limits.h>
6981 #if CHAR_MIN == 0
6982 # define CHAR_UNSIGNED 1
6983 #endif
6984 @end example
6985 @end defmac
6987 @defmac AC_C_STRINGIZE
6988 @acindex{C_STRINGIZE}
6989 @cvindex HAVE_STRINGIZE
6990 If the C preprocessor supports the stringizing operator, define
6991 @code{HAVE_STRINGIZE}.  The stringizing operator is @samp{#} and is
6992 found in macros such as this:
6994 @example
6995 #define x(y) #y
6996 @end example
6998 This macro is obsolescent, as current C compilers support the
6999 stringizing operator.  New programs need not use this macro.
7000 @end defmac
7002 @defmac AC_C_FLEXIBLE_ARRAY_MEMBER
7003 @acindex{C_FLEXIBLE_ARRAY_MEMBER}
7004 @cvindex FLEXIBLE_ARRAY_MEMBER
7005 If the C compiler supports flexible array members, define
7006 @code{FLEXIBLE_ARRAY_MEMBER} to nothing; otherwise define it to 1.
7007 That way, a declaration like this:
7009 @example
7010 struct s
7011   @{
7012     size_t n_vals;
7013     double val[FLEXIBLE_ARRAY_MEMBER];
7014   @};
7015 @end example
7017 @noindent
7018 will let applications use the ``struct hack'' even with compilers that
7019 do not support flexible array members.  To allocate and use such an
7020 object, you can use code like this:
7022 @example
7023 size_t i;
7024 size_t n = compute_value_count ();
7025 struct s *p =
7026    malloc (offsetof (struct s, val)
7027            + n * sizeof (double));
7028 p->n_vals = n;
7029 for (i = 0; i < n; i++)
7030   p->val[i] = compute_value (i);
7031 @end example
7032 @end defmac
7034 @defmac AC_C_VARARRAYS
7035 @acindex{C_VARARRAYS}
7036 @cvindex HAVE_C_VARARRAYS
7037 If the C compiler supports variable-length arrays, define
7038 @code{HAVE_C_VARARRAYS}.  A variable-length array is an array of automatic
7039 storage duration whose length is determined at run time, when the array
7040 is declared.
7041 @end defmac
7043 @defmac AC_C_TYPEOF
7044 @acindex{C_TYPEOF}
7045 @cvindex HAVE_TYPEOF
7046 @cvindex typeof
7047 If the C compiler supports @acronym{GCC}'s @code{typeof} syntax either
7048 directly or
7049 through a different spelling of the keyword (e.g., @code{__typeof__}),
7050 define @code{HAVE_TYPEOF}.  If the support is available only through a
7051 different spelling, define @code{typeof} to that spelling.
7052 @end defmac
7054 @defmac AC_C_PROTOTYPES
7055 @acindex{C_PROTOTYPES}
7056 @cvindex PROTOTYPES
7057 @cvindex __PROTOTYPES
7058 @cvindex PARAMS
7059 If function prototypes are understood by the compiler (as determined by
7060 @code{AC_PROG_CC}), define @code{PROTOTYPES} and @code{__PROTOTYPES}.
7061 Defining @code{__PROTOTYPES} is for the benefit of
7062 header files that cannot use macros that infringe on user name space.
7064 This macro is obsolescent, as current C compilers support prototypes.
7065 New programs need not use this macro.
7066 @end defmac
7068 @anchor{AC_PROG_GCC_TRADITIONAL}
7069 @defmac AC_PROG_GCC_TRADITIONAL
7070 @acindex{PROG_GCC_TRADITIONAL}
7071 @ovindex CC
7072 Add @option{-traditional} to output variable @code{CC} if using the
7073 @acronym{GNU} C compiler and @code{ioctl} does not work properly without
7074 @option{-traditional}.  That usually happens when the fixed header files
7075 have not been installed on an old system.
7077 This macro is obsolescent, since current versions of the @acronym{GNU} C
7078 compiler fix the header files automatically when installed.
7079 @end defmac
7082 @node C++ Compiler
7083 @subsection C++ Compiler Characteristics
7086 @defmac AC_PROG_CXX (@ovar{compiler-search-list})
7087 @acindex{PROG_CXX}
7088 @ovindex CXX
7089 @ovindex CXXFLAGS
7090 Determine a C++ compiler to use.  Check whether the environment variable
7091 @code{CXX} or @code{CCC} (in that order) is set; if so, then set output
7092 variable @code{CXX} to its value.
7094 Otherwise, if the macro is invoked without an argument, then search for
7095 a C++ compiler under the likely names (first @code{g++} and @code{c++}
7096 then other names).  If none of those checks succeed, then as a last
7097 resort set @code{CXX} to @code{g++}.
7099 This macro may, however, be invoked with an optional first argument
7100 which, if specified, must be a blank-separated list of C++ compilers to
7101 search for.  This just gives the user an opportunity to specify an
7102 alternative search list for the C++ compiler.  For example, if you
7103 didn't like the default order, then you could invoke @code{AC_PROG_CXX}
7104 like this:
7106 @example
7107 AC_PROG_CXX([gcc cl KCC CC cxx cc++ xlC aCC c++ g++])
7108 @end example
7110 If using the @acronym{GNU} C++ compiler, set shell variable @code{GXX} to
7111 @samp{yes}.  If output variable @code{CXXFLAGS} was not already set, set
7112 it to @option{-g -O2} for the @acronym{GNU} C++ compiler (@option{-O2} on
7113 systems where G++ does not accept @option{-g}), or @option{-g} for other
7114 compilers.
7115 @end defmac
7117 @defmac AC_PROG_CXXCPP
7118 @acindex{PROG_CXXCPP}
7119 @ovindex CXXCPP
7120 Set output variable @code{CXXCPP} to a command that runs the C++
7121 preprocessor.  If @samp{$CXX -E} doesn't work, @file{/lib/cpp} is used.
7122 It is portable to run @code{CXXCPP} only on files with a @file{.c},
7123 @file{.C}, @file{.cc}, or @file{.cpp} extension.
7125 Some preprocessors don't indicate missing include files by the error
7126 status.  For such preprocessors an internal variable is set that causes
7127 other macros to check the standard error from the preprocessor and
7128 consider the test failed if any warnings have been reported.  However,
7129 it is not known whether such broken preprocessors exist for C++.
7130 @end defmac
7132 @defmac AC_PROG_CXX_C_O
7133 @acindex{PROG_CXX_C_O}
7134 @cvindex CXX_NO_MINUS_C_MINUS_O
7135 Test whether the C++ compiler accepts the options @option{-c} and
7136 @option{-o} simultaneously, and define @code{CXX_NO_MINUS_C_MINUS_O},
7137 if it does not.
7138 @end defmac
7141 @node Objective C Compiler
7142 @subsection Objective C Compiler Characteristics
7145 @defmac AC_PROG_OBJC (@ovar{compiler-search-list})
7146 @acindex{PROG_OBJC}
7147 @ovindex OBJC
7148 @ovindex OBJCFLAGS
7149 Determine an Objective C compiler to use.  If @code{OBJC} is not already
7150 set in the environment, check for Objective C compilers.  Set output
7151 variable @code{OBJC} to the name of the compiler found.
7153 This macro may, however, be invoked with an optional first argument
7154 which, if specified, must be a blank-separated list of Objective C compilers to
7155 search for.  This just gives the user an opportunity to specify an
7156 alternative search list for the Objective C compiler.  For example, if you
7157 didn't like the default order, then you could invoke @code{AC_PROG_OBJC}
7158 like this:
7160 @example
7161 AC_PROG_OBJC([gcc objcc objc])
7162 @end example
7164 If using the @acronym{GNU} Objective C compiler, set shell variable
7165 @code{GOBJC} to @samp{yes}.  If output variable @code{OBJCFLAGS} was not
7166 already set, set it to @option{-g -O2} for the @acronym{GNU} Objective C
7167 compiler (@option{-O2} on systems where @command{gcc} does not accept
7168 @option{-g}), or @option{-g} for other compilers.
7169 @end defmac
7171 @defmac AC_PROG_OBJCPP
7172 @acindex{PROG_OBJCPP}
7173 @ovindex OBJCPP
7174 Set output variable @code{OBJCPP} to a command that runs the Objective C
7175 preprocessor.  If @samp{$OBJC -E} doesn't work, @file{/lib/cpp} is used.
7176 @end defmac
7179 @node Erlang Compiler and Interpreter
7180 @subsection Erlang Compiler and Interpreter Characteristics
7181 @cindex Erlang
7183 Autoconf defines the following macros for determining paths to the essential
7184 Erlang/OTP programs:
7186 @defmac AC_ERLANG_PATH_ERLC (@ovar{value-if-not-found}, @dvar{path, $PATH})
7187 @acindex{ERLANG_PATH_ERLC}
7188 @ovindex ERLC
7189 @ovindex ERLCFLAGS
7190 Determine an Erlang compiler to use.  If @code{ERLC} is not already set in the
7191 environment, check for @command{erlc}.  Set output variable @code{ERLC} to the
7192 complete path of the compiler command found.  In addition, if @code{ERLCFLAGS}
7193 is not set in the environment, set it to an empty value.
7195 The two optional arguments have the same meaning as the two last arguments of
7196 macro @code{AC_PROG_PATH} for looking for the @command{erlc} program.  For
7197 example, to look for @command{erlc} only in the @file{/usr/lib/erlang/bin}
7198 directory:
7200 @example
7201 AC_ERLANG_PATH_ERLC([not found], [/usr/lib/erlang/bin])
7202 @end example
7203 @end defmac
7205 @defmac AC_ERLANG_NEED_ERLC (@dvar{path, $PATH})
7206 @acindex{ERLANG_NEED_ERLC}
7207 A simplified variant of the @code{AC_ERLANG_PATH_ERLC} macro, that prints an
7208 error message and exits the @command{configure} script if the @command{erlc}
7209 program is not found.
7210 @end defmac
7212 @defmac AC_ERLANG_PATH_ERL (@ovar{value-if-not-found}, @dvar{path, $PATH})
7213 @acindex{ERLANG_PATH_ERL}
7214 @ovindex ERL
7215 Determine an Erlang interpreter to use.  If @code{ERL} is not already
7216 set in the
7217 environment, check for @command{erl}.  Set output variable @code{ERL} to the
7218 complete path of the interpreter command found.
7220 The two optional arguments have the same meaning as the two last arguments of
7221 macro @code{AC_PROG_PATH} for looking for the @command{erl} program.  For
7222 example, to look for @command{erl} only in the @file{/usr/lib/erlang/bin}
7223 directory:
7225 @example
7226 AC_ERLANG_PATH_ERL([not found], [/usr/lib/erlang/bin])
7227 @end example
7228 @end defmac
7230 @defmac AC_ERLANG_NEED_ERL (@dvar{path, $PATH})
7231 @acindex{ERLANG_NEED_ERL}
7232 A simplified variant of the @code{AC_ERLANG_PATH_ERL} macro, that prints an
7233 error message and exits the @command{configure} script if the @command{erl}
7234 program is not found.
7235 @end defmac
7238 @node Fortran Compiler
7239 @subsection Fortran Compiler Characteristics
7240 @cindex Fortran
7241 @cindex F77
7243 The Autoconf Fortran support is divided into two categories: legacy
7244 Fortran 77 macros (@code{F77}), and modern Fortran macros (@code{FC}).
7245 The former are intended for traditional Fortran 77 code, and have output
7246 variables like @code{F77}, @code{FFLAGS}, and @code{FLIBS}.  The latter
7247 are for newer programs that can (or must) compile under the newer
7248 Fortran standards, and have output variables like @code{FC},
7249 @code{FCFLAGS}, and @code{FCLIBS}.
7251 Except for two new macros @code{AC_FC_SRCEXT} and
7252 @code{AC_FC_FREEFORM} (see below), the @code{FC} and @code{F77} macros
7253 behave almost identically, and so they are documented together in this
7254 section.
7257 @defmac AC_PROG_F77 (@ovar{compiler-search-list})
7258 @acindex{PROG_F77}
7259 @ovindex F77
7260 @ovindex FFLAGS
7261 Determine a Fortran 77 compiler to use.  If @code{F77} is not already
7262 set in the environment, then check for @code{g77} and @code{f77}, and
7263 then some other names.  Set the output variable @code{F77} to the name
7264 of the compiler found.
7266 This macro may, however, be invoked with an optional first argument
7267 which, if specified, must be a blank-separated list of Fortran 77
7268 compilers to search for.  This just gives the user an opportunity to
7269 specify an alternative search list for the Fortran 77 compiler.  For
7270 example, if you didn't like the default order, then you could invoke
7271 @code{AC_PROG_F77} like this:
7273 @example
7274 AC_PROG_F77([fl32 f77 fort77 xlf g77 f90 xlf90])
7275 @end example
7277 If using @code{g77} (the @acronym{GNU} Fortran 77 compiler), then
7278 set the shell variable @code{G77} to @samp{yes}.
7279 If the output variable @code{FFLAGS} was not already set in the
7280 environment, then set it to @option{-g -02} for @code{g77} (or @option{-O2}
7281 where @code{g77} does not accept @option{-g}).  Otherwise, set
7282 @code{FFLAGS} to @option{-g} for all other Fortran 77 compilers.
7283 @end defmac
7285 @defmac AC_PROG_FC (@ovar{compiler-search-list}, @ovar{dialect})
7286 @acindex{PROG_FC}
7287 @ovindex FC
7288 @ovindex FCFLAGS
7289 Determine a Fortran compiler to use.  If @code{FC} is not already set in
7290 the environment, then @code{dialect} is a hint to indicate what Fortran
7291 dialect to search for; the default is to search for the newest available
7292 dialect.  Set the output variable @code{FC} to the name of the compiler
7293 found.
7295 By default, newer dialects are preferred over older dialects, but if
7296 @code{dialect} is specified then older dialects are preferred starting
7297 with the specified dialect.  @code{dialect} can currently be one of
7298 Fortran 77, Fortran 90, or Fortran 95.  However, this is only a hint of
7299 which compiler @emph{name} to prefer (e.g., @code{f90} or @code{f95}),
7300 and no attempt is made to guarantee that a particular language standard
7301 is actually supported.  Thus, it is preferable that you avoid the
7302 @code{dialect} option, and use AC_PROG_FC only for code compatible with
7303 the latest Fortran standard.
7305 This macro may, alternatively, be invoked with an optional first argument
7306 which, if specified, must be a blank-separated list of Fortran
7307 compilers to search for, just as in @code{AC_PROG_F77}.
7309 If the output variable @code{FCFLAGS} was not already set in the
7310 environment, then set it to @option{-g -02} for @acronym{GNU} @code{g77} (or
7311 @option{-O2} where @code{g77} does not accept @option{-g}).  Otherwise,
7312 set @code{FCFLAGS} to @option{-g} for all other Fortran compilers.
7313 @end defmac
7315 @defmac AC_PROG_F77_C_O
7316 @defmacx AC_PROG_FC_C_O
7317 @acindex{PROG_F77_C_O}
7318 @acindex{PROG_FC_C_O}
7319 @cvindex F77_NO_MINUS_C_MINUS_O
7320 @cvindex FC_NO_MINUS_C_MINUS_O
7321 Test whether the Fortran compiler accepts the options @option{-c} and
7322 @option{-o} simultaneously, and define @code{F77_NO_MINUS_C_MINUS_O} or
7323 @code{FC_NO_MINUS_C_MINUS_O}, respectively, if it does not.
7324 @end defmac
7326 The following macros check for Fortran compiler characteristics.
7327 To check for characteristics not listed here, use
7328 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}) or
7329 @code{AC_RUN_IFELSE} (@pxref{Runtime}), making sure to first set the
7330 current language to Fortran 77 or Fortran via @code{AC_LANG([Fortran 77])}
7331 or @code{AC_LANG(Fortran)} (@pxref{Language Choice}).
7334 @defmac AC_F77_LIBRARY_LDFLAGS
7335 @defmacx AC_FC_LIBRARY_LDFLAGS
7336 @acindex{F77_LIBRARY_LDFLAGS}
7337 @ovindex FLIBS
7338 @acindex{FC_LIBRARY_LDFLAGS}
7339 @ovindex FCLIBS
7340 Determine the linker flags (e.g., @option{-L} and @option{-l}) for the
7341 @dfn{Fortran intrinsic and runtime libraries} that are required to
7342 successfully link a Fortran program or shared library.  The output
7343 variable @code{FLIBS} or @code{FCLIBS} is set to these flags (which
7344 should be included after @code{LIBS} when linking).
7346 This macro is intended to be used in those situations when it is
7347 necessary to mix, e.g., C++ and Fortran source code in a single
7348 program or shared library (@pxref{Mixing Fortran 77 With C and C++, , ,
7349 automake, @acronym{GNU} Automake}).
7351 For example, if object files from a C++ and Fortran compiler must be
7352 linked together, then the C++ compiler/linker must be used for linking
7353 (since special C++-ish things need to happen at link time like calling
7354 global constructors, instantiating templates, enabling exception
7355 support, etc.).
7357 However, the Fortran intrinsic and runtime libraries must be linked in
7358 as well, but the C++ compiler/linker doesn't know by default how to add
7359 these Fortran 77 libraries.  Hence, this macro was created to determine
7360 these Fortran libraries.
7362 The macros @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7363 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} are probably also necessary to
7364 link C/C++ with Fortran; see below.
7365 @end defmac
7367 @defmac AC_F77_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7368 @defmacx AC_FC_DUMMY_MAIN (@ovar{action-if-found}, @ovar{action-if-not-found})
7369 @acindex{F77_DUMMY_MAIN}
7370 @cvindex F77_DUMMY_MAIN
7371 With many compilers, the Fortran libraries detected by
7372 @code{AC_F77_LIBRARY_LDFLAGS} or @code{AC_FC_LIBRARY_LDFLAGS} provide
7373 their own @code{main} entry function that initializes things like
7374 Fortran I/O, and which then calls a user-provided entry function named
7375 (say) @code{MAIN__} to run the user's program.  The
7376 @code{AC_F77_DUMMY_MAIN} and @code{AC_FC_DUMMY_MAIN} or
7377 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros figure out how to deal with
7378 this interaction.
7380 When using Fortran for purely numerical functions (no I/O, etc.)@: often
7381 one prefers to provide one's own @code{main} and skip the Fortran
7382 library initializations.  In this case, however, one may still need to
7383 provide a dummy @code{MAIN__} routine in order to prevent linking errors
7384 on some systems.  @code{AC_F77_DUMMY_MAIN} or @code{AC_FC_DUMMY_MAIN}
7385 detects whether any such routine is @emph{required} for linking, and
7386 what its name is; the shell variable @code{F77_DUMMY_MAIN} or
7387 @code{FC_DUMMY_MAIN} holds this name, @code{unknown} when no solution
7388 was found, and @code{none} when no such dummy main is needed.
7390 By default, @var{action-if-found} defines @code{F77_DUMMY_MAIN} or
7391 @code{FC_DUMMY_MAIN} to the name of this routine (e.g., @code{MAIN__})
7392 @emph{if} it is required.  @var{action-if-not-found} defaults to
7393 exiting with an error.
7395 In order to link with Fortran routines, the user's C/C++ program should
7396 then include the following code to define the dummy main if it is
7397 needed:
7399 @example
7400 #ifdef F77_DUMMY_MAIN
7401 #  ifdef __cplusplus
7402      extern "C"
7403 #  endif
7404    int F77_DUMMY_MAIN() @{ return 1; @}
7405 #endif
7406 @end example
7408 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7410 Note that this macro is called automatically from @code{AC_F77_WRAPPERS}
7411 or @code{AC_FC_WRAPPERS}; there is generally no need to call it
7412 explicitly unless one wants to change the default actions.
7413 @end defmac
7415 @defmac AC_F77_MAIN
7416 @defmacx AC_FC_MAIN
7417 @acindex{F77_MAIN}
7418 @cvindex F77_MAIN
7419 @acindex{FC_MAIN}
7420 @cvindex FC_MAIN
7421 As discussed above, many Fortran libraries allow you to provide an entry
7422 point called (say) @code{MAIN__} instead of the usual @code{main}, which
7423 is then called by a @code{main} function in the Fortran libraries that
7424 initializes things like Fortran I/O@.  The
7425 @code{AC_F77_MAIN} and @code{AC_FC_MAIN} macros detect whether it is
7426 @emph{possible} to utilize such an alternate main function, and defines
7427 @code{F77_MAIN} and @code{FC_MAIN} to the name of the function.  (If no
7428 alternate main function name is found, @code{F77_MAIN} and @code{FC_MAIN} are
7429 simply defined to @code{main}.)
7431 Thus, when calling Fortran routines from C that perform things like I/O,
7432 one should use this macro and declare the "main" function like so:
7434 @example
7435 #ifdef __cplusplus
7436   extern "C"
7437 #endif
7438 int F77_MAIN(int argc, char *argv[]);
7439 @end example
7441 (Again, replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7442 @end defmac
7444 @defmac AC_F77_WRAPPERS
7445 @defmacx AC_FC_WRAPPERS
7446 @acindex{F77_WRAPPERS}
7447 @cvindex F77_FUNC
7448 @cvindex F77_FUNC_
7449 @acindex{FC_WRAPPERS}
7450 @cvindex FC_FUNC
7451 @cvindex FC_FUNC_
7452 Defines C macros @code{F77_FUNC (name, NAME)}, @code{FC_FUNC (name, NAME)},
7453 @code{F77_FUNC_(name, NAME)}, and @code{FC_FUNC_(name, NAME)} to properly
7454 mangle the names of C/C++ identifiers, and identifiers with underscores,
7455 respectively, so that they match the name-mangling scheme used by the
7456 Fortran compiler.
7458 Fortran is case-insensitive, and in order to achieve this the Fortran
7459 compiler converts all identifiers into a canonical case and format.  To
7460 call a Fortran subroutine from C or to write a C function that is
7461 callable from Fortran, the C program must explicitly use identifiers in
7462 the format expected by the Fortran compiler.  In order to do this, one
7463 simply wraps all C identifiers in one of the macros provided by
7464 @code{AC_F77_WRAPPERS} or @code{AC_FC_WRAPPERS}.  For example, suppose
7465 you have the following Fortran 77 subroutine:
7467 @example
7468       subroutine foobar (x, y)
7469       double precision x, y
7470       y = 3.14159 * x
7471       return
7472       end
7473 @end example
7475 You would then declare its prototype in C or C++ as:
7477 @example
7478 #define FOOBAR_F77 F77_FUNC (foobar, FOOBAR)
7479 #ifdef __cplusplus
7480 extern "C"  /* prevent C++ name mangling */
7481 #endif
7482 void FOOBAR_F77(double *x, double *y);
7483 @end example
7485 Note that we pass both the lowercase and uppercase versions of the
7486 function name to @code{F77_FUNC} so that it can select the right one.
7487 Note also that all parameters to Fortran 77 routines are passed as
7488 pointers (@pxref{Mixing Fortran 77 With C and C++, , , automake, @acronym{GNU}
7489 Automake}).
7491 (Replace @code{F77} with @code{FC} for Fortran instead of Fortran 77.)
7493 Although Autoconf tries to be intelligent about detecting the
7494 name-mangling scheme of the Fortran compiler, there may be Fortran
7495 compilers that it doesn't support yet.  In this case, the above code
7496 generates a compile-time error, but some other behavior
7497 (e.g., disabling Fortran-related features) can be induced by checking
7498 whether @code{F77_FUNC} or @code{FC_FUNC} is defined.
7500 Now, to call that routine from a C program, we would do something like:
7502 @example
7504     double x = 2.7183, y;
7505     FOOBAR_F77 (&x, &y);
7507 @end example
7509 If the Fortran identifier contains an underscore (e.g., @code{foo_bar}),
7510 you should use @code{F77_FUNC_} or @code{FC_FUNC_} instead of
7511 @code{F77_FUNC} or @code{FC_FUNC} (with the same arguments).  This is
7512 because some Fortran compilers mangle names differently if they contain
7513 an underscore.
7514 @end defmac
7516 @defmac AC_F77_FUNC (@var{name}, @ovar{shellvar})
7517 @defmacx AC_FC_FUNC (@var{name}, @ovar{shellvar})
7518 @acindex{F77_FUNC}
7519 @acindex{FC_FUNC}
7520 Given an identifier @var{name}, set the shell variable @var{shellvar} to
7521 hold the mangled version @var{name} according to the rules of the
7522 Fortran linker (see also @code{AC_F77_WRAPPERS} or
7523 @code{AC_FC_WRAPPERS}).  @var{shellvar} is optional; if it is not
7524 supplied, the shell variable is simply @var{name}.  The purpose of
7525 this macro is to give the caller a way to access the name-mangling
7526 information other than through the C preprocessor as above, for example,
7527 to call Fortran routines from some language other than C/C++.
7528 @end defmac
7530 @defmac AC_FC_SRCEXT (@var{ext}, @ovar{action-if-success}, @
7531   @ovar{action-if-failure})
7532 @acindex{FC_SRCEXT}
7533 By default, the @code{FC} macros perform their tests using a @file{.f}
7534 extension for source-code files.  Some compilers, however, only enable
7535 newer language features for appropriately named files, e.g., Fortran 90
7536 features only for @file{.f90} files.  On the other hand, some other
7537 compilers expect all source files to end in @file{.f} and require
7538 special flags to support other file name extensions.  The
7539 @code{AC_FC_SRCEXT} macro deals with both of these issues.
7541 The @code{AC_FC_SRCEXT} tries to get the @code{FC} compiler to accept files
7542 ending with the extension .@var{ext} (i.e., @var{ext} does @emph{not}
7543 contain the dot).  If any special compiler flags are needed for this, it
7544 stores them in the output variable @code{FCFLAGS_}@var{ext}.  This
7545 extension and these flags are then used for all subsequent @code{FC} tests
7546 (until @code{AC_FC_SRCEXT} is called again).
7548 For example, you would use @code{AC_FC_SRCEXT(f90)} to employ the
7549 @file{.f90} extension in future tests, and it would set a
7550 @code{FCFLAGS_f90} output variable with any extra flags that are needed
7551 to compile such files.
7553 The @code{FCFLAGS_}@var{ext} can @emph{not} be simply absorbed into
7554 @code{FCFLAGS}, for two reasons based on the limitations of some
7555 compilers.  First, only one @code{FCFLAGS_}@var{ext} can be used at a
7556 time, so files with different extensions must be compiled separately.
7557 Second, @code{FCFLAGS_}@var{ext} must appear @emph{immediately} before
7558 the source-code file name when compiling.  So, continuing the example
7559 above, you might compile a @file{foo.f90} file in your makefile with the
7560 command:
7562 @example
7563 foo.o: foo.f90
7564      $(FC) -c $(FCFLAGS) $(FCFLAGS_f90) '$(srcdir)/foo.f90'
7565 @end example
7567 If @code{AC_FC_SRCEXT} succeeds in compiling files with the @var{ext}
7568 extension, it calls @var{action-if-success} (defaults to nothing).  If
7569 it fails, and cannot find a way to make the @code{FC} compiler accept such
7570 files, it calls @var{action-if-failure} (defaults to exiting with an
7571 error message).
7573 @end defmac
7575 @defmac AC_FC_FREEFORM (@ovar{action-if-success}, @ovar{action-if-failure})
7576 @acindex{FC_FREEFORM}
7578 The @code{AC_FC_FREEFORM} tries to ensure that the Fortran compiler
7579 (@code{$FC}) allows free-format source code (as opposed to the older
7580 fixed-format style from Fortran 77).  If necessary, it may add some
7581 additional flags to @code{FCFLAGS}.
7583 This macro is most important if you are using the default @file{.f}
7584 extension, since many compilers interpret this extension as indicating
7585 fixed-format source unless an additional flag is supplied.  If you
7586 specify a different extension with @code{AC_FC_SRCEXT}, such as
7587 @file{.f90} or @file{.f95}, then @code{AC_FC_FREEFORM} ordinarily
7588 succeeds without modifying @code{FCFLAGS}.
7590 If @code{AC_FC_FREEFORM} succeeds in compiling free-form source, it
7591 calls @var{action-if-success} (defaults to nothing).  If it fails, it
7592 calls @var{action-if-failure} (defaults to exiting with an error
7593 message).
7594 @end defmac
7596 @node System Services
7597 @section System Services
7599 The following macros check for operating system services or capabilities.
7601 @anchor{AC_PATH_X}
7602 @defmac AC_PATH_X
7603 @acindex{PATH_X}
7604 @evindex XMKMF
7605 @cindex X Window System
7606 Try to locate the X Window System include files and libraries.  If the
7607 user gave the command line options @option{--x-includes=@var{dir}} and
7608 @option{--x-libraries=@var{dir}}, use those directories.
7610 If either or both were not given, get the missing values by running
7611 @code{xmkmf} (or an executable pointed to by the @code{XMKMF}
7612 environment variable) on a trivial @file{Imakefile} and examining the
7613 makefile that it produces.  Setting @code{XMKMF} to @samp{false}
7614 disables this method.
7616 If this method fails to find the X Window System, @command{configure}
7617 looks for the files in several directories where they often reside.
7618 If either method is successful, set the shell variables
7619 @code{x_includes} and @code{x_libraries} to their locations, unless they
7620 are in directories the compiler searches by default.
7622 If both methods fail, or the user gave the command line option
7623 @option{--without-x}, set the shell variable @code{no_x} to @samp{yes};
7624 otherwise set it to the empty string.
7625 @end defmac
7627 @anchor{AC_PATH_XTRA}
7628 @defmac AC_PATH_XTRA
7629 @acindex{PATH_XTRA}
7630 @ovindex X_CFLAGS
7631 @ovindex X_LIBS
7632 @ovindex X_EXTRA_LIBS
7633 @ovindex X_PRE_LIBS
7634 @cvindex X_DISPLAY_MISSING
7635 An enhanced version of @code{AC_PATH_X}.  It adds the C compiler flags
7636 that X needs to output variable @code{X_CFLAGS}, and the X linker flags
7637 to @code{X_LIBS}.  Define @code{X_DISPLAY_MISSING} if X is not
7638 available.
7640 This macro also checks for special libraries that some systems need in
7641 order to compile X programs.  It adds any that the system needs to
7642 output variable @code{X_EXTRA_LIBS}.  And it checks for special X11R6
7643 libraries that need to be linked with before @option{-lX11}, and adds
7644 any found to the output variable @code{X_PRE_LIBS}.
7646 @c This is an incomplete kludge.  Make a real way to do it.
7647 @c If you need to check for other X functions or libraries yourself, then
7648 @c after calling this macro, add the contents of @code{X_EXTRA_LIBS} to
7649 @c @code{LIBS} temporarily, like this: (FIXME - add example)
7650 @end defmac
7652 @anchor{AC_SYS_INTERPRETER}
7653 @defmac AC_SYS_INTERPRETER
7654 @acindex{SYS_INTERPRETER}
7655 Check whether the system supports starting scripts with a line of the
7656 form @samp{#!/bin/sh} to select the interpreter to use for the script.
7657 After running this macro, shell code in @file{configure.ac} can check
7658 the shell variable @code{interpval}; it is set to @samp{yes}
7659 if the system supports @samp{#!}, @samp{no} if not.
7660 @end defmac
7662 @defmac AC_SYS_LARGEFILE
7663 @acindex{SYS_LARGEFILE}
7664 @cvindex _FILE_OFFSET_BITS
7665 @cvindex _LARGE_FILES
7666 @ovindex CC
7667 @cindex Large file support
7668 @cindex LFS
7669 Arrange for 64-bit file offsets, known as
7670 @uref{http://@/www.unix-systems@/.org/@/version2/@/whatsnew/@/lfs20mar.html,
7671 large-file support}.  On some hosts, one must use special compiler
7672 options to build programs that can access large files.  Append any such
7673 options to the output variable @code{CC}.  Define
7674 @code{_FILE_OFFSET_BITS} and @code{_LARGE_FILES} if necessary.
7676 Large-file support can be disabled by configuring with the
7677 @option{--disable-largefile} option.
7679 If you use this macro, check that your program works even when
7680 @code{off_t} is wider than @code{long int}, since this is common when
7681 large-file support is enabled.  For example, it is not correct to print
7682 an arbitrary @code{off_t} value @code{X} with @code{printf ("%ld",
7683 (long int) X)}.
7685 The LFS introduced the @code{fseeko} and @code{ftello} functions to
7686 replace their C counterparts @code{fseek} and @code{ftell} that do not
7687 use @code{off_t}.  Take care to use @code{AC_FUNC_FSEEKO} to make their
7688 prototypes available when using them and large-file support is
7689 enabled.
7690 @end defmac
7692 @anchor{AC_SYS_LONG_FILE_NAMES}
7693 @defmac AC_SYS_LONG_FILE_NAMES
7694 @acindex{SYS_LONG_FILE_NAMES}
7695 @cvindex HAVE_LONG_FILE_NAMES
7696 If the system supports file names longer than 14 characters, define
7697 @code{HAVE_LONG_FILE_NAMES}.
7698 @end defmac
7700 @defmac AC_SYS_POSIX_TERMIOS
7701 @acindex{SYS_POSIX_TERMIOS}
7702 @cindex Posix termios headers
7703 @cindex termios Posix headers
7704 Check to see if the Posix termios headers and functions are available on the
7705 system.  If so, set the shell variable @code{ac_cv_sys_posix_termios} to
7706 @samp{yes}.  If not, set the variable to @samp{no}.
7707 @end defmac
7709 @node Posix Variants
7710 @section Posix Variants
7712 The following macro makes it possible to use features of Posix that are
7713 extensions to C, as well as platform extensions not defined by Posix.
7715 @anchor{AC_USE_SYSTEM_EXTENSIONS}
7716 @defmac AC_USE_SYSTEM_EXTENSIONS
7717 @acindex{USE_SYSTEM_EXTENSIONS}
7718 @cvindex _ALL_SOURCE
7719 @cvindex _GNU_SOURCE
7720 @cvindex _MINIX
7721 @cvindex _POSIX_1_SOURCE
7722 @cvindex _POSIX_PTHREAD_SEMANTICS
7723 @cvindex _POSIX_SOURCE
7724 @cvindex _TANDEM_SOURCE
7725 @cvindex __EXTENSIONS__
7726 This macro was introduced in Autoconf 2.60.  If possible, enable
7727 extensions to C or Posix on hosts that normally disable the extensions,
7728 typically due to standards-conformance namespace issues.  This should be
7729 called before any macros that run the C compiler.  The following
7730 preprocessor macros are defined where appropriate:
7732 @table @code
7733 @item _GNU_SOURCE
7734 Enable extensions on @acronym{GNU}/Linux.
7735 @item __EXTENSIONS__
7736 Enable general extensions on Solaris.
7737 @item _POSIX_PTHREAD_SEMANTICS
7738 Enable threading extensions on Solaris.
7739 @item _TANDEM_SOURCE
7740 Enable extensions for the @acronym{HP} NonStop platform.
7741 @item _ALL_SOURCE
7742 Enable extensions for @acronym{AIX} 3, and for Interix.
7743 @item _POSIX_SOURCE
7744 Enable Posix functions for Minix.
7745 @item _POSIX_1_SOURCE
7746 Enable additional Posix functions for Minix.
7747 @item _MINIX
7748 Identify Minix platform.  This particular preprocessor macro is
7749 obsolescent, and may be removed in a future release of Autoconf.
7750 @end table
7751 @end defmac
7754 @node Erlang Libraries
7755 @section Erlang Libraries
7756 @cindex Erlang, Library, checking
7758 The following macros check for an installation of Erlang/OTP, and for the
7759 presence of certain Erlang libraries.  All those macros require the
7760 configuration of an Erlang interpreter and an Erlang compiler
7761 (@pxref{Erlang Compiler and Interpreter}).
7763 @defmac AC_ERLANG_SUBST_ROOT_DIR
7764 @acindex{ERLANG_SUBST_ROOT_DIR}
7765 @ovindex ERLANG_ROOT_DIR
7767 Set the output variable @code{ERLANG_ROOT_DIR} to the path to the base
7768 directory in which Erlang/OTP is installed (as returned by Erlang's
7769 @code{code:root_dir/0} function).  The result of this test is cached if
7770 caching is enabled when running @command{configure}.
7771 @end defmac
7773 @defmac AC_ERLANG_SUBST_LIB_DIR
7774 @acindex{ERLANG_SUBST_LIB_DIR}
7775 @ovindex ERLANG_LIB_DIR
7777 Set the output variable @code{ERLANG_LIB_DIR} to the path of the library
7778 directory of Erlang/OTP (as returned by Erlang's
7779 @code{code:lib_dir/0} function), which subdirectories each contain an installed
7780 Erlang/OTP library.  The result of this test is cached if caching is enabled
7781 when running @command{configure}.
7782 @end defmac
7784 @defmac AC_ERLANG_CHECK_LIB (@var{library}, @ovar{action-if-found}, @
7785   @ovar{action-if-not-found})
7786 @acindex{ERLANG_CHECK_LIB}
7787 @ovindex ERLANG_LIB_DIR_@var{library}
7788 @ovindex ERLANG_LIB_VER_@var{library}
7790 Test whether the Erlang/OTP library @var{library} is installed by
7791 calling Erlang's @code{code:lib_dir/1} function.  The result of this
7792 test is cached if caching is enabled when running @command{configure}.
7793 @var{action-if-found} is a list of shell commands to run if the library
7794 is installed; @var{action-if-not-found} is a list of shell commands to
7795 run if it is not.  Additionally, if the library is installed, the output
7796 variable @samp{ERLANG_LIB_DIR_@var{library}} is set to the path to the
7797 library installation directory, and the output variable
7798 @samp{ERLANG_LIB_VER_@var{library}} is set to the version number that is
7799 part of the subdirectory name, if it is in the standard form
7800 (@code{@var{library}-@var{version}}).  If the directory name does not
7801 have a version part, @samp{ERLANG_LIB_VER_@var{library}} is set to the
7802 empty string.  If the library is not installed,
7803 @samp{ERLANG_LIB_DIR_@var{library}} and
7804 @samp{ERLANG_LIB_VER_@var{library}} are set to @code{"not found"}.  For
7805 example, to check if library @code{stdlib} is installed:
7807 @example
7808 AC_ERLANG_CHECK_LIB([stdlib],
7809   [echo "stdlib version \"$ERLANG_LIB_VER_stdlib\""
7810    echo "is installed in \"$ERLANG_LIB_DIR_stdlib\""],
7811   [AC_MSG_ERROR([stdlib was not found!])])
7812 @end example
7813 @end defmac
7815 In addition to the above macros, which test installed Erlang libraries, the
7816 following macros determine the paths to the directories into which newly built
7817 Erlang libraries are to be installed:
7819 @defmac AC_ERLANG_SUBST_INSTALL_LIB_DIR
7820 @acindex{ERLANG_SUBST_INSTALL_LIB_DIR}
7821 @ovindex ERLANG_INSTALL_LIB_DIR
7823 Set the @code{ERLANG_INSTALL_LIB_DIR} output variable to the directory into
7824 which every built Erlang library should be installed in a separate
7825 subdirectory.
7826 If this variable is not set in the environment when @command{configure} runs,
7827 its default value is @code{$ERLANG_LIB_DIR}, which value is set by the
7828 @code{AC_ERLANG_SUBST_LIB_DIR} macro.
7829 @end defmac
7831 @defmac AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR (@var{library}, @var{version})
7832 @acindex{ERLANG_SUBST_INSTALL_LIB_SUBDIR}
7833 @ovindex ERLANG_INSTALL_LIB_DIR_@var{library}
7835 Set the @samp{ERLANG_INSTALL_LIB_DIR_@var{library}} output variable to the
7836 directory into which the built Erlang library @var{library} version
7837 @var{version} should be installed.  If this variable is not set in the
7838 environment when @command{configure} runs, its default value is
7839 @samp{$ERLANG_INSTALL_LIB_DIR/@var{library}-@var{version}}, the value of the
7840 @code{ERLANG_INSTALL_LIB_DIR} variable being set by the
7841 @code{AC_ERLANG_SUBST_INSTALL_LIB_DIR} macro.
7842 @end defmac
7848 @c ========================================================= Writing Tests
7850 @node Writing Tests
7851 @chapter Writing Tests
7853 If the existing feature tests don't do something you need, you have to
7854 write new ones.  These macros are the building blocks.  They provide
7855 ways for other macros to check whether various kinds of features are
7856 available and report the results.
7858 This chapter contains some suggestions and some of the reasons why the
7859 existing tests are written the way they are.  You can also learn a lot
7860 about how to write Autoconf tests by looking at the existing ones.  If
7861 something goes wrong in one or more of the Autoconf tests, this
7862 information can help you understand the assumptions behind them, which
7863 might help you figure out how to best solve the problem.
7865 These macros check the output of the compiler system of the current
7866 language (@pxref{Language Choice}).  They do not cache the results of
7867 their tests for future use (@pxref{Caching Results}), because they don't
7868 know enough about the information they are checking for to generate a
7869 cache variable name.  They also do not print any messages, for the same
7870 reason.  The checks for particular kinds of features call these macros
7871 and do cache their results and print messages about what they're
7872 checking for.
7874 When you write a feature test that could be applicable to more than one
7875 software package, the best thing to do is encapsulate it in a new macro.
7876 @xref{Writing Autoconf Macros}, for how to do that.
7878 @menu
7879 * Language Choice::             Selecting which language to use for testing
7880 * Writing Test Programs::       Forging source files for compilers
7881 * Running the Preprocessor::    Detecting preprocessor symbols
7882 * Running the Compiler::        Detecting language or header features
7883 * Running the Linker::          Detecting library features
7884 * Runtime::                     Testing for runtime features
7885 * Systemology::                 A zoology of operating systems
7886 * Multiple Cases::              Tests for several possible values
7887 @end menu
7889 @node Language Choice
7890 @section Language Choice
7891 @cindex Language
7893 Autoconf-generated @command{configure} scripts check for the C compiler and
7894 its features by default.  Packages that use other programming languages
7895 (maybe more than one, e.g., C and C++) need to test features of the
7896 compilers for the respective languages.  The following macros determine
7897 which programming language is used in the subsequent tests in
7898 @file{configure.ac}.
7900 @anchor{AC_LANG}
7901 @defmac AC_LANG (@var{language})
7902 Do compilation tests using the compiler, preprocessor, and file
7903 extensions for the specified @var{language}.
7905 Supported languages are:
7907 @table @samp
7908 @item C
7909 Do compilation tests using @code{CC} and @code{CPP} and use extension
7910 @file{.c} for test programs.  Use compilation flags: @code{CPPFLAGS} with
7911 @code{CPP}, and both @code{CPPFLAGS} and @code{CFLAGS} with @code{CC}.
7913 @item C++
7914 Do compilation tests using @code{CXX} and @code{CXXCPP} and use
7915 extension @file{.C} for test programs.  Use compilation flags:
7916 @code{CPPFLAGS} with @code{CXXCPP}, and both @code{CPPFLAGS} and
7917 @code{CXXFLAGS} with @code{CXX}.
7919 @item Fortran 77
7920 Do compilation tests using @code{F77} and use extension @file{.f} for
7921 test programs.  Use compilation flags: @code{FFLAGS}.
7923 @item Fortran
7924 Do compilation tests using @code{FC} and use extension @file{.f} (or
7925 whatever has been set by @code{AC_FC_SRCEXT}) for test programs.  Use
7926 compilation flags: @code{FCFLAGS}.
7928 @item Erlang
7929 @ovindex ERLC
7930 @ovindex ERL
7931 @ovindex ERLCFLAGS
7932 Compile and execute tests using @code{ERLC} and @code{ERL} and use extension
7933 @file{.erl} for test Erlang modules.  Use compilation flags: @code{ERLCFLAGS}.
7935 @item Objective C
7936 Do compilation tests using @code{OBJC} and @code{OBJCPP} and use
7937 extension @file{.m} for test programs.  Use compilation flags:
7938 @code{CPPFLAGS} with @code{OBJCPP}, and both @code{CPPFLAGS} and
7939 @code{OBJCFLAGS} with @code{OBJC}.
7940 @end table
7941 @end defmac
7943 @anchor{AC_LANG_PUSH}
7944 @defmac AC_LANG_PUSH (@var{language})
7945 @acindex{LANG_PUSH}
7946 Remember the current language (as set by @code{AC_LANG}) on a stack, and
7947 then select the @var{language}.  Use this macro and @code{AC_LANG_POP}
7948 in macros that need to temporarily switch to a particular language.
7949 @end defmac
7951 @defmac AC_LANG_POP (@ovar{language})
7952 @acindex{LANG_POP}
7953 Select the language that is saved on the top of the stack, as set by
7954 @code{AC_LANG_PUSH}, and remove it from the stack.
7956 If given, @var{language} specifies the language we just @emph{quit}.  It
7957 is a good idea to specify it when it's known (which should be the
7958 case@dots{}), since Autoconf detects inconsistencies.
7960 @example
7961 AC_LANG_PUSH([Fortran 77])
7962 # Perform some tests on Fortran 77.
7963 # @dots{}
7964 AC_LANG_POP([Fortran 77])
7965 @end example
7966 @end defmac
7968 @defmac AC_LANG_ASSERT (@var{language})
7969 @acindex{LANG_ASSERT} Check statically that the current language is
7970 @var{language}.  You should use this in your language specific macros
7971 to avoid that they be called with an inappropriate language.
7973 This macro runs only at @command{autoconf} time, and incurs no cost at
7974 @command{configure} time.  Sadly enough and because Autoconf is a two
7975 layer language @footnote{Because M4 is not aware of Sh code,
7976 especially conditionals, some optimizations that look nice statically
7977 may produce incorrect results at runtime.}, the macros
7978 @code{AC_LANG_PUSH} and @code{AC_LANG_POP} cannot be ``optimizing'',
7979 therefore as much as possible you ought to avoid using them to wrap
7980 your code, rather, require from the user to run the macro with a
7981 correct current language, and check it with @code{AC_LANG_ASSERT}.
7982 And anyway, that may help the user understand she is running a Fortran
7983 macro while expecting a result about her Fortran 77 compiler@enddots{}
7984 @end defmac
7987 @defmac AC_REQUIRE_CPP
7988 @acindex{REQUIRE_CPP}
7989 Ensure that whichever preprocessor would currently be used for tests has
7990 been found.  Calls @code{AC_REQUIRE} (@pxref{Prerequisite Macros}) with an
7991 argument of either @code{AC_PROG_CPP} or @code{AC_PROG_CXXCPP},
7992 depending on which language is current.
7993 @end defmac
7996 @node Writing Test Programs
7997 @section Writing Test Programs
7999 Autoconf tests follow a common scheme: feed some program with some
8000 input, and most of the time, feed a compiler with some source file.
8001 This section is dedicated to these source samples.
8003 @menu
8004 * Guidelines::                  General rules for writing test programs
8005 * Test Functions::              Avoiding pitfalls in test programs
8006 * Generating Sources::          Source program boilerplate
8007 @end menu
8009 @node Guidelines
8010 @subsection Guidelines for Test Programs
8012 The most important rule to follow when writing testing samples is:
8014 @center @emph{Look for realism.}
8016 This motto means that testing samples must be written with the same
8017 strictness as real programs are written.  In particular, you should
8018 avoid ``shortcuts'' and simplifications.
8020 Don't just play with the preprocessor if you want to prepare a
8021 compilation.  For instance, using @command{cpp} to check whether a header is
8022 functional might let your @command{configure} accept a header which
8023 causes some @emph{compiler} error.  Do not hesitate to check a header with
8024 other headers included before, especially required headers.
8026 Make sure the symbols you use are properly defined, i.e., refrain for
8027 simply declaring a function yourself instead of including the proper
8028 header.
8030 Test programs should not write to standard output.  They
8031 should exit with status 0 if the test succeeds, and with status 1
8032 otherwise, so that success
8033 can be distinguished easily from a core dump or other failure;
8034 segmentation violations and other failures produce a nonzero exit
8035 status.  Unless you arrange for @code{exit} to be declared, test
8036 programs should @code{return}, not @code{exit}, from @code{main},
8037 because on many systems @code{exit} is not declared by default.
8039 Test programs can use @code{#if} or @code{#ifdef} to check the values of
8040 preprocessor macros defined by tests that have already run.  For
8041 example, if you call @code{AC_HEADER_STDBOOL}, then later on in
8042 @file{configure.ac} you can have a test program that includes
8043 @file{stdbool.h} conditionally:
8045 @example
8046 @group
8047 #ifdef HAVE_STDBOOL_H
8048 # include <stdbool.h>
8049 #endif
8050 @end group
8051 @end example
8053 Both @code{#if HAVE_STDBOOL_H} and @code{#ifdef HAVE_STDBOOL_H} will
8054 work with any standard C compiler.  Some developers prefer @code{#if}
8055 because it is easier to read, while others prefer @code{#ifdef} because
8056 it avoids diagnostics with picky compilers like @acronym{GCC} with the
8057 @option{-Wundef} option.
8059 If a test program needs to use or create a data file, give it a name
8060 that starts with @file{conftest}, such as @file{conftest.data}.  The
8061 @command{configure} script cleans up by running @samp{rm -f -r conftest*}
8062 after running test programs and if the script is interrupted.
8064 @node Test Functions
8065 @subsection Test Functions
8067 These days it's safe to assume support for function prototypes
8068 (introduced in C89).
8070 Functions that test programs declare should also be conditionalized for
8071 C++, which requires @samp{extern "C"} prototypes.  Make sure to not
8072 include any header files containing clashing prototypes.
8074 @example
8075 #ifdef __cplusplus
8076 extern "C"
8077 #endif
8078 void *valloc (size_t);
8079 @end example
8081 If a test program calls a function with invalid parameters (just to see
8082 whether it exists), organize the program to ensure that it never invokes
8083 that function.  You can do this by calling it in another function that is
8084 never invoked.  You can't do it by putting it after a call to
8085 @code{exit}, because @acronym{GCC} version 2 knows that @code{exit}
8086 never returns
8087 and optimizes out any code that follows it in the same block.
8089 If you include any header files, be sure to call the functions
8090 relevant to them with the correct number of arguments, even if they are
8091 just 0, to avoid compilation errors due to prototypes.  @acronym{GCC}
8092 version 2
8093 has internal prototypes for several functions that it automatically
8094 inlines; for example, @code{memcpy}.  To avoid errors when checking for
8095 them, either pass them the correct number of arguments or redeclare them
8096 with a different return type (such as @code{char}).
8099 @node Generating Sources
8100 @subsection Generating Sources
8102 Autoconf provides a set of macros that can be used to generate test
8103 source files.  They are written to be language generic, i.e., they
8104 actually depend on the current language (@pxref{Language Choice}) to
8105 ``format'' the output properly.
8108 @defmac AC_LANG_CONFTEST (@var{source})
8109 @acindex{LANG_CONFTEST}
8110 Save the @var{source} text in the current test source file:
8111 @file{conftest.@var{extension}} where the @var{extension} depends on the
8112 current language.
8114 Note that the @var{source} is evaluated exactly once, like regular
8115 Autoconf macro arguments, and therefore (i) you may pass a macro
8116 invocation, (ii) if not, be sure to double quote if needed.
8117 @end defmac
8119 @defmac AC_LANG_SOURCE (@var{source})
8120 @acindex{LANG_SOURCE}
8121 Expands into the @var{source}, with the definition of
8122 all the @code{AC_DEFINE} performed so far.
8123 @end defmac
8125 For instance executing (observe the double quotation!):
8127 @example
8128 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8129 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8130   [Greetings string.])
8131 AC_LANG(C)
8132 AC_LANG_CONFTEST(
8133    [AC_LANG_SOURCE([[const char hw[] = "Hello, World\n";]])])
8134 gcc -E -dD -o - conftest.c
8135 @end example
8137 @noindent
8138 results in:
8140 @example
8141 @dots{}
8142 # 1 "conftest.c"
8144 #define PACKAGE_NAME "Hello"
8145 #define PACKAGE_TARNAME "hello"
8146 #define PACKAGE_VERSION "1.0"
8147 #define PACKAGE_STRING "Hello 1.0"
8148 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8149 #define HELLO_WORLD "Hello, World\n"
8151 const char hw[] = "Hello, World\n";
8152 @end example
8154 When the test language is Fortran or Erlang, the @code{AC_DEFINE} definitions
8155 are not automatically translated into constants in the source code by this
8156 macro.
8158 @defmac AC_LANG_PROGRAM (@var{prologue}, @var{body})
8159 @acindex{LANG_PROGRAM}
8160 Expands into a source file which consists of the @var{prologue}, and
8161 then @var{body} as body of the main function (e.g., @code{main} in
8162 C).  Since it uses @code{AC_LANG_SOURCE}, the features of the latter are
8163 available.
8164 @end defmac
8166 For instance:
8168 @example
8169 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8170 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8171   [Greetings string.])
8172 AC_LANG_CONFTEST(
8173 [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8174                  [[fputs (hw, stdout);]])])
8175 gcc -E -dD -o - conftest.c
8176 @end example
8178 @noindent
8179 results in:
8181 @example
8182 @dots{}
8183 # 1 "conftest.c"
8185 #define PACKAGE_NAME "Hello"
8186 #define PACKAGE_TARNAME "hello"
8187 #define PACKAGE_VERSION "1.0"
8188 #define PACKAGE_STRING "Hello 1.0"
8189 #define PACKAGE_BUGREPORT "bug-hello@@example.org"
8190 #define HELLO_WORLD "Hello, World\n"
8192 const char hw[] = "Hello, World\n";
8194 main ()
8196 fputs (hw, stdout);
8197   ;
8198   return 0;
8200 @end example
8202 In Erlang tests, the created source file is that of an Erlang module called
8203 @code{conftest} (@file{conftest.erl}).  This module defines and exports
8204 at least
8205 one @code{start/0} function, which is called to perform the test.  The
8206 @var{prologue} is optional code that is inserted between the module header and
8207 the @code{start/0} function definition.  @var{body} is the body of the
8208 @code{start/0} function without the final period (@pxref{Runtime}, about
8209 constraints on this function's behavior).
8211 For instance:
8213 @example
8214 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8215 AC_LANG(Erlang)
8216 AC_LANG_CONFTEST(
8217 [AC_LANG_PROGRAM([[-define(HELLO_WORLD, "Hello, world!").]],
8218                  [[io:format("~s~n", [?HELLO_WORLD])]])])
8219 cat conftest.erl
8220 @end example
8222 @noindent
8223 results in:
8225 @example
8226 -module(conftest).
8227 -export([start/0]).
8228 -define(HELLO_WORLD, "Hello, world!").
8229 start() ->
8230 io:format("~s~n", [?HELLO_WORLD])
8232 @end example
8234 @defmac AC_LANG_CALL (@var{prologue}, @var{function})
8235 @acindex{LANG_CALL}
8236 Expands into a source file which consists of the @var{prologue}, and
8237 then a call to the @var{function} as body of the main function (e.g.,
8238 @code{main} in C).  Since it uses @code{AC_LANG_PROGRAM}, the feature
8239 of the latter are available.
8241 This function will probably be replaced in the future by a version
8242 which would enable specifying the arguments.  The use of this macro is
8243 not encouraged, as it violates strongly the typing system.
8245 This macro cannot be used for Erlang tests.
8246 @end defmac
8248 @defmac AC_LANG_FUNC_LINK_TRY (@var{function})
8249 @acindex{LANG_FUNC_LINK_TRY}
8250 Expands into a source file which uses the @var{function} in the body of
8251 the main function (e.g., @code{main} in C).  Since it uses
8252 @code{AC_LANG_PROGRAM}, the features of the latter are available.
8254 As @code{AC_LANG_CALL}, this macro is documented only for completeness.
8255 It is considered to be severely broken, and in the future will be
8256 removed in favor of actual function calls (with properly typed
8257 arguments).
8259 This macro cannot be used for Erlang tests.
8260 @end defmac
8262 @node Running the Preprocessor
8263 @section Running the Preprocessor
8265 Sometimes one might need to run the preprocessor on some source file.
8266 @emph{Usually it is a bad idea}, as you typically need to @emph{compile}
8267 your project, not merely run the preprocessor on it; therefore you
8268 certainly want to run the compiler, not the preprocessor.  Resist the
8269 temptation of following the easiest path.
8271 Nevertheless, if you need to run the preprocessor, then use
8272 @code{AC_PREPROC_IFELSE}.
8274 The macros described in this section cannot be used for tests in Erlang or
8275 Fortran, since those languages require no preprocessor.
8277 @anchor{AC_PREPROC_IFELSE}
8278 @defmac AC_PREPROC_IFELSE (@var{input}, @ovar{action-if-true}, @
8279   @ovar{action-if-false})
8280 @acindex{PREPROC_IFELSE}
8281 Run the preprocessor of the current language (@pxref{Language Choice})
8282 on the @var{input}, run the shell commands @var{action-if-true} on
8283 success, @var{action-if-false} otherwise.  The @var{input} can be made
8284 by @code{AC_LANG_PROGRAM} and friends.
8286 This macro uses @code{CPPFLAGS}, but not @code{CFLAGS}, because
8287 @option{-g}, @option{-O}, etc.@: are not valid options to many C
8288 preprocessors.
8290 It is customary to report unexpected failures with
8291 @code{AC_MSG_FAILURE}.
8292 @end defmac
8294 For instance:
8296 @example
8297 AC_INIT([Hello], [1.0], [bug-hello@@example.org])
8298 AC_DEFINE([HELLO_WORLD], ["Hello, World\n"],
8299   [Greetings string.])
8300 AC_PREPROC_IFELSE(
8301    [AC_LANG_PROGRAM([[const char hw[] = "Hello, World\n";]],
8302                     [[fputs (hw, stdout);]])],
8303    [AC_MSG_RESULT([OK])],
8304    [AC_MSG_FAILURE([unexpected preprocessor failure])])
8305 @end example
8307 @noindent
8308 results in:
8310 @example
8311 checking for gcc... gcc
8312 checking for C compiler default output file name... a.out
8313 checking whether the C compiler works... yes
8314 checking whether we are cross compiling... no
8315 checking for suffix of executables...
8316 checking for suffix of object files... o
8317 checking whether we are using the GNU C compiler... yes
8318 checking whether gcc accepts -g... yes
8319 checking for gcc option to accept ISO C89... none needed
8320 checking how to run the C preprocessor... gcc -E
8322 @end example
8324 @sp 1
8326 The macro @code{AC_TRY_CPP} (@pxref{Obsolete Macros}) used to play the
8327 role of @code{AC_PREPROC_IFELSE}, but double quotes its argument, making
8328 it impossible to use it to elaborate sources.  You are encouraged to
8329 get rid of your old use of the macro @code{AC_TRY_CPP} in favor of
8330 @code{AC_PREPROC_IFELSE}, but, in the first place, are you sure you need
8331 to run the @emph{preprocessor} and not the compiler?
8333 @anchor{AC_EGREP_HEADER}
8334 @defmac AC_EGREP_HEADER (@var{pattern}, @var{header-file}, @
8335   @var{action-if-found}, @ovar{action-if-not-found})
8336 @acindex{EGREP_HEADER}
8337 If the output of running the preprocessor on the system header file
8338 @var{header-file} matches the extended regular expression
8339 @var{pattern}, execute shell commands @var{action-if-found}, otherwise
8340 execute @var{action-if-not-found}.
8341 @end defmac
8343 @anchor{AC_EGREP_CPP}
8344 @defmac AC_EGREP_CPP (@var{pattern}, @var{program}, @
8345   @ovar{action-if-found}, @ovar{action-if-not-found})
8346 @acindex{EGREP_CPP}
8347 @var{program} is the text of a C or C++ program, on which shell
8348 variable, back quote, and backslash substitutions are performed.  If the
8349 output of running the preprocessor on @var{program} matches the
8350 extended regular expression @var{pattern}, execute shell commands
8351 @var{action-if-found}, otherwise execute @var{action-if-not-found}.
8352 @end defmac
8356 @node Running the Compiler
8357 @section Running the Compiler
8359 To check for a syntax feature of the current language's (@pxref{Language
8360 Choice}) compiler, such as whether it recognizes a certain keyword, or
8361 simply to try some library feature, use @code{AC_COMPILE_IFELSE} to try
8362 to compile a small program that uses that feature.
8364 @defmac AC_COMPILE_IFELSE (@var{input}, @ovar{action-if-true}, @
8365   @ovar{action-if-false})
8366 @acindex{COMPILE_IFELSE}
8367 Run the compiler and compilation flags of the current language
8368 (@pxref{Language Choice}) on the @var{input}, run the shell commands
8369 @var{action-if-true} on success, @var{action-if-false} otherwise.  The
8370 @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8372 It is customary to report unexpected failures with
8373 @code{AC_MSG_FAILURE}.  This macro does not try to link; use
8374 @code{AC_LINK_IFELSE} if you need to do that (@pxref{Running the
8375 Linker}).
8376 @end defmac
8378 @ovindex ERL
8379 For tests in Erlang, the @var{input} must be the source code of a module named
8380 @code{conftest}.  @code{AC_COMPILE_IFELSE} generates a @file{conftest.beam}
8381 file that can be interpreted by the Erlang virtual machine (@code{ERL}).  It is
8382 recommended to use @code{AC_LANG_PROGRAM} to specify the test program,
8383 to ensure that the Erlang module has the right name.
8385 @node Running the Linker
8386 @section Running the Linker
8388 To check for a library, a function, or a global variable, Autoconf
8389 @command{configure} scripts try to compile and link a small program that
8390 uses it.  This is unlike Metaconfig, which by default uses @code{nm} or
8391 @code{ar} on the C library to try to figure out which functions are
8392 available.  Trying to link with the function is usually a more reliable
8393 approach because it avoids dealing with the variations in the options
8394 and output formats of @code{nm} and @code{ar} and in the location of the
8395 standard libraries.  It also allows configuring for cross-compilation or
8396 checking a function's runtime behavior if needed.  On the other hand,
8397 it can be slower than scanning the libraries once, but accuracy is more
8398 important than speed.
8400 @code{AC_LINK_IFELSE} is used to compile test programs to test for
8401 functions and global variables.  It is also used by @code{AC_CHECK_LIB}
8402 to check for libraries (@pxref{Libraries}), by adding the library being
8403 checked for to @code{LIBS} temporarily and trying to link a small
8404 program.
8406 @anchor{AC_LINK_IFELSE}
8407 @defmac AC_LINK_IFELSE (@var{input}, @ovar{action-if-true}, @
8408   @ovar{action-if-false})
8409 @acindex{LINK_IFELSE}
8410 Run the compiler (and compilation flags) and the linker of the current
8411 language (@pxref{Language Choice}) on the @var{input}, run the shell
8412 commands @var{action-if-true} on success, @var{action-if-false}
8413 otherwise.  The @var{input} can be made by @code{AC_LANG_PROGRAM} and
8414 friends.
8416 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8417 current compilation flags.
8419 It is customary to report unexpected failures with
8420 @code{AC_MSG_FAILURE}.  This macro does not try to execute the program;
8421 use @code{AC_RUN_IFELSE} if you need to do that (@pxref{Runtime}).
8422 @end defmac
8424 The @code{AC_LINK_IFELSE} macro cannot be used for Erlang tests, since Erlang
8425 programs are interpreted and do not require linking.
8429 @node Runtime
8430 @section Checking Runtime Behavior
8432 Sometimes you need to find out how a system performs at runtime, such
8433 as whether a given function has a certain capability or bug.  If you
8434 can, make such checks when your program runs instead of when it is
8435 configured.  You can check for things like the machine's endianness when
8436 your program initializes itself.
8438 If you really need to test for a runtime behavior while configuring,
8439 you can write a test program to determine the result, and compile and
8440 run it using @code{AC_RUN_IFELSE}.  Avoid running test programs if
8441 possible, because this prevents people from configuring your package for
8442 cross-compiling.
8444 @anchor{AC_RUN_IFELSE}
8445 @defmac AC_RUN_IFELSE (@var{input}, @ovar{action-if-true}, @
8446   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
8447 @acindex{RUN_IFELSE}
8448 If @var{program} compiles and links successfully and returns an exit
8449 status of 0 when executed, run shell commands @var{action-if-true}.
8450 Otherwise, run shell commands @var{action-if-false}.
8452 The @var{input} can be made by @code{AC_LANG_PROGRAM} and friends.
8453 @code{LDFLAGS} and @code{LIBS} are used for linking, in addition to the
8454 compilation flags of the current language (@pxref{Language Choice}).
8456 If the compiler being used does not produce executables that run on the
8457 system where @command{configure} is being run, then the test program is
8458 not run.  If the optional shell commands @var{action-if-cross-compiling}
8459 are given, they are run instead.  Otherwise, @command{configure} prints
8460 an error message and exits.
8462 In the @var{action-if-false} section, the failing exit status is
8463 available in the shell variable @samp{$?}.  This exit status might be
8464 that of a failed compilation, or it might be that of a failed program
8465 execution.
8467 It is customary to report unexpected failures with
8468 @code{AC_MSG_FAILURE}.
8469 @end defmac
8471 Try to provide a pessimistic default value to use when cross-compiling
8472 makes runtime tests impossible.  You do this by passing the optional
8473 last argument to @code{AC_RUN_IFELSE}.  @command{autoconf} prints a
8474 warning message when creating @command{configure} each time it
8475 encounters a call to @code{AC_RUN_IFELSE} with no
8476 @var{action-if-cross-compiling} argument given.  You may ignore the
8477 warning, though users cannot configure your package for
8478 cross-compiling.  A few of the macros distributed with Autoconf produce
8479 this warning message.
8481 To configure for cross-compiling you can also choose a value for those
8482 parameters based on the canonical system name (@pxref{Manual
8483 Configuration}).  Alternatively, set up a test results cache file with
8484 the correct values for the host system (@pxref{Caching Results}).
8486 @ovindex cross_compiling
8487 To provide a default for calls of @code{AC_RUN_IFELSE} that are embedded
8488 in other macros, including a few of the ones that come with Autoconf,
8489 you can test whether the shell variable @code{cross_compiling} is set to
8490 @samp{yes}, and then use an alternate method to get the results instead
8491 of calling the macros.
8493 It is also permissible to temporarily assign to @code{cross_compiling}
8494 in order to force tests to behave as though they are in a
8495 cross-compilation environment, particularly since this provides a way to
8496 test your @var{action-if-cross-compiling} even when you are not using a
8497 cross-compiler.
8499 @example
8500 # We temporarily set cross-compile mode to force AC_COMPUTE_INT
8501 # to use the slow link-only method
8502 save_cross_compiling=$cross_compiling
8503 cross_compiling=yes
8504 AC_COMPUTE_INT([@dots{}])
8505 cross_compiling=$save_cross_compiling
8506 @end example
8508 A C or C++ runtime test should be portable.
8509 @xref{Portable C and C++}.
8511 Erlang tests must exit themselves the Erlang VM by calling the @code{halt/1}
8512 function: the given status code is used to determine the success of the test
8513 (status is @code{0}) or its failure (status is different than @code{0}), as
8514 explained above.  It must be noted that data output through the standard output
8515 (e.g., using @code{io:format/2}) may be truncated when halting the VM.
8516 Therefore, if a test must output configuration information, it is recommended
8517 to create and to output data into the temporary file named @file{conftest.out},
8518 using the functions of module @code{file}.  The @code{conftest.out} file is
8519 automatically deleted by the @code{AC_RUN_IFELSE} macro.  For instance, a
8520 simplified implementation of Autoconf's @code{AC_ERLANG_SUBST_LIB_DIR}
8521 macro is:
8523 @example
8524 AC_INIT([LibdirTest], [1.0], [bug-libdirtest@@example.org])
8525 AC_ERLANG_NEED_ERL
8526 AC_LANG(Erlang)
8527 AC_RUN_IFELSE(
8528   [AC_LANG_PROGRAM([], [dnl
8529     file:write_file("conftest.out", code:lib_dir()),
8530     halt(0)])],
8531   [echo "code:lib_dir() returned: `cat conftest.out`"],
8532   [AC_MSG_FAILURE([test Erlang program execution failed])])
8533 @end example
8536 @node Systemology
8537 @section Systemology
8538 @cindex Systemology
8540 This section aims at presenting some systems and pointers to
8541 documentation.  It may help you addressing particular problems reported
8542 by users.
8544 @uref{http://@/www.opengroup.org/@/susv3, Posix-conforming systems} are
8545 derived from the @uref{http://@/www.bell-labs.com/@/history/@/unix/, Unix
8546 operating system}.
8548 The @uref{http://@/bhami.com/@/rosetta.html, Rosetta Stone for Unix}
8549 contains a table correlating the features of various Posix-conforming
8550 systems.  @uref{http://@/www.levenez.com/@/unix/, Unix History} is a
8551 simplified diagram of how many Unix systems were derived from each
8552 other.
8554 @uref{http://@/heirloom.sourceforge.net/, The Heirloom Project}
8555 provides some variants of traditional implementations of Unix utilities.
8557 @table @asis
8558 @item Darwin
8559 @cindex Darwin
8560 Darwin is also known as Mac OS X@.  Beware that the file system @emph{can} be
8561 case-preserving, but case insensitive.  This can cause nasty problems,
8562 since for instance the installation attempt for a package having an
8563 @file{INSTALL} file can result in @samp{make install} report that
8564 nothing was to be done!
8566 That's all dependent on whether the file system is a UFS (case
8567 sensitive) or HFS+ (case preserving).  By default Apple wants you to
8568 install the OS on HFS+.  Unfortunately, there are some pieces of
8569 software which really need to be built on UFS@.  We may want to rebuild
8570 Darwin to have both UFS and HFS+ available (and put the /local/build
8571 tree on the UFS).
8573 @item @acronym{QNX} 4.25
8574 @cindex @acronym{QNX} 4.25
8575 @c FIXME: Please, if you feel like writing something more precise,
8576 @c it'd be great.  In particular, I can't understand the difference with
8577 @c QNX Neutrino.
8578 @acronym{QNX} is a realtime operating system running on Intel architecture
8579 meant to be scalable from the small embedded systems to the hundred
8580 processor super-computer.  It claims to be Posix certified.  More
8581 information is available on the
8582 @uref{http://@/www.qnx.com/, @acronym{QNX} home page}.
8584 @item Tru64
8585 @cindex Tru64
8586 @uref{http://@/h30097.www3.hp.com/@/docs/,
8587 Documentation of several versions of Tru64} is available in different
8588 formats.
8590 @item Unix version 7
8591 @cindex Unix version 7
8592 @cindex V7
8593 Officially this was called the ``Seventh Edition'' of ``the @sc{unix}
8594 time-sharing system'' but we use the more-common name ``Unix version 7''.
8595 Documentation is available in the
8596 @uref{http://@/plan9.bell-labs.com/@/7thEdMan/, Unix Seventh Edition Manual}.
8597 Previous versions of Unix are called ``Unix version 6'', etc., but
8598 they were not as widely used.
8599 @end table
8602 @node Multiple Cases
8603 @section Multiple Cases
8605 Some operations are accomplished in several possible ways, depending on
8606 the OS variant.  Checking for them essentially requires a ``case
8607 statement''.  Autoconf does not directly provide one; however, it is
8608 easy to simulate by using a shell variable to keep track of whether a
8609 way to perform the operation has been found yet.
8611 Here is an example that uses the shell variable @code{fstype} to keep
8612 track of whether the remaining cases need to be checked.
8614 @example
8615 @group
8616 AC_MSG_CHECKING([how to get file system type])
8617 fstype=no
8618 # The order of these tests is important.
8619 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statvfs.h>
8620 #include <sys/fstyp.h>]])],
8621                   [AC_DEFINE([FSTYPE_STATVFS], [1],
8622                      [Define if statvfs exists.])
8623                    fstype=SVR4])
8624 if test $fstype = no; then
8625   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8626 #include <sys/fstyp.h>]])],
8627                   [AC_DEFINE([FSTYPE_USG_STATFS], [1],
8628                      [Define if USG statfs.])
8629                    fstype=SVR3])
8631 if test $fstype = no; then
8632   AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <sys/statfs.h>
8633 #include <sys/vmount.h>]])]),
8634                   [AC_DEFINE([FSTYPE_AIX_STATFS], [1],
8635                      [Define if AIX statfs.])
8636                    fstype=AIX])
8638 # (more cases omitted here)
8639 AC_MSG_RESULT([$fstype])
8640 @end group
8641 @end example
8643 @c ====================================================== Results of Tests.
8645 @node Results
8646 @chapter Results of Tests
8648 Once @command{configure} has determined whether a feature exists, what can
8649 it do to record that information?  There are four sorts of things it can
8650 do: define a C preprocessor symbol, set a variable in the output files,
8651 save the result in a cache file for future @command{configure} runs, and
8652 print a message letting the user know the result of the test.
8654 @menu
8655 * Defining Symbols::            Defining C preprocessor symbols
8656 * Setting Output Variables::    Replacing variables in output files
8657 * Special Chars in Variables::  Characters to beware of in variables
8658 * Caching Results::             Speeding up subsequent @command{configure} runs
8659 * Printing Messages::           Notifying @command{configure} users
8660 @end menu
8662 @node Defining Symbols
8663 @section Defining C Preprocessor Symbols
8665 A common action to take in response to a feature test is to define a C
8666 preprocessor symbol indicating the results of the test.  That is done by
8667 calling @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}.
8669 By default, @code{AC_OUTPUT} places the symbols defined by these macros
8670 into the output variable @code{DEFS}, which contains an option
8671 @option{-D@var{symbol}=@var{value}} for each symbol defined.  Unlike in
8672 Autoconf version 1, there is no variable @code{DEFS} defined while
8673 @command{configure} is running.  To check whether Autoconf macros have
8674 already defined a certain C preprocessor symbol, test the value of the
8675 appropriate cache variable, as in this example:
8677 @example
8678 AC_CHECK_FUNC([vprintf], [AC_DEFINE([HAVE_VPRINTF], [1],
8679                           [Define if vprintf exists.])])
8680 if test "$ac_cv_func_vprintf" != yes; then
8681   AC_CHECK_FUNC([_doprnt], [AC_DEFINE([HAVE_DOPRNT], [1],
8682                             [Define if _doprnt exists.])])
8684 @end example
8686 If @code{AC_CONFIG_HEADERS} has been called, then instead of creating
8687 @code{DEFS}, @code{AC_OUTPUT} creates a header file by substituting the
8688 correct values into @code{#define} statements in a template file.
8689 @xref{Configuration Headers}, for more information about this kind of
8690 output.
8692 @defmac AC_DEFINE (@var{variable}, @var{value}, @ovar{description})
8693 @defmacx AC_DEFINE (@var{variable})
8694 @cvindex @var{variable}
8695 @acindex{DEFINE}
8696 Define @var{variable} to @var{value} (verbatim), by defining a C
8697 preprocessor macro for @var{variable}.  @var{variable} should be a C
8698 identifier, optionally suffixed by a parenthesized argument list to
8699 define a C preprocessor macro with arguments.  The macro argument list,
8700 if present, should be a comma-separated list of C identifiers, possibly
8701 terminated by an ellipsis @samp{...} if C99 syntax is employed.
8702 @var{variable} should not contain comments, white space, trigraphs,
8703 backslash-newlines, universal character names, or non-@acronym{ASCII}
8704 characters.
8706 @var{value} may contain backslash-escaped newlines, which will be
8707 preserved if you use @code{AC_CONFIG_HEADERS} but flattened if passed
8708 via @code{@@DEFS@@} (with no effect on the compilation, since the
8709 preprocessor sees only one line in the first place).  @var{value} should
8710 not contain raw newlines.  If you are not using
8711 @code{AC_CONFIG_HEADERS}, @var{value} should not contain any @samp{#}
8712 characters, as @command{make} tends to eat them.  To use a shell
8713 variable, use @code{AC_DEFINE_UNQUOTED} instead.
8715 @var{description} is only useful if you are using
8716 @code{AC_CONFIG_HEADERS}.  In this case, @var{description} is put into
8717 the generated @file{config.h.in} as the comment before the macro define.
8718 The following example defines the C preprocessor variable
8719 @code{EQUATION} to be the string constant @samp{"$a > $b"}:
8721 @example
8722 AC_DEFINE([EQUATION], ["$a > $b"],
8723   [Equation string.])
8724 @end example
8726 If neither @var{value} nor @var{description} are given, then
8727 @var{value} defaults to 1 instead of to the empty string.  This is for
8728 backwards compatibility with older versions of Autoconf, but this usage
8729 is obsolescent and may be withdrawn in future versions of Autoconf.
8731 If the @var{variable} is a literal string, it is passed to
8732 @code{m4_pattern_allow} (@pxref{Forbidden Patterns}).
8734 If multiple @code{AC_DEFINE} statements are executed for the same
8735 @var{variable} name (not counting any parenthesized argument list),
8736 the last one wins.
8737 @end defmac
8739 @defmac AC_DEFINE_UNQUOTED (@var{variable}, @var{value}, @ovar{description})
8740 @defmacx AC_DEFINE_UNQUOTED (@var{variable})
8741 @acindex{DEFINE_UNQUOTED}
8742 @cvindex @var{variable}
8743 Like @code{AC_DEFINE}, but three shell expansions are
8744 performed---once---on @var{variable} and @var{value}: variable expansion
8745 (@samp{$}), command substitution (@samp{`}), and backslash escaping
8746 (@samp{\}).  Single and double quote characters in the value have no
8747 special meaning.  Use this macro instead of @code{AC_DEFINE} when
8748 @var{variable} or @var{value} is a shell variable.  Examples:
8750 @example
8751 AC_DEFINE_UNQUOTED([config_machfile], ["$machfile"],
8752   [Configuration machine file.])
8753 AC_DEFINE_UNQUOTED([GETGROUPS_T], [$ac_cv_type_getgroups],
8754   [getgroups return type.])
8755 AC_DEFINE_UNQUOTED([$ac_tr_hdr], [1],
8756   [Translated header name.])
8757 @end example
8758 @end defmac
8760 Due to a syntactical bizarreness of the Bourne shell, do not use
8761 semicolons to separate @code{AC_DEFINE} or @code{AC_DEFINE_UNQUOTED}
8762 calls from other macro calls or shell code; that can cause syntax errors
8763 in the resulting @command{configure} script.  Use either blanks or
8764 newlines.  That is, do this:
8766 @example
8767 AC_CHECK_HEADER([elf.h],
8768   [AC_DEFINE([SVR4], [1], [System V Release 4]) LIBS="-lelf $LIBS"])
8769 @end example
8771 @noindent
8772 or this:
8774 @example
8775 AC_CHECK_HEADER([elf.h],
8776   [AC_DEFINE([SVR4], [1], [System V Release 4])
8777    LIBS="-lelf $LIBS"])
8778 @end example
8780 @noindent
8781 instead of this:
8783 @example
8784 AC_CHECK_HEADER([elf.h],
8785   [AC_DEFINE([SVR4], [1], [System V Release 4]); LIBS="-lelf $LIBS"])
8786 @end example
8788 @node Setting Output Variables
8789 @section Setting Output Variables
8790 @cindex Output variables
8792 Another way to record the results of tests is to set @dfn{output
8793 variables}, which are shell variables whose values are substituted into
8794 files that @command{configure} outputs.  The two macros below create new
8795 output variables.  @xref{Preset Output Variables}, for a list of output
8796 variables that are always available.
8798 @defmac AC_SUBST (@var{variable}, @ovar{value})
8799 @acindex{SUBST}
8800 Create an output variable from a shell variable.  Make @code{AC_OUTPUT}
8801 substitute the variable @var{variable} into output files (typically one
8802 or more makefiles).  This means that @code{AC_OUTPUT}
8803 replaces instances of @samp{@@@var{variable}@@} in input files with the
8804 value that the shell variable @var{variable} has when @code{AC_OUTPUT}
8805 is called.  The value can contain any non-@code{NUL} character, including
8806 newline.  If you are using Automake 1.11 or newer, for newlines in values
8807 you might want to consider using @code{AM_SUBST_NOTMAKE} to prevent
8808 @command{automake} from adding a line @code{@var{variable} =
8809 @@@var{variable}@@} to the @file{Makefile.in} files (@pxref{Optional, ,
8810 Automake, automake, Other things Automake recognizes}).
8812 Variable occurrences should not overlap: e.g., an input file should
8813 not contain @samp{@@@var{var1}@@@var{var2}@@} if @var{var1} and @var{var2}
8814 are variable names.
8815 The substituted value is not rescanned for more output variables;
8816 occurrences of @samp{@@@var{variable}@@} in the value are inserted
8817 literally into the output file.  (The algorithm uses the special marker
8818 @code{|#_!!_#|} internally, so neither the substituted value nor the
8819 output file may contain @code{|#_!!_#|}.)
8821 If @var{value} is given, in addition assign it to @var{variable}.
8823 The string @var{variable} is passed to @code{m4_pattern_allow}
8824 (@pxref{Forbidden Patterns}).
8825 @end defmac
8827 @defmac AC_SUBST_FILE (@var{variable})
8828 @acindex{SUBST_FILE}
8829 Another way to create an output variable from a shell variable.  Make
8830 @code{AC_OUTPUT} insert (without substitutions) the contents of the file
8831 named by shell variable @var{variable} into output files.  This means
8832 that @code{AC_OUTPUT} replaces instances of
8833 @samp{@@@var{variable}@@} in output files (such as @file{Makefile.in})
8834 with the contents of the file that the shell variable @var{variable}
8835 names when @code{AC_OUTPUT} is called.  Set the variable to
8836 @file{/dev/null} for cases that do not have a file to insert.
8837 This substitution occurs only when the @samp{@@@var{variable}@@} is on a
8838 line by itself, optionally surrounded by spaces and tabs.  The
8839 substitution replaces the whole line, including the spaces, tabs, and
8840 the terminating newline.
8842 This macro is useful for inserting makefile fragments containing
8843 special dependencies or other @command{make} directives for particular host
8844 or target types into makefiles.  For example, @file{configure.ac}
8845 could contain:
8847 @example
8848 AC_SUBST_FILE([host_frag])
8849 host_frag=$srcdir/conf/sun4.mh
8850 @end example
8852 @noindent
8853 and then a @file{Makefile.in} could contain:
8855 @example
8856 @@host_frag@@
8857 @end example
8859 The string @var{variable} is passed to @code{m4_pattern_allow}
8860 (@pxref{Forbidden Patterns}).
8861 @end defmac
8863 @cindex Precious Variable
8864 @cindex Variable, Precious
8865 Running @command{configure} in varying environments can be extremely
8866 dangerous.  If for instance the user runs @samp{CC=bizarre-cc
8867 ./configure}, then the cache, @file{config.h}, and many other output
8868 files depend upon @command{bizarre-cc} being the C compiler.  If
8869 for some reason the user runs @command{./configure} again, or if it is
8870 run via @samp{./config.status --recheck}, (@xref{Automatic Remaking},
8871 and @pxref{config.status Invocation}), then the configuration can be
8872 inconsistent, composed of results depending upon two different
8873 compilers.
8875 Environment variables that affect this situation, such as @samp{CC}
8876 above, are called @dfn{precious variables}, and can be declared as such
8877 by @code{AC_ARG_VAR}.
8879 @defmac AC_ARG_VAR (@var{variable}, @var{description})
8880 @acindex{ARG_VAR}
8881 Declare @var{variable} is a precious variable, and include its
8882 @var{description} in the variable section of @samp{./configure --help}.
8884 Being precious means that
8885 @itemize @minus
8886 @item
8887 @var{variable} is substituted via @code{AC_SUBST}.
8889 @item
8890 The value of @var{variable} when @command{configure} was launched is
8891 saved in the cache, including if it was not specified on the command
8892 line but via the environment.  Indeed, while @command{configure} can
8893 notice the definition of @code{CC} in @samp{./configure CC=bizarre-cc},
8894 it is impossible to notice it in @samp{CC=bizarre-cc ./configure},
8895 which, unfortunately, is what most users do.
8897 We emphasize that it is the @emph{initial} value of @var{variable} which
8898 is saved, not that found during the execution of @command{configure}.
8899 Indeed, specifying @samp{./configure FOO=foo} and letting
8900 @samp{./configure} guess that @code{FOO} is @code{foo} can be two
8901 different things.
8903 @item
8904 @var{variable} is checked for consistency between two
8905 @command{configure} runs.  For instance:
8907 @example
8908 $ @kbd{./configure --silent --config-cache}
8909 $ @kbd{CC=cc ./configure --silent --config-cache}
8910 configure: error: `CC' was not set in the previous run
8911 configure: error: changes in the environment can compromise \
8912 the build
8913 configure: error: run `make distclean' and/or \
8914 `rm config.cache' and start over
8915 @end example
8917 @noindent
8918 and similarly if the variable is unset, or if its content is changed.
8919 If the content has white space changes only, then the error is degraded
8920 to a warning only, but the old value is reused.
8922 @item
8923 @var{variable} is kept during automatic reconfiguration
8924 (@pxref{config.status Invocation}) as if it had been passed as a command
8925 line argument, including when no cache is used:
8927 @example
8928 $ @kbd{CC=/usr/bin/cc ./configure var=raboof --silent}
8929 $ @kbd{./config.status --recheck}
8930 running CONFIG_SHELL=/bin/sh /bin/sh ./configure var=raboof \
8931   CC=/usr/bin/cc  --no-create --no-recursion
8932 @end example
8933 @end itemize
8934 @end defmac
8936 @node Special Chars in Variables
8937 @section Special Characters in Output Variables
8938 @cindex Output variables, special characters in
8940 Many output variables are intended to be evaluated both by
8941 @command{make} and by the shell.  Some characters are expanded
8942 differently in these two contexts, so to avoid confusion these
8943 variables' values should not contain any of the following characters:
8945 @example
8946 " # $ & ' ( ) * ; < > ? [ \ ^ ` |
8947 @end example
8949 Also, these variables' values should neither contain newlines, nor start
8950 with @samp{~}, nor contain white space or @samp{:} immediately followed
8951 by @samp{~}.  The values can contain nonempty sequences of white space
8952 characters like tabs and spaces, but each such sequence might
8953 arbitrarily be replaced by a single space during substitution.
8955 These restrictions apply both to the values that @command{configure}
8956 computes, and to the values set directly by the user.  For example, the
8957 following invocations of @command{configure} are problematic, since they
8958 attempt to use special characters within @code{CPPFLAGS} and white space
8959 within @code{$(srcdir)}:
8961 @example
8962 CPPFLAGS='-DOUCH="&\"#$*?"' '../My Source/ouch-1.0/configure'
8964 '../My Source/ouch-1.0/configure' CPPFLAGS='-DOUCH="&\"#$*?"'
8965 @end example
8967 @node Caching Results
8968 @section Caching Results
8969 @cindex Cache
8971 To avoid checking for the same features repeatedly in various
8972 @command{configure} scripts (or in repeated runs of one script),
8973 @command{configure} can optionally save the results of many checks in a
8974 @dfn{cache file} (@pxref{Cache Files}).  If a @command{configure} script
8975 runs with caching enabled and finds a cache file, it reads the results
8976 of previous runs from the cache and avoids rerunning those checks.  As a
8977 result, @command{configure} can then run much faster than if it had to
8978 perform all of the checks every time.
8980 @defmac AC_CACHE_VAL (@var{cache-id}, @var{commands-to-set-it})
8981 @acindex{CACHE_VAL}
8982 Ensure that the results of the check identified by @var{cache-id} are
8983 available.  If the results of the check were in the cache file that was
8984 read, and @command{configure} was not given the @option{--quiet} or
8985 @option{--silent} option, print a message saying that the result was
8986 cached; otherwise, run the shell commands @var{commands-to-set-it}.  If
8987 the shell commands are run to determine the value, the value is
8988 saved in the cache file just before @command{configure} creates its output
8989 files.  @xref{Cache Variable Names}, for how to choose the name of the
8990 @var{cache-id} variable.
8992 The @var{commands-to-set-it} @emph{must have no side effects} except for
8993 setting the variable @var{cache-id}, see below.
8994 @end defmac
8996 @defmac AC_CACHE_CHECK (@var{message}, @var{cache-id}, @
8997   @var{commands-to-set-it})
8998 @acindex{CACHE_CHECK}
8999 A wrapper for @code{AC_CACHE_VAL} that takes care of printing the
9000 messages.  This macro provides a convenient shorthand for the most
9001 common way to use these macros.  It calls @code{AC_MSG_CHECKING} for
9002 @var{message}, then @code{AC_CACHE_VAL} with the @var{cache-id} and
9003 @var{commands} arguments, and @code{AC_MSG_RESULT} with @var{cache-id}.
9005 The @var{commands-to-set-it} @emph{must have no side effects} except for
9006 setting the variable @var{cache-id}, see below.
9007 @end defmac
9009 It is common to find buggy macros using @code{AC_CACHE_VAL} or
9010 @code{AC_CACHE_CHECK}, because people are tempted to call
9011 @code{AC_DEFINE} in the @var{commands-to-set-it}.  Instead, the code that
9012 @emph{follows} the call to @code{AC_CACHE_VAL} should call
9013 @code{AC_DEFINE}, by examining the value of the cache variable.  For
9014 instance, the following macro is broken:
9016 @example
9017 @group
9018 AC_DEFUN([AC_SHELL_TRUE],
9019 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9020                 [my_cv_shell_true_works=no
9021                  (true) 2>/dev/null && my_cv_shell_true_works=yes
9022                  if test "$my_cv_shell_true_works" = yes; then
9023                    AC_DEFINE([TRUE_WORKS], [1],
9024                              [Define if `true(1)' works properly.])
9025                  fi])
9027 @end group
9028 @end example
9030 @noindent
9031 This fails if the cache is enabled: the second time this macro is run,
9032 @code{TRUE_WORKS} @emph{will not be defined}.  The proper implementation
9035 @example
9036 @group
9037 AC_DEFUN([AC_SHELL_TRUE],
9038 [AC_CACHE_CHECK([whether true(1) works], [my_cv_shell_true_works],
9039                 [my_cv_shell_true_works=no
9040                  (true) 2>/dev/null && my_cv_shell_true_works=yes])
9041  if test "$my_cv_shell_true_works" = yes; then
9042    AC_DEFINE([TRUE_WORKS], [1],
9043              [Define if `true(1)' works properly.])
9044  fi
9046 @end group
9047 @end example
9049 Also, @var{commands-to-set-it} should not print any messages, for
9050 example with @code{AC_MSG_CHECKING}; do that before calling
9051 @code{AC_CACHE_VAL}, so the messages are printed regardless of whether
9052 the results of the check are retrieved from the cache or determined by
9053 running the shell commands.
9055 @menu
9056 * Cache Variable Names::        Shell variables used in caches
9057 * Cache Files::                 Files @command{configure} uses for caching
9058 * Cache Checkpointing::         Loading and saving the cache file
9059 @end menu
9061 @node Cache Variable Names
9062 @subsection Cache Variable Names
9063 @cindex Cache variable
9065 The names of cache variables should have the following format:
9067 @example
9068 @var{package-prefix}_cv_@var{value-type}_@var{specific-value}_@ovar{additional-options}
9069 @end example
9071 @noindent
9072 for example, @samp{ac_cv_header_stat_broken} or
9073 @samp{ac_cv_prog_gcc_traditional}.  The parts of the variable name are:
9075 @table @asis
9076 @item @var{package-prefix}
9077 An abbreviation for your package or organization; the same prefix you
9078 begin local Autoconf macros with, except lowercase by convention.
9079 For cache values used by the distributed Autoconf macros, this value is
9080 @samp{ac}.
9082 @item @code{_cv_}
9083 Indicates that this shell variable is a cache value.  This string
9084 @emph{must} be present in the variable name, including the leading
9085 underscore.
9087 @item @var{value-type}
9088 A convention for classifying cache values, to produce a rational naming
9089 system.  The values used in Autoconf are listed in @ref{Macro Names}.
9091 @item @var{specific-value}
9092 Which member of the class of cache values this test applies to.
9093 For example, which function (@samp{alloca}), program (@samp{gcc}), or
9094 output variable (@samp{INSTALL}).
9096 @item @var{additional-options}
9097 Any particular behavior of the specific member that this test applies to.
9098 For example, @samp{broken} or @samp{set}.  This part of the name may
9099 be omitted if it does not apply.
9100 @end table
9102 The values assigned to cache variables may not contain newlines.
9103 Usually, their values are Boolean (@samp{yes} or @samp{no}) or the
9104 names of files or functions; so this is not an important restriction.
9106 @node Cache Files
9107 @subsection Cache Files
9109 A cache file is a shell script that caches the results of configure
9110 tests run on one system so they can be shared between configure scripts
9111 and configure runs.  It is not useful on other systems.  If its contents
9112 are invalid for some reason, the user may delete or edit it.
9114 By default, @command{configure} uses no cache file,
9115 to avoid problems caused by accidental
9116 use of stale cache files.
9118 To enable caching, @command{configure} accepts @option{--config-cache} (or
9119 @option{-C}) to cache results in the file @file{config.cache}.
9120 Alternatively, @option{--cache-file=@var{file}} specifies that
9121 @var{file} be the cache file.  The cache file is created if it does not
9122 exist already.  When @command{configure} calls @command{configure} scripts in
9123 subdirectories, it uses the @option{--cache-file} argument so that they
9124 share the same cache.  @xref{Subdirectories}, for information on
9125 configuring subdirectories with the @code{AC_CONFIG_SUBDIRS} macro.
9127 @file{config.status} only pays attention to the cache file if it is
9128 given the @option{--recheck} option, which makes it rerun
9129 @command{configure}.
9131 It is wrong to try to distribute cache files for particular system types.
9132 There is too much room for error in doing that, and too much
9133 administrative overhead in maintaining them.  For any features that
9134 can't be guessed automatically, use the standard method of the canonical
9135 system type and linking files (@pxref{Manual Configuration}).
9137 The site initialization script can specify a site-wide cache file to
9138 use, instead of the usual per-program cache.  In this case, the cache
9139 file gradually accumulates information whenever someone runs a new
9140 @command{configure} script.  (Running @command{configure} merges the new cache
9141 results with the existing cache file.)  This may cause problems,
9142 however, if the system configuration (e.g., the installed libraries or
9143 compilers) changes and the stale cache file is not deleted.
9145 @node Cache Checkpointing
9146 @subsection Cache Checkpointing
9148 If your configure script, or a macro called from @file{configure.ac}, happens
9149 to abort the configure process, it may be useful to checkpoint the cache
9150 a few times at key points using @code{AC_CACHE_SAVE}.  Doing so
9151 reduces the amount of time it takes to rerun the configure script with
9152 (hopefully) the error that caused the previous abort corrected.
9154 @c FIXME: Do we really want to document this guy?
9155 @defmac AC_CACHE_LOAD
9156 @acindex{CACHE_LOAD}
9157 Loads values from existing cache file, or creates a new cache file if a
9158 cache file is not found.  Called automatically from @code{AC_INIT}.
9159 @end defmac
9161 @defmac AC_CACHE_SAVE
9162 @acindex{CACHE_SAVE}
9163 Flushes all cached values to the cache file.  Called automatically from
9164 @code{AC_OUTPUT}, but it can be quite useful to call
9165 @code{AC_CACHE_SAVE} at key points in @file{configure.ac}.
9166 @end defmac
9168 For instance:
9170 @example
9171 @r{ @dots{} AC_INIT, etc. @dots{}}
9172 @group
9173 # Checks for programs.
9174 AC_PROG_CC
9175 AC_PROG_AWK
9176 @r{ @dots{} more program checks @dots{}}
9177 AC_CACHE_SAVE
9178 @end group
9180 @group
9181 # Checks for libraries.
9182 AC_CHECK_LIB([nsl], [gethostbyname])
9183 AC_CHECK_LIB([socket], [connect])
9184 @r{ @dots{} more lib checks @dots{}}
9185 AC_CACHE_SAVE
9186 @end group
9188 @group
9189 # Might abort@dots{}
9190 AM_PATH_GTK([1.0.2], [], [AC_MSG_ERROR([GTK not in path])])
9191 AM_PATH_GTKMM([0.9.5], [], [AC_MSG_ERROR([GTK not in path])])
9192 @end group
9193 @r{ @dots{} AC_OUTPUT, etc. @dots{}}
9194 @end example
9196 @node Printing Messages
9197 @section Printing Messages
9198 @cindex Messages, from @command{configure}
9200 @command{configure} scripts need to give users running them several kinds
9201 of information.  The following macros print messages in ways appropriate
9202 for each kind.  The arguments to all of them get enclosed in shell
9203 double quotes, so the shell performs variable and back-quote
9204 substitution on them.
9206 These macros are all wrappers around the @command{echo} shell command.
9207 They direct output to the appropriate file descriptor (@pxref{File
9208 Descriptor Macros}).
9209 @command{configure} scripts should rarely need to run @command{echo} directly
9210 to print messages for the user.  Using these macros makes it easy to
9211 change how and when each kind of message is printed; such changes need
9212 only be made to the macro definitions and all the callers change
9213 automatically.
9215 To diagnose static issues, i.e., when @command{autoconf} is run, see
9216 @ref{Diagnostic Macros}.
9218 @defmac AC_MSG_CHECKING (@var{feature-description})
9219 @acindex{MSG_CHECKING}
9220 Notify the user that @command{configure} is checking for a particular
9221 feature.  This macro prints a message that starts with @samp{checking }
9222 and ends with @samp{...} and no newline.  It must be followed by a call
9223 to @code{AC_MSG_RESULT} to print the result of the check and the
9224 newline.  The @var{feature-description} should be something like
9225 @samp{whether the Fortran compiler accepts C++ comments} or @samp{for
9226 c89}.
9228 This macro prints nothing if @command{configure} is run with the
9229 @option{--quiet} or @option{--silent} option.
9230 @end defmac
9232 @anchor{AC_MSG_RESULT}
9233 @defmac AC_MSG_RESULT (@var{result-description})
9234 @acindex{MSG_RESULT}
9235 Notify the user of the results of a check.  @var{result-description} is
9236 almost always the value of the cache variable for the check, typically
9237 @samp{yes}, @samp{no}, or a file name.  This macro should follow a call
9238 to @code{AC_MSG_CHECKING}, and the @var{result-description} should be
9239 the completion of the message printed by the call to
9240 @code{AC_MSG_CHECKING}.
9242 This macro prints nothing if @command{configure} is run with the
9243 @option{--quiet} or @option{--silent} option.
9244 @end defmac
9246 @anchor{AC_MSG_NOTICE}
9247 @defmac AC_MSG_NOTICE (@var{message})
9248 @acindex{MSG_NOTICE}
9249 Deliver the @var{message} to the user.  It is useful mainly to print a
9250 general description of the overall purpose of a group of feature checks,
9251 e.g.,
9253 @example
9254 AC_MSG_NOTICE([checking if stack overflow is detectable])
9255 @end example
9257 This macro prints nothing if @command{configure} is run with the
9258 @option{--quiet} or @option{--silent} option.
9259 @end defmac
9261 @anchor{AC_MSG_ERROR}
9262 @defmac AC_MSG_ERROR (@var{error-description}, @dvar{exit-status, $?/1})
9263 @acindex{MSG_ERROR}
9264 Notify the user of an error that prevents @command{configure} from
9265 completing.  This macro prints an error message to the standard error
9266 output and exits @command{configure} with @var{exit-status} (@samp{$?}
9267 by default, except that @samp{0} is converted to @samp{1}).
9268 @var{error-description} should be something like @samp{invalid value
9269 $HOME for \$HOME}.
9271 The @var{error-description} should start with a lower-case letter, and
9272 ``cannot'' is preferred to ``can't''.
9273 @end defmac
9275 @defmac AC_MSG_FAILURE (@var{error-description}, @ovar{exit-status})
9276 @acindex{MSG_FAILURE}
9277 This @code{AC_MSG_ERROR} wrapper notifies the user of an error that
9278 prevents @command{configure} from completing @emph{and} that additional
9279 details are provided in @file{config.log}.  This is typically used when
9280 abnormal results are found during a compilation.
9281 @end defmac
9283 @anchor{AC_MSG_WARN}
9284 @defmac AC_MSG_WARN (@var{problem-description})
9285 @acindex{MSG_WARN}
9286 Notify the @command{configure} user of a possible problem.  This macro
9287 prints the message to the standard error output; @command{configure}
9288 continues running afterward, so macros that call @code{AC_MSG_WARN} should
9289 provide a default (back-up) behavior for the situations they warn about.
9290 @var{problem-description} should be something like @samp{ln -s seems to
9291 make hard links}.
9292 @end defmac
9296 @c ====================================================== Programming in M4.
9298 @node Programming in M4
9299 @chapter Programming in M4
9300 @cindex M4
9302 Autoconf is written on top of two layers: @dfn{M4sugar}, which provides
9303 convenient macros for pure M4 programming, and @dfn{M4sh}, which
9304 provides macros dedicated to shell script generation.
9306 As of this version of Autoconf, these two layers still contain
9307 experimental macros, whose interface might change in the future.  As a
9308 matter of fact, @emph{anything that is not documented must not be used}.
9310 @menu
9311 * M4 Quotation::                Protecting macros from unwanted expansion
9312 * Using autom4te::              The Autoconf executables backbone
9313 * Programming in M4sugar::      Convenient pure M4 macros
9314 @end menu
9316 @node M4 Quotation
9317 @section M4 Quotation
9318 @cindex M4 quotation
9319 @cindex quotation
9321 The most common problem with existing macros is an improper quotation.
9322 This section, which users of Autoconf can skip, but which macro writers
9323 @emph{must} read, first justifies the quotation scheme that was chosen
9324 for Autoconf and then ends with a rule of thumb.  Understanding the
9325 former helps one to follow the latter.
9327 @menu
9328 * Active Characters::           Characters that change the behavior of M4
9329 * One Macro Call::              Quotation and one macro call
9330 * Quoting and Parameters::      M4 vs. shell parameters
9331 * Quotation and Nested Macros::  Macros calling macros
9332 * Changequote is Evil::         Worse than INTERCAL: M4 + changequote
9333 * Quadrigraphs::                Another way to escape special characters
9334 * Balancing Parentheses::       Dealing with unbalanced parentheses
9335 * Quotation Rule Of Thumb::     One parenthesis, one quote
9336 @end menu
9338 @node Active Characters
9339 @subsection Active Characters
9341 To fully understand where proper quotation is important, you first need
9342 to know what the special characters are in Autoconf: @samp{#} introduces
9343 a comment inside which no macro expansion is performed, @samp{,}
9344 separates arguments, @samp{[} and @samp{]} are the quotes themselves,
9345 @samp{(} and @samp{)} (which M4 tries to match by pairs), and finally
9346 @samp{$} inside a macro definition.
9348 In order to understand the delicate case of macro calls, we first have
9349 to present some obvious failures.  Below they are ``obvious-ified'',
9350 but when you find them in real life, they are usually in disguise.
9352 Comments, introduced by a hash and running up to the newline, are opaque
9353 tokens to the top level: active characters are turned off, and there is
9354 no macro expansion:
9356 @example
9357 # define([def], ine)
9358 @result{}# define([def], ine)
9359 @end example
9361 Each time there can be a macro expansion, there is a quotation
9362 expansion, i.e., one level of quotes is stripped:
9364 @example
9365 int tab[10];
9366 @result{}int tab10;
9367 [int tab[10];]
9368 @result{}int tab[10];
9369 @end example
9371 Without this in mind, the reader might try hopelessly to use her macro
9372 @code{array}:
9374 @example
9375 define([array], [int tab[10];])
9376 array
9377 @result{}int tab10;
9378 [array]
9379 @result{}array
9380 @end example
9382 @noindent
9383 How can you correctly output the intended results@footnote{Using
9384 @code{defn}.}?
9387 @node One Macro Call
9388 @subsection One Macro Call
9390 Let's proceed on the interaction between active characters and macros
9391 with this small macro, which just returns its first argument:
9393 @example
9394 define([car], [$1])
9395 @end example
9397 @noindent
9398 The two pairs of quotes above are not part of the arguments of
9399 @code{define}; rather, they are understood by the top level when it
9400 tries to find the arguments of @code{define}.  Therefore, assuming
9401 @code{car} is not already defined, it is equivalent to write:
9403 @example
9404 define(car, $1)
9405 @end example
9407 @noindent
9408 But, while it is acceptable for a @file{configure.ac} to avoid unnecessary
9409 quotes, it is bad practice for Autoconf macros which must both be more
9410 robust and also advocate perfect style.
9412 At the top level, there are only two possibilities: either you
9413 quote or you don't:
9415 @example
9416 car(foo, bar, baz)
9417 @result{}foo
9418 [car(foo, bar, baz)]
9419 @result{}car(foo, bar, baz)
9420 @end example
9422 Let's pay attention to the special characters:
9424 @example
9425 car(#)
9426 @error{}EOF in argument list
9427 @end example
9429 The closing parenthesis is hidden in the comment; with a hypothetical
9430 quoting, the top level understood it this way:
9432 @example
9433 car([#)]
9434 @end example
9436 @noindent
9437 Proper quotation, of course, fixes the problem:
9439 @example
9440 car([#])
9441 @result{}#
9442 @end example
9444 Here are more examples:
9446 @example
9447 car(foo, bar)
9448 @result{}foo
9449 car([foo, bar])
9450 @result{}foo, bar
9451 car((foo, bar))
9452 @result{}(foo, bar)
9453 car([(foo], [bar)])
9454 @result{}(foo
9455 define([a], [b])
9456 @result{}
9457 car(a)
9458 @result{}b
9459 car([a])
9460 @result{}b
9461 car([[a]])
9462 @result{}a
9463 car([[[a]]])
9464 @result{}[a]
9465 @end example
9467 @node Quoting and Parameters
9468 @subsection Quoting and Parameters
9470 When M4 encounters @samp{$} within a macro definition, followed
9471 immediately by a character it recognizes (@samp{0}@dots{}@samp{9},
9472 @samp{#}, @samp{@@}, or @samp{*}), it will perform M4 parameter
9473 expansion.  This happens regardless of how many layers of quotes the
9474 parameter expansion is nested within, or even if it occurs in text that
9475 will be rescanned as a comment.
9477 @example
9478 define([none], [$1])
9479 @result{}
9480 define([one], [[$1]])
9481 @result{}
9482 define([two], [[[$1]]])
9483 @result{}
9484 define([comment], [# $1])
9485 @result{}
9486 define([active], [ACTIVE])
9487 @result{}
9488 none([active])
9489 @result{}ACTIVE
9490 one([active])
9491 @result{}active
9492 two([active])
9493 @result{}[active]
9494 comment([active])
9495 @result{}# active
9496 @end example
9498 On the other hand, since autoconf generates shell code, you often want
9499 to output shell variable expansion, rather than performing M4 parameter
9500 expansion.  To do this, you must use M4 quoting to separate the @samp{$}
9501 from the next character in the definition of your macro.  If the macro
9502 definition occurs in single-quoted text, then insert another level of
9503 quoting; if the usage is already inside a double-quoted string, then
9504 split it into concatenated strings.
9506 @example
9507 define([single], [a single-quoted $[]1 definition])
9508 @result{}
9509 define([double], [[a double-quoted $][1 definition]])
9510 @result{}
9511 single
9512 @result{}a single-quoted $1 definition
9513 double
9514 @result{}a double-quoted $1 definition
9515 @end example
9517 Posix states that M4 implementations are free to provide implementation
9518 extensions when @samp{$@{} is encountered in a macro definition.
9519 Autoconf reserves the longer sequence @samp{$@{@{} for use with planned
9520 extensions that will be available in the future @acronym{GNU} M4 2.0,
9521 but guarantees that all other instances of @samp{$@{} will be output
9522 literally.  Therefore, this idiom can also be used to output shell code
9523 parameter references:
9525 @example
9526 define([first], [$@{1@}])first
9527 @result{}$@{1@}
9528 @end example
9530 Posix also states that @samp{$11} should expand to the first parameter
9531 concatenated with a literal @samp{1}, although some versions of
9532 @acronym{GNU} M4 expand the eleventh parameter instead.  For
9533 portability, you should only use single-digit M4 parameter expansion.
9535 With this in mind, we can explore the cases where macros invoke
9536 macros@enddots{}
9538 @node Quotation and Nested Macros
9539 @subsection Quotation and Nested Macros
9541 The examples below use the following macros:
9543 @example
9544 define([car], [$1])
9545 define([active], [ACT, IVE])
9546 define([array], [int tab[10]])
9547 @end example
9549 Each additional embedded macro call introduces other possible
9550 interesting quotations:
9552 @example
9553 car(active)
9554 @result{}ACT
9555 car([active])
9556 @result{}ACT, IVE
9557 car([[active]])
9558 @result{}active
9559 @end example
9561 In the first case, the top level looks for the arguments of @code{car},
9562 and finds @samp{active}.  Because M4 evaluates its arguments
9563 before applying the macro, @samp{active} is expanded, which results in:
9565 @example
9566 car(ACT, IVE)
9567 @result{}ACT
9568 @end example
9570 @noindent
9571 In the second case, the top level gives @samp{active} as first and only
9572 argument of @code{car}, which results in:
9574 @example
9575 active
9576 @result{}ACT, IVE
9577 @end example
9579 @noindent
9580 i.e., the argument is evaluated @emph{after} the macro that invokes it.
9581 In the third case, @code{car} receives @samp{[active]}, which results in:
9583 @example
9584 [active]
9585 @result{}active
9586 @end example
9588 @noindent
9589 exactly as we already saw above.
9591 The example above, applied to a more realistic example, gives:
9593 @example
9594 car(int tab[10];)
9595 @result{}int tab10;
9596 car([int tab[10];])
9597 @result{}int tab10;
9598 car([[int tab[10];]])
9599 @result{}int tab[10];
9600 @end example
9602 @noindent
9603 Huh?  The first case is easily understood, but why is the second wrong,
9604 and the third right?  To understand that, you must know that after
9605 M4 expands a macro, the resulting text is immediately subjected
9606 to macro expansion and quote removal.  This means that the quote removal
9607 occurs twice---first before the argument is passed to the @code{car}
9608 macro, and second after the @code{car} macro expands to the first
9609 argument.
9611 As the author of the Autoconf macro @code{car}, you then consider it to
9612 be incorrect that your users have to double-quote the arguments of
9613 @code{car}, so you ``fix'' your macro.  Let's call it @code{qar} for
9614 quoted car:
9616 @example
9617 define([qar], [[$1]])
9618 @end example
9620 @noindent
9621 and check that @code{qar} is properly fixed:
9623 @example
9624 qar([int tab[10];])
9625 @result{}int tab[10];
9626 @end example
9628 @noindent
9629 Ahhh!  That's much better.
9631 But note what you've done: now that the result of @code{qar} is always
9632 a literal string, the only time a user can use nested macros is if she
9633 relies on an @emph{unquoted} macro call:
9635 @example
9636 qar(active)
9637 @result{}ACT
9638 qar([active])
9639 @result{}active
9640 @end example
9642 @noindent
9643 leaving no way for her to reproduce what she used to do with @code{car}:
9645 @example
9646 car([active])
9647 @result{}ACT, IVE
9648 @end example
9650 @noindent
9651 Worse yet: she wants to use a macro that produces a set of @code{cpp}
9652 macros:
9654 @example
9655 define([my_includes], [#include <stdio.h>])
9656 car([my_includes])
9657 @result{}#include <stdio.h>
9658 qar(my_includes)
9659 @error{}EOF in argument list
9660 @end example
9662 This macro, @code{qar}, because it double quotes its arguments, forces
9663 its users to leave their macro calls unquoted, which is dangerous.
9664 Commas and other active symbols are interpreted by M4 before
9665 they are given to the macro, often not in the way the users expect.
9666 Also, because @code{qar} behaves differently from the other macros,
9667 it's an exception that should be avoided in Autoconf.
9669 @node Changequote is Evil
9670 @subsection @code{changequote} is Evil
9671 @cindex @code{changequote}
9673 The temptation is often high to bypass proper quotation, in particular
9674 when it's late at night.  Then, many experienced Autoconf hackers
9675 finally surrender to the dark side of the force and use the ultimate
9676 weapon: @code{changequote}.
9678 The M4 builtin @code{changequote} belongs to a set of primitives that
9679 allow one to adjust the syntax of the language to adjust it to one's
9680 needs.  For instance, by default M4 uses @samp{`} and @samp{'} as
9681 quotes, but in the context of shell programming (and actually of most
9682 programming languages), that's about the worst choice one can make:
9683 because of strings and back-quoted expressions in shell code (such as
9684 @samp{'this'} and @samp{`that`}), and because of literal characters in usual
9685 programming languages (as in @samp{'0'}), there are many unbalanced
9686 @samp{`} and @samp{'}.  Proper M4 quotation then becomes a nightmare, if
9687 not impossible.  In order to make M4 useful in such a context, its
9688 designers have equipped it with @code{changequote}, which makes it
9689 possible to choose another pair of quotes.  M4sugar, M4sh, Autoconf, and
9690 Autotest all have chosen to use @samp{[} and @samp{]}.  Not especially
9691 because they are unlikely characters, but @emph{because they are
9692 characters unlikely to be unbalanced}.
9694 There are other magic primitives, such as @code{changecom} to specify
9695 what syntactic forms are comments (it is common to see
9696 @samp{changecom(<!--, -->)} when M4 is used to produce HTML pages),
9697 @code{changeword} and @code{changesyntax} to change other syntactic
9698 details (such as the character to denote the @var{n}th argument, @samp{$} by
9699 default, the parentheses around arguments, etc.).
9701 These primitives are really meant to make M4 more useful for specific
9702 domains: they should be considered like command line options:
9703 @option{--quotes}, @option{--comments}, @option{--words}, and
9704 @option{--syntax}.  Nevertheless, they are implemented as M4 builtins, as
9705 it makes M4 libraries self contained (no need for additional options).
9707 There lies the problem@enddots{}
9709 @sp 1
9711 The problem is that it is then tempting to use them in the middle of an
9712 M4 script, as opposed to its initialization.  This, if not carefully
9713 thought out, can lead to disastrous effects: @emph{you are changing the
9714 language in the middle of the execution}.  Changing and restoring the
9715 syntax is often not enough: if you happened to invoke macros in between,
9716 these macros are lost, as the current syntax is probably not
9717 the one they were implemented with.
9719 @c FIXME: I've been looking for a short, real case example, but I
9720 @c lost them all :(
9723 @node Quadrigraphs
9724 @subsection Quadrigraphs
9725 @cindex quadrigraphs
9726 @cindex @samp{@@S|@@}
9727 @cindex @samp{@@&t@@}
9728 @c Info cannot handle `:' in index entries.
9729 @c @cindex @samp{@@<:@@}
9730 @c @cindex @samp{@@:>@@}
9731 @c @cindex @samp{@@%:@@}
9732 @c @cindex @samp{@@@{:@@}
9733 @c @cindex @samp{@@:@}@@}
9735 When writing an Autoconf macro you may occasionally need to generate
9736 special characters that are difficult to express with the standard
9737 Autoconf quoting rules.  For example, you may need to output the regular
9738 expression @samp{[^[]}, which matches any character other than @samp{[}.
9739 This expression contains unbalanced brackets so it cannot be put easily
9740 into an M4 macro.
9742 Additionally, there are a few m4sugar macros (such as @code{m4_split}
9743 and @code{m4_expand}) which internally use special markers in addition
9744 to the regular quoting characters.  If the arguments to these macros
9745 contain the literal strings @samp{-=<@{(} or @samp{)@}>=-}, the macros
9746 might behave incorrectly.
9748 You can work around these problems by using one of the following
9749 @dfn{quadrigraphs}:
9751 @table @samp
9752 @item @@<:@@
9753 @samp{[}
9754 @item @@:>@@
9755 @samp{]}
9756 @item @@S|@@
9757 @samp{$}
9758 @item @@%:@@
9759 @samp{#}
9760 @item @@@{:@@
9761 @samp{(}
9762 @item @@:@}@@
9763 @samp{)}
9764 @item @@&t@@
9765 Expands to nothing.
9766 @end table
9768 Quadrigraphs are replaced at a late stage of the translation process,
9769 after @command{m4} is run, so they do not get in the way of M4 quoting.
9770 For example, the string @samp{^@@<:@@}, independently of its quotation,
9771 appears as @samp{^[} in the output.
9773 The empty quadrigraph can be used:
9775 @itemize @minus
9776 @item to mark trailing spaces explicitly
9778 Trailing spaces are smashed by @command{autom4te}.  This is a feature.
9780 @item to produce quadrigraphs and other strings reserved by m4sugar
9782 For instance @samp{@@<@@&t@@:@@} produces @samp{@@<:@@}.  For a more
9783 contrived example:
9785 @example
9786 m4_define([a], [A])m4_define([b], [B])m4_define([c], [C])dnl
9787 m4_split([a )@}>=- b -=<@{( c])
9788 @result{}[a], [], [B], [], [c]
9789 m4_split([a )@}@@&t@@>=- b -=<@@&t@@@{( c])
9790 @result{}[a], [)@}>=-], [b], [-=<@{(], [c]
9791 @end example
9793 @item to escape @emph{occurrences} of forbidden patterns
9795 For instance you might want to mention @code{AC_FOO} in a comment, while
9796 still being sure that @command{autom4te} still catches unexpanded
9797 @samp{AC_*}.  Then write @samp{AC@@&t@@_FOO}.
9798 @end itemize
9800 The name @samp{@@&t@@} was suggested by Paul Eggert:
9802 @quotation
9803 I should give some credit to the @samp{@@&t@@} pun.  The @samp{&} is my
9804 own invention, but the @samp{t} came from the source code of the
9805 @sc{algol68c} compiler, written by Steve Bourne (of Bourne shell fame),
9806 and which used @samp{mt} to denote the empty string.  In C, it would
9807 have looked like something like:
9809 @example
9810 char const mt[] = "";
9811 @end example
9813 @noindent
9814 but of course the source code was written in Algol 68.
9816 I don't know where he got @samp{mt} from: it could have been his own
9817 invention, and I suppose it could have been a common pun around the
9818 Cambridge University computer lab at the time.
9819 @end quotation
9822 @node Balancing Parentheses
9823 @subsection Dealing with unbalanced parentheses
9824 @cindex balancing parentheses
9825 @cindex parentheses, balancing
9826 @cindex unbalanced parentheses, managing
9828 One of the pitfalls of portable shell programming is that @command{case}
9829 statements require unbalanced parentheses (@pxref{case, , Limitations of
9830 Shell Builtins}).  With syntax highlighting
9831 editors, the presence of unbalanced @samp{)} can interfere with editors
9832 that perform syntax highlighting of macro contents based on finding the
9833 matching @samp{(}.  Another concern is how much editing must be done
9834 when transferring code snippets between shell scripts and macro
9835 definitions.  But most importantly, the presence of unbalanced
9836 parentheses can introduce expansion bugs.
9838 For an example, here is an underquoted attempt to use the macro
9839 @code{my_case}, which happens to expand to a portable @command{case}
9840 statement:
9842 @example
9843 AC_DEFUN([my_case],
9844 [case $file_name in
9845   *.c) echo "C source code";;
9846 esac])
9847 AS_IF(:, my_case)
9848 @end example
9850 @noindent
9851 In the above example, the @code{AS_IF} call underquotes its arguments.
9852 As a result, the unbalanced @samp{)} generated by the premature
9853 expansion of @code{my_case} results in expanding @code{AS_IF} with a
9854 truncated parameter, and the expansion is syntactically invalid:
9856 @example
9857 if :; then
9858   case $file_name in
9859   *.c
9860 fi echo "C source code";;
9861 esac)
9862 @end example
9864 If nothing else, this should emphasize the importance of the quoting
9865 arguments to macro calls.  On the other hand, there are several
9866 variations for defining @code{my_case} to be more robust, even when used
9867 without proper quoting, each with some benefits and some drawbacks.
9869 @itemize @w{}
9870 @item Creative literal shell comment
9871 @example
9872 AC_DEFUN([my_case],
9873 [case $file_name in #(
9874   *.c) echo "C source code";;
9875 esac])
9876 @end example
9877 @noindent
9878 This version provides balanced parentheses to several editors, and can
9879 be copied and pasted into a terminal as is.  Unfortunately, it is still
9880 unbalanced as an Autoconf argument, since @samp{#(} is an M4 comment
9881 that masks the normal properties of @samp{(}.
9883 @item Quadrigraph shell comment
9884 @example
9885 AC_DEFUN([my_case],
9886 [case $file_name in @@%:@@(
9887   *.c) echo "C source code";;
9888 esac])
9889 @end example
9890 @noindent
9891 This version provides balanced parentheses to even more editors, and can
9892 be used as a balanced Autoconf argument.  Unfortunately, it requires
9893 some editing before it can be copied and pasted into a terminal, and the
9894 use of the quadrigraph @samp{@@%:@@} for @samp{#} reduces readability.
9896 @item Quoting just the parenthesis
9897 @example
9898 AC_DEFUN([my_case],
9899 [case $file_name in
9900   *.c[)] echo "C source code";;
9901 esac])
9902 @end example
9903 @noindent
9904 This version quotes the @samp{)}, so that it can be used as a balanced
9905 Autoconf argument.  As written, this is not balanced to an editor, but
9906 it can be coupled with @samp{[#(]} to meet that need, too.  However, it
9907 still requires some edits before it can be copied and pasted into a
9908 terminal.
9910 @item Double-quoting the entire statement
9911 @example
9912 AC_DEFUN([my_case],
9913 [[case $file_name in #(
9914   *.c) echo "C source code";;
9915 esac]])
9916 @end example
9917 @noindent
9918 Since the entire macro is double-quoted, there is no problem with using
9919 this as an Autoconf argument; and since the double-quoting is over the
9920 entire statement, this code can be easily copied and pasted into a
9921 terminal.  However, the double quoting prevents the expansion of any
9922 macros inside the case statement, which may cause its own set of
9923 problems.
9925 @item Using @code{AS_CASE}
9926 @example
9927 AC_DEFUN([my_case],
9928 [AS_CASE([$file_name],
9929   [*.c], [echo "C source code"])])
9930 @end example
9931 @noindent
9932 This version avoids the balancing issue altogether, by relying on
9933 @code{AS_CASE} (@pxref{Common Shell Constructs}); it also allows for the
9934 expansion of @code{AC_REQUIRE} to occur prior to the entire case
9935 statement, rather than within a branch of the case statement that might
9936 not be taken.  However, the abstraction comes with a penalty that it is
9937 no longer a quick copy, paste, and edit to get back to shell code.
9938 @end itemize
9941 @node Quotation Rule Of Thumb
9942 @subsection Quotation Rule Of Thumb
9944 To conclude, the quotation rule of thumb is:
9946 @center @emph{One pair of quotes per pair of parentheses.}
9948 Never over-quote, never under-quote, in particular in the definition of
9949 macros.  In the few places where the macros need to use brackets
9950 (usually in C program text or regular expressions), properly quote
9951 @emph{the arguments}!
9953 It is common to read Autoconf programs with snippets like:
9955 @example
9956 AC_TRY_LINK(
9957 changequote(<<, >>)dnl
9958 <<#include <time.h>
9959 #ifndef tzname /* For SGI.  */
9960 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9961 #endif>>,
9962 changequote([, ])dnl
9963 [atoi (*tzname);], ac_cv_var_tzname=yes, ac_cv_var_tzname=no)
9964 @end example
9966 @noindent
9967 which is incredibly useless since @code{AC_TRY_LINK} is @emph{already}
9968 double quoting, so you just need:
9970 @example
9971 AC_TRY_LINK(
9972 [#include <time.h>
9973 #ifndef tzname /* For SGI.  */
9974 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
9975 #endif],
9976             [atoi (*tzname);],
9977             [ac_cv_var_tzname=yes],
9978             [ac_cv_var_tzname=no])
9979 @end example
9981 @noindent
9982 The M4-fluent reader might note that these two examples are rigorously
9983 equivalent, since M4 swallows both the @samp{changequote(<<, >>)}
9984 and @samp{<<} @samp{>>} when it @dfn{collects} the arguments: these
9985 quotes are not part of the arguments!
9987 Simplified, the example above is just doing this:
9989 @example
9990 changequote(<<, >>)dnl
9991 <<[]>>
9992 changequote([, ])dnl
9993 @end example
9995 @noindent
9996 instead of simply:
9998 @example
9999 [[]]
10000 @end example
10002 With macros that do not double quote their arguments (which is the
10003 rule), double-quote the (risky) literals:
10005 @example
10006 AC_LINK_IFELSE([AC_LANG_PROGRAM(
10007 [[#include <time.h>
10008 #ifndef tzname /* For SGI.  */
10009 extern char *tzname[]; /* RS6000 and others reject char **tzname.  */
10010 #endif]],
10011                                 [atoi (*tzname);])],
10012                [ac_cv_var_tzname=yes],
10013                [ac_cv_var_tzname=no])
10014 @end example
10016 Please note that the macro @code{AC_TRY_LINK} is obsolete, so you really
10017 should be using @code{AC_LINK_IFELSE} instead.
10019 @xref{Quadrigraphs}, for what to do if you run into a hopeless case
10020 where quoting does not suffice.
10022 When you create a @command{configure} script using newly written macros,
10023 examine it carefully to check whether you need to add more quotes in
10024 your macros.  If one or more words have disappeared in the M4
10025 output, you need more quotes.  When in doubt, quote.
10027 However, it's also possible to put on too many layers of quotes.  If
10028 this happens, the resulting @command{configure} script may contain
10029 unexpanded macros.  The @command{autoconf} program checks for this problem
10030 by looking for the string @samp{AC_} in @file{configure}.  However, this
10031 heuristic does not work in general: for example, it does not catch
10032 overquoting in @code{AC_DEFINE} descriptions.
10035 @c ---------------------------------------- Using autom4te
10037 @node Using autom4te
10038 @section Using @command{autom4te}
10040 The Autoconf suite, including M4sugar, M4sh, and Autotest, in addition
10041 to Autoconf per se, heavily rely on M4.  All these different uses
10042 revealed common needs factored into a layer over M4:
10043 @command{autom4te}@footnote{
10045 Yet another great name from Lars J. Aas.
10049 @command{autom4te} is a preprocessor that is like @command{m4}.
10050 It supports M4 extensions designed for use in tools like Autoconf.
10052 @menu
10053 * autom4te Invocation::         A @acronym{GNU} M4 wrapper
10054 * Customizing autom4te::        Customizing the Autoconf package
10055 @end menu
10057 @node autom4te Invocation
10058 @subsection Invoking @command{autom4te}
10060 The command line arguments are modeled after M4's:
10062 @example
10063 autom4te @var{options} @var{files}
10064 @end example
10066 @noindent
10067 @evindex M4
10068 where the @var{files} are directly passed to @command{m4}.  By default,
10069 @acronym{GNU} M4 is found during configuration, but the environment
10070 variable
10071 @env{M4} can be set to tell @command{autom4te} where to look.  In addition
10072 to the regular expansion, it handles the replacement of the quadrigraphs
10073 (@pxref{Quadrigraphs}), and of @samp{__oline__}, the current line in the
10074 output.  It supports an extended syntax for the @var{files}:
10076 @table @file
10077 @item @var{file}.m4f
10078 This file is an M4 frozen file.  Note that @emph{all the previous files
10079 are ignored}.  See the option @option{--melt} for the rationale.
10081 @item @var{file}?
10082 If found in the library path, the @var{file} is included for expansion,
10083 otherwise it is ignored instead of triggering a failure.
10084 @end table
10086 @sp 1
10088 Of course, it supports the Autoconf common subset of options:
10090 @table @option
10091 @item --help
10092 @itemx -h
10093 Print a summary of the command line options and exit.
10095 @item --version
10096 @itemx -V
10097 Print the version number of Autoconf and exit.
10099 @item --verbose
10100 @itemx -v
10101 Report processing steps.
10103 @item --debug
10104 @itemx -d
10105 Don't remove the temporary files and be even more verbose.
10107 @item --include=@var{dir}
10108 @itemx -I @var{dir}
10109 Also look for input files in @var{dir}.  Multiple invocations
10110 accumulate.
10112 @item --output=@var{file}
10113 @itemx -o @var{file}
10114 Save output (script or trace) to @var{file}.  The file @option{-} stands
10115 for the standard output.
10116 @end table
10118 @sp 1
10120 As an extension of @command{m4}, it includes the following options:
10122 @table @option
10123 @item --warnings=@var{category}
10124 @itemx -W @var{category}
10125 @evindex WARNINGS
10126 @c FIXME: Point to the M4sugar macros, not Autoconf's.
10127 Report the warnings related to @var{category} (which can actually be a
10128 comma separated list).  @xref{Reporting Messages}, macro
10129 @code{AC_DIAGNOSE}, for a comprehensive list of categories.  Special
10130 values include:
10132 @table @samp
10133 @item all
10134 report all the warnings
10136 @item none
10137 report none
10139 @item error
10140 treats warnings as errors
10142 @item no-@var{category}
10143 disable warnings falling into @var{category}
10144 @end table
10146 Warnings about @samp{syntax} are enabled by default, and the environment
10147 variable @env{WARNINGS}, a comma separated list of categories, is
10148 honored.  @samp{autom4te -W @var{category}} actually
10149 behaves as if you had run:
10151 @example
10152 autom4te --warnings=syntax,$WARNINGS,@var{category}
10153 @end example
10155 @noindent
10156 For example, if you want to disable defaults and @env{WARNINGS}
10157 of @command{autom4te}, but enable the warnings about obsolete
10158 constructs, you would use @option{-W none,obsolete}.
10160 @cindex Back trace
10161 @cindex Macro invocation stack
10162 @command{autom4te} displays a back trace for errors, but not for
10163 warnings; if you want them, just pass @option{-W error}.
10165 @item --melt
10166 @itemx -M
10167 Do not use frozen files.  Any argument @code{@var{file}.m4f} is
10168 replaced by @code{@var{file}.m4}.  This helps tracing the macros which
10169 are executed only when the files are frozen, typically
10170 @code{m4_define}.  For instance, running:
10172 @example
10173 autom4te --melt 1.m4 2.m4f 3.m4 4.m4f input.m4
10174 @end example
10176 @noindent
10177 is roughly equivalent to running:
10179 @example
10180 m4 1.m4 2.m4 3.m4 4.m4 input.m4
10181 @end example
10183 @noindent
10184 while
10186 @example
10187 autom4te 1.m4 2.m4f 3.m4 4.m4f input.m4
10188 @end example
10190 @noindent
10191 is equivalent to:
10193 @example
10194 m4 --reload-state=4.m4f input.m4
10195 @end example
10197 @item --freeze
10198 @itemx -F
10199 Produce a frozen state file.  @command{autom4te} freezing is stricter
10200 than M4's: it must produce no warnings, and no output other than empty
10201 lines (a line with white space is @emph{not} empty) and comments
10202 (starting with @samp{#}).  Unlike @command{m4}'s similarly-named option,
10203 this option takes no argument:
10205 @example
10206 autom4te 1.m4 2.m4 3.m4 --freeze --output=3.m4f
10207 @end example
10209 @noindent
10210 corresponds to
10212 @example
10213 m4 1.m4 2.m4 3.m4 --freeze-state=3.m4f
10214 @end example
10216 @item --mode=@var{octal-mode}
10217 @itemx -m @var{octal-mode}
10218 Set the mode of the non-traces output to @var{octal-mode}; by default
10219 @samp{0666}.
10220 @end table
10222 @sp 1
10224 @cindex @file{autom4te.cache}
10225 As another additional feature over @command{m4}, @command{autom4te}
10226 caches its results.  @acronym{GNU} M4 is able to produce a regular
10227 output and traces at the same time.  Traces are heavily used in the
10228 @acronym{GNU} Build System: @command{autoheader} uses them to build
10229 @file{config.h.in}, @command{autoreconf} to determine what
10230 @acronym{GNU} Build System components are used, @command{automake} to
10231 ``parse'' @file{configure.ac} etc.  To avoid recomputation,
10232 traces are cached while performing regular expansion,
10233 and conversely.  This cache is (actually, the caches are) stored in
10234 the directory @file{autom4te.cache}.  @emph{It can safely be removed}
10235 at any moment (especially if for some reason @command{autom4te}
10236 considers it trashed).
10238 @table @option
10239 @item --cache=@var{directory}
10240 @itemx -C @var{directory}
10241 Specify the name of the directory where the result should be cached.
10242 Passing an empty value disables caching.  Be sure to pass a relative
10243 file name, as for the time being, global caches are not supported.
10245 @item --no-cache
10246 Don't cache the results.
10248 @item --force
10249 @itemx -f
10250 If a cache is used, consider it obsolete (but update it anyway).
10251 @end table
10253 @sp 1
10255 Because traces are so important to the @acronym{GNU} Build System,
10256 @command{autom4te} provides high level tracing features as compared to
10257 M4, and helps exploiting the cache:
10259 @table @option
10260 @item --trace=@var{macro}[:@var{format}]
10261 @itemx -t @var{macro}[:@var{format}]
10262 Trace the invocations of @var{macro} according to the @var{format}.
10263 Multiple @option{--trace} arguments can be used to list several macros.
10264 Multiple @option{--trace} arguments for a single macro are not
10265 cumulative; instead, you should just make @var{format} as long as
10266 needed.
10268 The @var{format} is a regular string, with newlines if desired, and
10269 several special escape codes.  It defaults to @samp{$f:$l:$n:$%}.  It can
10270 use the following special escapes:
10272 @table @samp
10273 @item $$
10274 The character @samp{$}.
10276 @item $f
10277 The file name from which @var{macro} is called.
10279 @item $l
10280 The line number from which @var{macro} is called.
10282 @item $d
10283 The depth of the @var{macro} call.  This is an M4 technical detail that
10284 you probably don't want to know about.
10286 @item $n
10287 The name of the @var{macro}.
10289 @item $@var{num}
10290 The @var{num}th argument of the call to @var{macro}.
10292 @item $@@
10293 @itemx $@var{sep}@@
10294 @itemx $@{@var{separator}@}@@
10295 All the arguments passed to @var{macro}, separated by the character
10296 @var{sep} or the string @var{separator} (@samp{,} by default).  Each
10297 argument is quoted, i.e., enclosed in a pair of square brackets.
10299 @item $*
10300 @itemx $@var{sep}*
10301 @itemx $@{@var{separator}@}*
10302 As above, but the arguments are not quoted.
10304 @item $%
10305 @itemx $@var{sep}%
10306 @itemx $@{@var{separator}@}%
10307 As above, but the arguments are not quoted, all new line characters in
10308 the arguments are smashed, and the default separator is @samp{:}.
10310 The escape @samp{$%} produces single-line trace outputs (unless you put
10311 newlines in the @samp{separator}), while @samp{$@@} and @samp{$*} do
10312 not.
10313 @end table
10315 @xref{autoconf Invocation}, for examples of trace uses.
10317 @item --preselect=@var{macro}
10318 @itemx -p @var{macro}
10319 Cache the traces of @var{macro}, but do not enable traces.  This is
10320 especially important to save CPU cycles in the future.  For instance,
10321 when invoked, @command{autoconf} preselects all the macros that
10322 @command{autoheader}, @command{automake}, @command{autoreconf}, etc.,
10323 trace, so that running @command{m4} is not needed to trace them: the
10324 cache suffices.  This results in a huge speed-up.
10325 @end table
10327 @sp 1
10329 @cindex Autom4te Library
10330 Finally, @command{autom4te} introduces the concept of @dfn{Autom4te
10331 libraries}.  They consists in a powerful yet extremely simple feature:
10332 sets of combined command line arguments:
10334 @table @option
10335 @item --language=@var{language}
10336 @itemx -l @var{language}
10337 Use the @var{language} Autom4te library.  Current languages include:
10339 @table @code
10340 @item M4sugar
10341 create M4sugar output.
10343 @item M4sh
10344 create M4sh executable shell scripts.
10346 @item Autotest
10347 create Autotest executable test suites.
10349 @item Autoconf-without-aclocal-m4
10350 create Autoconf executable configure scripts without
10351 reading @file{aclocal.m4}.
10353 @item Autoconf
10354 create Autoconf executable configure scripts.  This language inherits
10355 all the characteristics of @code{Autoconf-without-aclocal-m4} and
10356 additionally reads @file{aclocal.m4}.
10357 @end table
10359 @item --prepend-include=@var{dir}
10360 @itemx -B @var{dir}
10361 Prepend directory @var{dir} to the search path.  This is used to include
10362 the language-specific files before any third-party macros.
10364 @end table
10366 @cindex @file{autom4te.cfg}
10367 As an example, if Autoconf is installed in its default location,
10368 @file{/usr/local}, the command @samp{autom4te -l m4sugar foo.m4} is
10369 strictly equivalent to the command:
10371 @example
10372 autom4te --prepend-include /usr/local/share/autoconf \
10373   m4sugar/m4sugar.m4f --warnings syntax foo.m4
10374 @end example
10376 @noindent
10377 Recursive expansion applies here: the command @samp{autom4te -l m4sh foo.m4}
10378 is the same as @samp{autom4te --language M4sugar m4sugar/m4sh.m4f
10379 foo.m4}, i.e.:
10381 @example
10382 autom4te --prepend-include /usr/local/share/autoconf \
10383   m4sugar/m4sugar.m4f m4sugar/m4sh.m4f --mode 777 foo.m4
10384 @end example
10386 @noindent
10387 The definition of the languages is stored in @file{autom4te.cfg}.
10389 @node Customizing autom4te
10390 @subsection Customizing @command{autom4te}
10392 One can customize @command{autom4te} via @file{~/.autom4te.cfg} (i.e.,
10393 as found in the user home directory), and @file{./.autom4te.cfg} (i.e.,
10394 as found in the directory from which @command{autom4te} is run).  The
10395 order is first reading @file{autom4te.cfg}, then @file{~/.autom4te.cfg},
10396 then @file{./.autom4te.cfg}, and finally the command line arguments.
10398 In these text files, comments are introduced with @code{#}, and empty
10399 lines are ignored.  Customization is performed on a per-language basis,
10400 wrapped in between a @samp{begin-language: "@var{language}"},
10401 @samp{end-language: "@var{language}"} pair.
10403 Customizing a language stands for appending options (@pxref{autom4te
10404 Invocation}) to the current definition of the language.  Options, and
10405 more generally arguments, are introduced by @samp{args:
10406 @var{arguments}}.  You may use the traditional shell syntax to quote the
10407 @var{arguments}.
10409 As an example, to disable Autoconf caches (@file{autom4te.cache})
10410 globally, include the following lines in @file{~/.autom4te.cfg}:
10412 @verbatim
10413 ## ------------------ ##
10414 ## User Preferences.  ##
10415 ## ------------------ ##
10417 begin-language: "Autoconf-without-aclocal-m4"
10418 args: --no-cache
10419 end-language: "Autoconf-without-aclocal-m4"
10420 @end verbatim
10423 @node Programming in M4sugar
10424 @section Programming in M4sugar
10426 @cindex M4sugar
10427 M4 by itself provides only a small, but sufficient, set of all-purpose
10428 macros.  M4sugar introduces additional generic macros.  Its name was
10429 coined by Lars J. Aas: ``Readability And Greater Understanding Stands 4
10430 M4sugar''.
10432 M4sugar reserves the macro namespace @samp{^_m4_} for internal use, and
10433 the macro namespace @samp{^m4_} for M4sugar macros.  You should not
10434 define your own macros into these namespaces.
10436 @menu
10437 * Redefined M4 Macros::         M4 builtins changed in M4sugar
10438 * Diagnostic Macros::           Diagnostic messages from M4sugar
10439 * Diversion support::           Diversions in M4sugar
10440 * Conditional constructs::      Conditions in M4
10441 * Looping constructs::          Iteration in M4
10442 * Evaluation Macros::           More quotation and evaluation control
10443 * Text processing Macros::      String manipulation in M4
10444 * Number processing Macros::    Arithmetic computation in M4
10445 * Set manipulation Macros::     Set manipulation in M4
10446 * Forbidden Patterns::          Catching unexpanded macros
10447 @end menu
10449 @node Redefined M4 Macros
10450 @subsection Redefined M4 Macros
10452 @msindex{builtin}
10453 @msindex{changecom}
10454 @msindex{changequote}
10455 @msindex{debugfile}
10456 @msindex{debugmode}
10457 @msindex{decr}
10458 @msindex{define}
10459 @msindex{divnum}
10460 @msindex{errprint}
10461 @msindex{esyscmd}
10462 @msindex{eval}
10463 @msindex{format}
10464 @msindex{ifdef}
10465 @msindex{incr}
10466 @msindex{index}
10467 @msindex{indir}
10468 @msindex{len}
10469 @msindex{pushdef}
10470 @msindex{shift}
10471 @msindex{substr}
10472 @msindex{syscmd}
10473 @msindex{sysval}
10474 @msindex{traceoff}
10475 @msindex{traceon}
10476 @msindex{translit}
10477 With a few exceptions, all the M4 native macros are moved in the
10478 @samp{m4_} pseudo-namespace, e.g., M4sugar renames @code{define} as
10479 @code{m4_define} etc.
10481 The list of macros unchanged from M4, except for their name, is:
10482 @itemize @minus
10483 @item m4_builtin
10484 @item m4_changecom
10485 @item m4_changequote
10486 @item m4_debugfile
10487 @item m4_debugmode
10488 @item m4_decr
10489 @item m4_define
10490 @item m4_divnum
10491 @item m4_errprint
10492 @item m4_esyscmd
10493 @item m4_eval
10494 @item m4_format
10495 @item m4_ifdef
10496 @item m4_incr
10497 @item m4_index
10498 @item m4_indir
10499 @item m4_len
10500 @item m4_pushdef
10501 @item m4_shift
10502 @item m4_substr
10503 @item m4_syscmd
10504 @item m4_sysval
10505 @item m4_traceoff
10506 @item m4_traceon
10507 @item m4_translit
10508 @end itemize
10510 Some M4 macros are redefined, and are slightly incompatible with their
10511 native equivalent.
10513 @defmac __file__
10514 @defmacx __line__
10515 @MSindex __file__
10516 @MSindex __line__
10517 All M4 macros starting with @samp{__} retain their original name: for
10518 example, no @code{m4__file__} is defined.
10519 @end defmac
10521 @defmac __oline__
10522 @MSindex __oline__
10523 This is not technically a macro, but a feature of Autom4te.  The
10524 sequence @code{__oline__} can be used similarly to the other m4sugar
10525 location macros, but rather than expanding to the location of the input
10526 file, it is translated to the line number where it appears in the output
10527 file after all other M4 expansions.
10528 @end defmac
10530 @defmac dnl
10531 @MSindex dnl
10532 This macro kept its original name: no @code{m4_dnl} is defined.
10533 @end defmac
10535 @defmac m4_bpatsubst (@var{string}, @var{regexp}, @ovar{replacement})
10536 @msindex{bpatsubst}
10537 This macro corresponds to @code{patsubst}.  The name @code{m4_patsubst}
10538 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10539 released and supports extended regular expression syntax.
10540 @end defmac
10542 @defmac m4_bregexp (@var{string}, @var{regexp}, @ovar{replacement})
10543 @msindex{bregexp}
10544 This macro corresponds to @code{regexp}.  The name @code{m4_regexp}
10545 is kept for future versions of M4sugar, once @acronym{GNU} M4 2.0 is
10546 released and supports extended regular expression syntax.
10547 @end defmac
10549 @defmac m4_copy (@var{source}, @var{dest})
10550 @defmacx m4_rename (@var{source}, @var{dest})
10551 @msindex{copy}
10552 @msindex{rename}
10553 These macros aren't directly builtins, but are closely related to
10554 @code{m4_pushdef} and @code{m4_defn}.  They both ensures that @var{dest}
10555 is undefined, then proceed to copy the entire pushdef stack of
10556 definitions of @var{source}.  @code{m4_copy} preserves the source, while
10557 @code{m4_rename} undefines the original macro name.
10559 Note that attempting to invoke a renamed macro might not work, since the
10560 macro may have a dependence on helper macros accessed via composition of
10561 @samp{$0} but that were not also renamed; likewise, other macros may
10562 have a hard-coded dependence on @var{source} and could break if
10563 @var{source} has been deleted.  On the other hand, it is always safe to
10564 rename a macro to temporarily move it out of the way, then rename it
10565 back later to restore original semantics.
10566 @end defmac
10568 @defmac m4_defn (@var{macro}@dots{})
10569 @msindex{defn}
10570 This macro fails if @var{macro} is not defined, even when using older
10571 versions of M4 that did not warn.  See @code{m4_undefine}.
10572 Unfortunately, in order to support these older versions of M4, there are
10573 some situations involving unbalanced quotes where concatenating multiple
10574 macros together will work in newer M4 but not in m4sugar; use
10575 quadrigraphs to work around this.
10576 @end defmac
10578 @defmac m4_divert (@var{diversion})
10579 @msindex{divert}
10580 M4sugar relies heavily on diversions, so rather than behaving as a
10581 primitive, @code{m4_divert} behaves like:
10582 @example
10583 m4_divert_pop()m4_divert_push([@var{diversion}])
10584 @end example
10585 @noindent
10586 @xref{Diversion support}, for more details about the use of the
10587 diversion stack.
10588 @end defmac
10590 @defmac m4_dumpdef (@var{name}@dots{})
10591 @defmacx m4_dumpdefs (@var{name}@dots{})
10592 @msindex{dumpdef}
10593 @msindex{dumpdefs}
10594 @code{m4_dumpdef} is like the M4 builtin, except that this version
10595 requires at least one argument, output always goes to standard error
10596 rather than the current debug file, no sorting is done on multiple
10597 arguments, and an error is issued if any
10598 @var{name} is undefined.  @code{m4_dumpdefs} is a convenience macro that
10599 calls @code{m4_dumpdef} for all of the
10600 @code{m4_pushdef} stack of definitions, starting with the current, and
10601 silently does nothing if @var{name} is undefined.
10603 Unfortunately, due to a limitation in M4 1.4.x, any macro defined as a
10604 builtin is output as the empty string.  This behavior is rectified by
10605 using M4 1.6 or newer.  However, this behavior difference means that
10606 @code{m4_dumpdef} should only be used while developing m4sugar macros,
10607 and never in the final published form of a macro.
10608 @end defmac
10610 @defmac m4_esyscmd_s (@var{command})
10611 @msindex{esyscmd_s}
10612 Like @code{m4_esyscmd}, this macro expands to the result of running
10613 @var{command} in a shell.  The difference is that any trailing newlines
10614 are removed, so that the output behaves more like shell command
10615 substitution.
10616 @end defmac
10618 @defmac m4_exit (@var{exit-status})
10619 @msindex{exit}
10620 This macro corresponds to @code{m4exit}.
10621 @end defmac
10623 @defmac m4_if (@var{comment})
10624 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @ovar{not-equal})
10625 @defmacx m4_if (@var{string-1}, @var{string-2}, @var{equal}, @dots{})
10626 @msindex{if}
10627 This macro corresponds to @code{ifelse}.  @var{string-1} and
10628 @var{string-2} are compared literally, so usually one of the two
10629 arguments is passed unquoted.  @xref{Conditional constructs}, for more
10630 conditional idioms.
10631 @end defmac
10633 @defmac m4_include (@var{file})
10634 @defmacx m4_sinclude (@var{file})
10635 @msindex{include}
10636 @msindex{sinclude}
10637 Like the M4 builtins, but warn against multiple inclusions of @var{file}.
10638 @end defmac
10640 @defmac m4_mkstemp (@var{template})
10641 @defmacx m4_maketemp (@var{template})
10642 @msindex{maketemp}
10643 @msindex{mkstemp}
10644 Posix requires @code{maketemp} to replace the trailing @samp{X}
10645 characters in @var{template} with the process id, without regards to the
10646 existence of a file by that name, but this a security hole.  When this
10647 was pointed out to the Posix folks, they agreed to invent a new macro
10648 @code{mkstemp} that always creates a uniquely named file, but not all
10649 versions of @acronym{GNU} M4 support the new macro.  In M4sugar,
10650 @code{m4_maketemp} and @code{m4_mkstemp} are synonyms for each other,
10651 and both have the secure semantics regardless of which macro the
10652 underlying M4 provides.
10653 @end defmac
10655 @defmac m4_popdef (@var{macro}@dots{})
10656 @msindex{popdef}
10657 This macro fails if @var{macro} is not defined, even when using older
10658 versions of M4 that did not warn.  See @code{m4_undefine}.
10659 @end defmac
10661 @defmac m4_undefine (@var{macro}@dots{})
10662 @msindex{undefine}
10663 This macro fails if @var{macro} is not defined, even when using older
10664 versions of M4 that did not warn.  Use
10666 @example
10667 m4_ifdef([@var{macro}], [m4_undefine([@var{macro}])])
10668 @end example
10670 @noindent
10671 if you are not sure whether @var{macro} is defined.
10672 @end defmac
10674 @defmac m4_undivert (@var{diversion}@dots{})
10675 @msindex{undivert}
10676 Unlike the M4 builtin, at least one @var{diversion} must be specified.
10677 Also, since the M4sugar diversion stack prefers named
10678 diversions, the use of @code{m4_undivert} to include files is risky.
10679 @xref{Diversion support}, for more details about the use of the
10680 diversion stack.
10681 @end defmac
10683 @defmac m4_wrap (@var{text})
10684 @defmacx m4_wrap_lifo (@var{text})
10685 @msindex{wrap}
10686 @msindex{wrap_lifo}
10687 These macros correspond to @code{m4wrap}.  Posix requires arguments of
10688 multiple wrap calls to be reprocessed at @acronym{EOF} in the same order
10689 as the original calls (first-in, first-out).  @acronym{GNU} M4 versions
10690 through 1.4.10, however, reprocess them in reverse order (last-in,
10691 first-out).  Both orders are useful, therefore, you can rely on
10692 @code{m4_wrap} to provide FIFO semantics and @code{m4_wrap_lifo} for
10693 LIFO semantics, regardless of the underlying @acronym{GNU} M4 version.
10695 Unlike the @acronym{GNU} M4 builtin, these macros only recognize one
10696 argument, and avoid token pasting between consecutive invocations.  On
10697 the other hand, nested calls to @code{m4_wrap} from within wrapped text
10698 work just as in the builtin.
10699 @end defmac
10702 @node Diagnostic Macros
10703 @subsection Diagnostic messages from M4sugar
10704 @cindex Messages, from @command{M4sugar}
10706 When macros statically diagnose abnormal situations, benign or fatal,
10707 they should report them using these macros.  For issuing dynamic issues,
10708 i.e., when @command{configure} is run, see @ref{Printing Messages}.
10710 @defmac m4_assert (@var{expression}, @dvar{exit-status, 1})
10711 @msindex{assert}
10712 Assert that the arithmetic @var{expression} evaluates to non-zero.
10713 Otherwise, issue a fatal error, and exit @command{autom4te} with
10714 @var{exit-status}.
10715 @end defmac
10717 @defmac m4_errprintn (@var{message})
10718 @msindex{errprintn}
10719 Similar to the builtin @code{m4_errprint}, except that a newline is
10720 guaranteed after @var{message}.
10721 @end defmac
10723 @anchor{m4_fatal}
10724 @defmac m4_fatal (@var{message})
10725 @msindex{fatal}
10726 Report a severe error @var{message} prefixed with the current location,
10727 and have @command{autom4te} die.
10728 @end defmac
10730 @defmac m4_location
10731 @msindex{location}
10732 Useful as a prefix in a message line.  Short for:
10733 @example
10734 __file__:__line__
10735 @end example
10736 @end defmac
10738 @anchor{m4_warn}
10739 @defmac m4_warn (@var{category}, @var{message})
10740 @msindex{warn}
10741 Report @var{message} as a warning (or as an error if requested by the
10742 user) if warnings of the @var{category} are turned on.  If the message
10743 is emitted, it is prefixed with the current location, and followed by a
10744 call trace of all macros defined via @code{AC_DEFUN} used to get to the
10745 current expansion.  You are encouraged to use standard categories, which
10746 currently include:
10748 @table @samp
10749 @item all
10750 messages that don't fall into one of the following categories.  Use of an
10751 empty @var{category} is equivalent.
10753 @item cross
10754 related to cross compilation issues.
10756 @item obsolete
10757 use of an obsolete construct.
10759 @item syntax
10760 dubious syntactic constructs, incorrectly ordered macro calls.
10761 @end table
10762 @end defmac
10765 @node Diversion support
10766 @subsection Diversion support
10768 M4sugar makes heavy use of diversions, because it is often the case that
10769 text that must appear early in the output is not discovered until late
10770 in the input.  Additionally, some of the topological sorting algorithms
10771 used in resolving macro dependencies use diversions.  However, most
10772 macros should not need to change diversions directly, but rather rely on
10773 higher-level M4sugar macros to manage diversions transparently.
10775 In the rare case that it is necessary to write a macro that explicitly
10776 outputs text to a different diversion, it is important to be aware of an
10777 M4 limitation regarding diversions: text only goes to a diversion if it
10778 is not part of argument collection.  Therefore, any macro that changes
10779 the current diversion cannot be used as an unquoted argument to another
10780 macro, but must be expanded at the top level.  The macro
10781 @code{m4_expand} will diagnose any attempt to change diversions, since
10782 it is generally useful only as an argument to another macro.  The
10783 following example shows what happens when diversion manipulation is
10784 attempted within macro arguments:
10786 @example
10787 m4_do([normal text]
10788 m4_divert_push([KILL])unwanted[]m4_divert_pop([KILL])
10789 [m4_divert_push([KILL])discarded[]m4_divert_pop([KILL])])dnl
10790 @result{}normal text
10791 @result{}unwanted
10792 @end example
10794 @noindent
10795 Notice that the unquoted text @code{unwanted} is output, even though it
10796 was processed while the current diversion was @code{KILL}, because it
10797 was collected as part of the argument to @code{m4_do}.  However, the
10798 text @code{discarded} disappeared as desired, because the diversion
10799 changes were single-quoted, and were not expanded until the top-level
10800 rescan of the output of @code{m4_do}.
10802 To make diversion management easier, M4sugar uses the concept of named
10803 diversions.  Rather than using diversion numbers directly, it is nicer
10804 to associate a name with each diversion; the diversion number associated
10805 with a particular diversion name is an implementation detail, so you
10806 should only use diversion names.  In general, you should not output text
10807 to a named diversion until after calling the appropriate initialization
10808 routine for your language (@code{m4_init}, @code{AS_INIT},
10809 @code{AT_INIT}, @dots{}), although there are some exceptions documented
10810 below.
10812 M4sugar defines two named diversions.
10813 @table @code
10814 @item KILL
10815 Text written to this diversion is discarded.  This is the default
10816 diversion once M4sugar is initialized.
10817 @item GROW
10818 This diversion is used behind the scenes by topological sorting macros,
10819 such as @code{AC_REQUIRE}.
10820 @end table
10822 M4sh adds several more named diversions.
10823 @table @code
10824 @item BINSH
10825 This diversion is reserved for the @samp{#!} interpreter line.
10826 @item HEADER-REVISION
10827 This diversion holds text from @code{AC_REVISION}.
10828 @item HEADER-COMMENT
10829 This diversion holds comments about the purpose of a file.
10830 @item HEADER-COPYRIGHT
10831 This diversion is managed by @code{AC_COPYRIGHT}.
10832 @item M4SH-SANITIZE
10833 This diversion contains M4sh sanitization code, used to ensure M4sh is
10834 executing in a reasonable shell environment.
10835 @item M4SH-INIT
10836 This diversion contains M4sh initialization code, initializing variables
10837 that are required by other M4sh macros.
10838 @item BODY
10839 This diversion contains the body of the shell code, and is the default
10840 diversion once M4sh is initialized.
10841 @end table
10843 Autotest inherits diversions from M4sh, and changes the default
10844 diversion from @code{BODY} back to @code{KILL}.  It also adds several
10845 more named diversions, with the following subset designed for developer
10846 use.
10847 @table @code
10848 @item PREPARE_TESTS
10849 This diversion contains initialization sequences which are executed
10850 after @file{atconfig} and @file{atlocal}, and after all command line
10851 arguments have been parsed, but prior to running any tests.  It can be
10852 used to set up state that is required across all tests.  This diversion
10853 will work even before @code{AT_INIT}.
10854 @end table
10856 For now, the named diversions of Autoconf and Autoheader, and the
10857 remaining diversions of Autotest, are not documented.  In other words,
10858 intentionally outputting text into an undocumented diversion is subject
10859 to breakage in a future release of Autoconf.
10861 @defmac m4_cleardivert (@var{diversion}@dots{})
10862 @msindex{cleardivert}
10863 Permanently discard any text that has been diverted into
10864 @var{diversion}.
10865 @end defmac
10867 @defmac m4_divert_once (@var{diversion}, @ovar{content})
10868 @msindex{divert_once}
10869 Similar to @code{m4_divert_text}, except that @var{content} is only
10870 output to @var{diversion} if this is the first time that
10871 @code{m4_divert_once} has been called with its particular arguments.
10872 @end defmac
10874 @defmac m4_divert_pop (@ovar{diversion})
10875 @msindex{divert_pop}
10876 If provided, check that the current diversion is indeed @var{diversion}.
10877 Then change to the diversion located earlier on the stack, giving an
10878 error if an attempt is made to pop beyond the initial m4sugar diversion
10879 of @code{KILL}.
10880 @end defmac
10882 @defmac m4_divert_push (@var{diversion})
10883 @msindex{divert_push}
10884 Remember the former diversion on the diversion stack, and output
10885 subsequent text into @var{diversion}.  M4sugar maintains a diversion
10886 stack, and issues an error if there is not a matching pop for every
10887 push.
10888 @end defmac
10890 @defmac m4_divert_text (@var{diversion}, @ovar{content})
10891 @msindex{divert_text}
10892 Output @var{content} and a newline into @var{diversion}, without
10893 affecting the current diversion.  Shorthand for:
10894 @example
10895 m4_divert_push([@var{diversion}])@var{content}
10896 m4_divert_pop([@var{diversion}])dnl
10897 @end example
10898 @end defmac
10900 @defmac m4_init
10901 @msindex{init}
10902 Initialize the M4sugar environment, setting up the default named
10903 diversion to be @code{KILL}.
10904 @end defmac
10906 @node Conditional constructs
10907 @subsection Conditional constructs
10909 The following macros provide additional conditional constructs as
10910 convenience wrappers around @code{m4_if}.
10912 @defmac m4_bmatch (@var{string}, @var{regex-1}, @var{value-1}, @
10913   @ovar{regex-2}, @ovar{value-2}, @dots{}, @ovar{default})
10914 @msindex{bmatch}
10915 The string @var{string} is repeatedly compared against a series of
10916 @var{regex} arguments; if a match is found, the expansion is the
10917 corresponding @var{value}, otherwise, the macro moves on to the next
10918 @var{regex}.  If no @var{regex} match, then the result is the optional
10919 @var{default}, or nothing.
10920 @end defmac
10922 @defmac m4_bpatsubsts (@var{string}, @var{regex-1}, @var{subst-1}, @
10923   @ovar{regex-2}, @ovar{subst-2}, @dots{})
10924 @msindex{bpatsubsts}
10925 The string @var{string} is altered by @var{regex-1} and @var{subst-1},
10926 as if by:
10927 @example
10928 m4_bpatsubst([[@var{string}]], [@var{regex}], [@var{subst}])
10929 @end example
10931 @noindent
10932 The result of the substitution is then passed through the next set of
10933 @var{regex} and @var{subst}, and so forth.  An empty @var{subst} implies
10934 deletion of any matched portions in the current string.  Note that this
10935 macro over-quotes @var{string}; this behavior is intentional, so that
10936 the result of each step of the recursion remains as a quoted string.
10937 However, it means that anchors (@samp{^} and @samp{$} in the @var{regex}
10938 will line up with the extra quotations, and not the characters of the
10939 original string.  The overquoting is removed after the final
10940 substitution.
10941 @end defmac
10943 @defmac m4_case (@var{string}, @var{value-1}, @var{if-value-1}, @
10944   @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10945 @msindex{case}
10946 Test @var{string} against multiple @var{value} possibilities, resulting
10947 in the first @var{if-value} for a match, or in the optional
10948 @var{default}.  This is shorthand for:
10949 @example
10950 m4_if([@var{string}], [@var{value-1}], [@var{if-value-1}],
10951       [@var{string}], [@var{value-2}], [@var{if-value-2}], @dots{},
10952       [@var{default}])
10953 @end example
10954 @end defmac
10956 @defmac m4_cond (@var{test-1}, @var{value-1}, @var{if-value-1}, @
10957   @ovar{test-2}, @ovar{value-2}, @ovar{if-value-2}, @dots{}, @ovar{default})
10958 @msindex{cond}
10959 This macro was introduced in Autoconf 2.62.  Similar to @code{m4_if},
10960 except that each @var{test} is expanded only when it is encountered.
10961 This is useful for short-circuiting expensive tests; while @code{m4_if}
10962 requires all its strings to be expanded up front before doing
10963 comparisons, @code{m4_cond} only expands a @var{test} when all earlier
10964 tests have failed.
10966 For an example, these two sequences give the same result, but in the
10967 case where @samp{$1} does not contain a backslash, the @code{m4_cond}
10968 version only expands @code{m4_index} once, instead of five times, for
10969 faster computation if this is a common case for @samp{$1}.  Notice that
10970 every third argument is unquoted for @code{m4_if}, and quoted for
10971 @code{m4_cond}:
10973 @example
10974 m4_if(m4_index([$1], [\]), [-1], [$2],
10975       m4_eval(m4_index([$1], [\\]) >= 0), [1], [$2],
10976       m4_eval(m4_index([$1], [\$]) >= 0), [1], [$2],
10977       m4_eval(m4_index([$1], [\`]) >= 0), [1], [$3],
10978       m4_eval(m4_index([$1], [\"]) >= 0), [1], [$3],
10979       [$2])
10980 m4_cond([m4_index([$1], [\])], [-1], [$2],
10981         [m4_eval(m4_index([$1], [\\]) >= 0)], [1], [$2],
10982         [m4_eval(m4_index([$1], [\$]) >= 0)], [1], [$2],
10983         [m4_eval(m4_index([$1], [\`]) >= 0)], [1], [$3],
10984         [m4_eval(m4_index([$1], [\"]) >= 0)], [1], [$3],
10985         [$2])
10986 @end example
10987 @end defmac
10989 @defmac m4_default (@var{expr-1}, @var{expr-2})
10990 @defmacx m4_default_quoted (@var{expr-1}, @var{expr-2})
10991 @msindex{default}
10992 @msindex{default_quoted}
10993 If @var{expr-1} is not empty, use it.  Otherwise, select @var{expr-2}.
10994 @code{m4_default} expands the result, while @code{m4_default_quoted}
10995 does not.  Useful for providing a fixed default if the expression that
10996 results in @var{expr-1} would otherwise be empty.
10998 @example
10999 m4_define([active], [ACTIVE])dnl
11000 m4_define([demo1], [m4_default([$1], [$2])])dnl
11001 m4_define([demo2], [m4_default_quoted([$1], [$2])])dnl
11002 demo1([active], [default])
11003 @result{}ACTIVE
11004 demo1([], [active])
11005 @result{}ACTIVE
11006 demo2([active], [default])
11007 @result{}active
11008 demo2([], [active])
11009 @result{}active
11010 @end example
11011 @end defmac
11013 @defmac m4_ifndef (@var{macro}, @var{if-not-defined}, @ovar{if-defined})
11014 @msindex{ifndef}
11015 This is shorthand for:
11016 @example
11017 m4_ifdef([@var{macro}], [@var{if-defined}], [@var{if-not-defined}])
11018 @end example
11019 @end defmac
11021 @defmac m4_ifset (@var{macro}, @ovar{if-true}, @ovar{if-false})
11022 @msindex{ifset}
11023 If @var{macro} is undefined, or is defined as the empty string, expand
11024 to @var{if-false}.  Otherwise, expands to @var{if-true}.  Similar to:
11025 @example
11026 m4_ifval(m4_defn([@var{macro}]), [@var{if-true}], [@var{if-false}])
11027 @end example
11028 @noindent
11029 except that it is not an error if @var{macro} is undefined.
11030 @end defmac
11032 @defmac m4_ifval (@var{cond}, @ovar{if-true}, @ovar{if-false})
11033 @msindex{ifval}
11034 Expands to @var{if-true} if @var{cond} is not empty, otherwise to
11035 @var{if-false}.  This is shorthand for:
11036 @example
11037 m4_if([@var{cond}], [], [@var{if-true}], [@var{if-false}])
11038 @end example
11039 @end defmac
11041 @defmac m4_ifvaln (@var{cond}, @ovar{if-true}, @ovar{if-false})
11042 @msindex{ifvaln}
11043 Similar to @code{m4_ifval}, except guarantee that a newline is present
11044 after any non-empty expansion.  Often followed by @code{dnl}.
11045 @end defmac
11047 @defmac m4_n (@var{text})
11048 @msindex{n}
11049 Expand to @var{text}, and add a newline if @var{text} is not empty.
11050 Often followed by @code{dnl}.
11051 @end defmac
11054 @node Looping constructs
11055 @subsection Looping constructs
11057 The following macros are useful in implementing recursive algorithms in
11058 M4, including loop operations.  An M4 list is formed by quoting a list
11059 of quoted elements; generally the lists are comma-separated, although
11060 @code{m4_foreach_w} is whitespace-separated.  For example, the list
11061 @samp{[[a], [b,c]]} contains two elements: @samp{[a]} and @samp{[b,c]}.
11062 It is common to see lists with unquoted elements when those elements are
11063 not likely to be macro names, as in @samp{[fputc_unlocked,
11064 fgetc_unlocked]}.
11066 Although not generally recommended, it is possible for quoted lists to
11067 have side effects; all side effects are expanded only once, and prior to
11068 visiting any list element.  On the other hand, the fact that unquoted
11069 macros are expanded exactly once means that macros without side effects
11070 can be used to generate lists.  For example,
11072 @example
11073 m4_foreach([i], [[1], [2], [3]m4_errprintn([hi])], [i])
11074 @error{}hi
11075 @result{}123
11076 m4_define([list], [[1], [2], [3]])
11077 @result{}
11078 m4_foreach([i], [list], [i])
11079 @result{}123
11080 @end example
11082 @defmac m4_car (@var{list})
11083 @msindex{car}
11084 Expands to the quoted first element of the comma-separated quoted
11085 @var{list}.  Often used with @code{m4_cdr} to recursively iterate
11086 through a list.  Generally, when using quoted lists of quoted elements,
11087 @code{m4_car} should be called without any extra quotes.
11088 @end defmac
11090 @defmac m4_cdr (@var{list})
11091 @msindex{cdr}
11092 Expands to a quoted list of all but the first element of the
11093 comma-separated quoted @var{list}, or the empty string if @var{list} had
11094 only one element.  Generally, when using quoted lists of quoted
11095 elements, @code{m4_cdr} should be called without any extra quotes.
11097 For example, this is a simple implementation of @code{m4_map}; note how
11098 each iteration checks for the end of recursion, then merely applies the
11099 first argument to the first element of the list, then repeats with the
11100 rest of the list.  (The actual implementation in M4sugar is a bit more
11101 involved, to gain some speed and share code with @code{m4_map_sep}).
11102 @example
11103 m4_define([m4_map], [m4_ifval([$2],
11104   [m4_apply([$1], m4_car($2))[]$0([$1], m4_cdr($2))])])dnl
11105 m4_map([ m4_eval], [[[1]], [[1+1]], [[10],[16]]])
11106 @result{} 1 2 a
11107 @end example
11108 @end defmac
11110 @defmac m4_for (@var{var}, @var{first}, @var{last}, @ovar{step}, @
11111   @var{expression})
11112 @msindex{for}
11113 Loop over the numeric values between @var{first} and @var{last}
11114 including bounds by increments of @var{step}.  For each iteration,
11115 expand @var{expression} with the numeric value assigned to @var{var}.
11116 If @var{step} is omitted, it defaults to @samp{1} or @samp{-1} depending
11117 on the order of the limits.  If given, @var{step} has to match this
11118 order.  The number of iterations is determined independently from
11119 definition of @var{var}; iteration cannot be short-circuited or
11120 lengthened by modifying @var{var} from within @var{expression}.
11121 @end defmac
11123 @defmac m4_foreach (@var{var}, @var{list}, @var{expression})
11124 @msindex{foreach}
11125 Loop over the comma-separated M4 list @var{list}, assigning each value
11126 to @var{var}, and expand @var{expression}.  The following example
11127 outputs two lines:
11129 @example
11130 m4_foreach([myvar], [[foo], [bar, baz]],
11131            [echo myvar
11132 ])dnl
11133 @result{}echo foo
11134 @result{}echo bar, baz
11135 @end example
11137 Note that for some forms of @var{expression}, it may be faster to use
11138 @code{m4_map_args}.
11139 @end defmac
11141 @anchor{m4_foreach_w}
11142 @defmac m4_foreach_w (@var{var}, @var{list}, @var{expression})
11143 @msindex{foreach_w}
11144 Loop over the white-space-separated list @var{list}, assigning each value
11145 to @var{var}, and expand @var{expression}.  If @var{var} is only
11146 referenced once in @var{expression}, it is more efficient to use
11147 @code{m4_map_args_w}.
11149 The deprecated macro @code{AC_FOREACH} is an alias of
11150 @code{m4_foreach_w}.
11151 @end defmac
11153 @defmac m4_map (@var{macro}, @var{list})
11154 @defmacx m4_mapall (@var{macro}, @var{list})
11155 @defmacx m4_map_sep (@var{macro}, @var{separator}, @var{list})
11156 @defmacx m4_mapall_sep (@var{macro}, @var{separator}, @var{list})
11157 @msindex{map}
11158 @msindex{mapall}
11159 @msindex{map_sep}
11160 @msindex{mapall_sep}
11161 Loop over the comma separated quoted list of argument descriptions in
11162 @var{list}, and invoke @var{macro} with the arguments.  An argument
11163 description is in turn a comma-separated quoted list of quoted elements,
11164 suitable for @code{m4_apply}.  The macros @code{m4_map} and
11165 @code{m4_map_sep} ignore empty argument descriptions, while
11166 @code{m4_mapall} and @code{m4_mapall_sep} invoke @var{macro} with no
11167 arguments.  The macros @code{m4_map_sep} and @code{m4_mapall_sep}
11168 additionally expand @var{separator} between invocations of @var{macro}.
11170 Note that @var{separator} is expanded, unlike in @code{m4_join}.  When
11171 separating output with commas, this means that the map result can be
11172 used as a series of arguments, by using a single-quoted comma as
11173 @var{separator}, or as a single string, by using a double-quoted comma.
11175 @example
11176 m4_map([m4_count], [])
11177 @result{}
11178 m4_map([ m4_count], [[],
11179                      [[1]],
11180                      [[1], [2]]])
11181 @result{} 1 2
11182 m4_mapall([ m4_count], [[],
11183                         [[1]],
11184                         [[1], [2]]])
11185 @result{} 0 1 2
11186 m4_map_sep([m4_eval], [,], [[[1+2]],
11187                             [[10], [16]]])
11188 @result{}3,a
11189 m4_map_sep([m4_echo], [,], [[[a]], [[b]]])
11190 @result{}a,b
11191 m4_count(m4_map_sep([m4_echo], [,], [[[a]], [[b]]]))
11192 @result{}2
11193 m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]])
11194 @result{}a,b
11195 m4_count(m4_map_sep([m4_echo], [[,]], [[[a]], [[b]]]))
11196 @result{}1
11197 @end example
11198 @end defmac
11200 @defmac m4_map_args (@var{macro}, @var{arg}@dots{})
11201 @msindex{map_args}
11202 Repeatedly invoke @var{macro} with each successive @var{arg} as its only
11203 argument.  In the following example, three solutions are presented with
11204 the same expansion; the solution using @code{m4_map_args} is the most
11205 efficient.
11206 @example
11207 m4_define([active], [ACTIVE])dnl
11208 m4_foreach([var], [[plain], [active]], [ m4_echo(m4_defn([var]))])
11209 @result{} plain active
11210 m4_map([ m4_echo], [[[plain]], [[active]]])
11211 @result{} plain active
11212 m4_map_args([ m4_echo], [plain], [active])
11213 @result{} plain active
11214 @end example
11216 In cases where it is useful to operate on additional parameters besides
11217 the list elements, the macro @code{m4_curry} can be used in @var{macro}
11218 to supply the argument currying necessary to generate the desired
11219 argument list.  In the following example, @code{list_add_n} is more
11220 efficient than @code{list_add_x}.  On the other hand, using
11221 @code{m4_map_args_sep} can be even more efficient.
11223 @example
11224 m4_define([list], [[1], [2], [3]])dnl
11225 m4_define([add], [m4_eval(([$1]) + ([$2]))])dnl
11226 dnl list_add_n(N, ARG...)
11227 dnl Output a list consisting of each ARG added to N
11228 m4_define([list_add_n],
11229 [m4_shift(m4_map_args([,m4_curry([add], [$1])], m4_shift($@@)))])dnl
11230 list_add_n([1], list)
11231 @result{}2,3,4
11232 list_add_n([2], list)
11233 @result{}3,4,5
11234 m4_define([list_add_x],
11235 [m4_shift(m4_foreach([var], m4_dquote(m4_shift($@@)),
11236   [,add([$1],m4_defn([var]))]))])dnl
11237 list_add_x([1], list)
11238 @result{}2,3,4
11239 @end example
11240 @end defmac
11242 @defmac m4_map_args_pair (@var{macro}, @dvar{macro-end, macro}, @
11243   @var{arg}@dots{})
11244 @msindex{map_args_pair}
11245 For every pair of arguments @var{arg}, invoke @var{macro} with two
11246 arguments.  If there is an odd number of arguments, invoke
11247 @var{macro-end}, which defaults to @var{macro}, with the remaining
11248 argument.
11250 @example
11251 m4_map_args_pair([, m4_reverse], [], [1], [2], [3])
11252 @result{}, 2, 1, 3
11253 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3])
11254 @result{}, 2, 1, [3]
11255 m4_map_args_pair([, m4_reverse], [, m4_dquote], [1], [2], [3], [4])
11256 @result{}, 2, 1, 4, 3
11257 @end example
11258 @end defmac
11260 @defmac m4_map_args_sep (@ovar{pre}, @ovar{post}, @ovar{sep}, @var{arg}@dots{})
11261 @msindex{map_args_sep}
11262 Expand the sequence @code{@var{pre}[@var{arg}]@var{post}} for each
11263 argument, additionally expanding @var{sep} between arguments.  One
11264 common use of this macro is constructing a macro call, where the opening
11265 and closing parentheses are split between @var{pre} and @var{post}; in
11266 particular, @code{m4_map_args([@var{macro}], [@var{arg}])} is equivalent
11267 to @code{m4_map_args_sep([@var{macro}(], [)], [], [@var{arg}])}.  This
11268 macro provides the most efficient means for iterating over an arbitrary
11269 list of arguments, particularly when repeatedly constructing a macro
11270 call with more arguments than @var{arg}.
11271 @end defmac
11273 @defmac m4_map_args_w (@var{string}, @ovar{pre}, @ovar{post}, @ovar{sep})
11274 @msindex{map_args_w}
11275 Expand the sequence @code{@var{pre}[word]@var{post}} for each word in
11276 the whitespace-separated @var{string}, additionally expanding @var{sep}
11277 between words.  This macro provides the most efficient means for
11278 iterating over a whitespace-separated string.  In particular,
11279 @code{m4_map_args_w([@var{string}], [@var{action}(], [)])} is more
11280 efficient than @code{m4_foreach_w([var], [@var{string}],
11281 [@var{action}(m4_defn([var]))])}.
11282 @end defmac
11284 @defmac m4_shiftn (@var{count}, @dots{})
11285 @defmacx m4_shift2 (@dots{})
11286 @defmacx m4_shift3 (@dots{})
11287 @msindex{shift2}
11288 @msindex{shift3}
11289 @msindex{shiftn}
11290 @code{m4_shiftn} performs @var{count} iterations of @code{m4_shift},
11291 along with validation that enough arguments were passed in to match the
11292 shift count, and that the count is positive.  @code{m4_shift2} and
11293 @code{m4_shift3} are specializations
11294 of @code{m4_shiftn}, introduced in Autoconf 2.62, and are more efficient
11295 for two and three shifts, respectively.
11296 @end defmac
11298 @defmac m4_stack_foreach (@var{macro}, @var{action})
11299 @defmacx m4_stack_foreach_lifo (@var{macro}, @var{action})
11300 @msindex{stack_foreach}
11301 @msindex{stack_foreach_lifo}
11302 For each of the @code{m4_pushdef} definitions of @var{macro}, expand
11303 @var{action} with the single argument of a definition of @var{macro}.
11304 @code{m4_stack_foreach} starts with the oldest definition, while
11305 @code{m4_stack_foreach_lifo} starts with the current definition.
11306 @var{action} should not push or pop definitions of @var{macro}, nor is
11307 there any guarantee that the current definition of @var{macro} matches
11308 the argument that was passed to @var{action}.  The macro @code{m4_curry}
11309 can be used if @var{action} needs more than one argument, although in
11310 that case it is more efficient to use @var{m4_stack_foreach_sep}.
11312 Due to technical limitations, there are a few low-level m4sugar
11313 functions, such as @code{m4_pushdef}, that cannot be used as the
11314 @var{macro} argument.
11316 @example
11317 m4_pushdef([a], [1])m4_pushdef([a], [2])dnl
11318 m4_stack_foreach([a], [ m4_incr])
11319 @result{} 2 3
11320 m4_stack_foreach_lifo([a], [ m4_curry([m4_substr], [abcd])])
11321 @result{} cd bcd
11322 @end example
11323 @end defmac
11325 @defmac m4_stack_foreach_sep (@var{macro}, @ovar{pre}, @ovar{post}, @ovar{sep})
11326 @defmacx m4_stack_foreach_sep_lifo (@var{macro}, @ovar{pre}, @ovar{post}, @
11327   @ovar{sep})
11328 @msindex{stack_foreach_sep}
11329 @msindex{stack_foreach_sep_lifo}
11330 Expand the sequence @code{@var{pre}[definition]@var{post}} for each
11331 @code{m4_pushdef} definition of @var{macro}, additionally expanding
11332 @var{sep} between definitions.  @code{m4_stack_foreach_sep} visits the
11333 oldest definition first, while @code{m4_stack_foreach_sep_lifo} visits
11334 the current definition first.  This macro provides the most efficient
11335 means for iterating over a pushdef stack.  In particular,
11336 @code{m4_stack_foreach([@var{macro}], [@var{action}])} is short for
11337 @code{m4_stack_foreach_sep([@var{macro}], [@var{action}(], [)])}.
11338 @end defmac
11340 @node Evaluation Macros
11341 @subsection Evaluation Macros
11343 The following macros give some control over the order of the evaluation
11344 by adding or removing levels of quotes.
11346 @defmac m4_apply (@var{macro}, @var{list})
11347 @msindex{apply}
11348 Apply the elements of the quoted, comma-separated @var{list} as the
11349 arguments to @var{macro}.  If @var{list} is empty, invoke @var{macro}
11350 without arguments.  Note the difference between @code{m4_indir}, which
11351 expects its first argument to be a macro name but can use names that are
11352 otherwise invalid, and @code{m4_apply}, where @var{macro} can contain
11353 other text, but must end in a valid macro name.
11354 @example
11355 m4_apply([m4_count], [])
11356 @result{}0
11357 m4_apply([m4_count], [[]])
11358 @result{}1
11359 m4_apply([m4_count], [[1], [2]])
11360 @result{}2
11361 m4_apply([m4_join], [[|], [1], [2]])
11362 @result{}1|2
11363 @end example
11364 @end defmac
11366 @defmac m4_count (@var{arg}, @dots{})
11367 @msindex{count}
11368 This macro returns the decimal count of the number of arguments it was
11369 passed.
11370 @end defmac
11372 @defmac m4_curry (@var{macro}, @var{arg}@dots{})
11373 @msindex{curry}
11374 This macro performs argument currying.  The expansion of this macro is
11375 another macro name that expects exactly one argument; that argument is
11376 then appended to the @var{arg} list, and then @var{macro} is expanded
11377 with the resulting argument list.
11379 @example
11380 m4_curry([m4_curry], [m4_reverse], [1])([2])([3])
11381 @result{}3, 2, 1
11382 @end example
11384 Unfortunately, due to a limitation in M4 1.4.x, it is not possible to
11385 pass the definition of a builtin macro as the argument to the output of
11386 @code{m4_curry}; the empty string is used instead of the builtin token.
11387 This behavior is rectified by using M4 1.6 or newer.
11388 @end defmac
11390 @defmac m4_do (@var{arg}, @dots{})
11391 @msindex{do}
11392 This macro loops over its arguments and expands each @var{arg} in
11393 sequence.  Its main use is for readability; it allows the use of
11394 indentation and fewer @code{dnl} to result in the same expansion.  This
11395 macro guarantees that no expansion will be concatenated with subsequent
11396 text; to achieve full concatenation, use @code{m4_unquote(m4_join([],
11397 @var{arg@dots{}}))}.
11399 @example
11400 m4_define([ab],[1])m4_define([bc],[2])m4_define([abc],[3])dnl
11401 m4_do([a],[b])c
11402 @result{}abc
11403 m4_unquote(m4_join([],[a],[b]))c
11404 @result{}3
11405 m4_define([a],[A])m4_define([b],[B])m4_define([c],[C])dnl
11406 m4_define([AB],[4])m4_define([BC],[5])m4_define([ABC],[6])dnl
11407 m4_do([a],[b])c
11408 @result{}ABC
11409 m4_unquote(m4_join([],[a],[b]))c
11410 @result{}3
11411 @end example
11412 @end defmac
11414 @defmac m4_dquote (@var{arg}, @dots{})
11415 @msindex{dquote}
11416 Return the arguments as a quoted list of quoted arguments.
11417 Conveniently, if there is just one @var{arg}, this effectively adds a
11418 level of quoting.
11419 @end defmac
11421 @defmac m4_dquote_elt (@var{arg}, @dots{})
11422 @msindex{dquote_elt}
11423 Return the arguments as a series of double-quoted arguments.  Whereas
11424 @code{m4_dquote} returns a single argument, @code{m4_dquote_elt} returns
11425 as many arguments as it was passed.
11426 @end defmac
11428 @defmac m4_echo (@var{arg}, @dots{})
11429 @msindex{echo}
11430 Return the arguments, with the same level of quoting.  Other than
11431 discarding whitespace after unquoted commas, this macro is a no-op.
11432 @end defmac
11434 @defmac m4_expand (@var{arg})
11435 @msindex{expand}
11436 Return the expansion of @var{arg} as a quoted string.  Whereas
11437 @code{m4_quote} is designed to collect expanded text into a single
11438 argument, @code{m4_expand} is designed to perform one level of expansion
11439 on quoted text.  One distinction is in the treatment of whitespace
11440 following a comma in the original @var{arg}.  Any time multiple
11441 arguments are collected into one with @code{m4_quote}, the M4 argument
11442 collection rules discard the whitespace.  However, with @code{m4_expand},
11443 whitespace is preserved, even after the expansion of macros contained in
11444 @var{arg}.  Additionally, @code{m4_expand} is able to expand text that
11445 would involve an unterminated comment, whereas expanding that same text
11446 as the argument to @code{m4_quote} runs into difficulty in finding the
11447 end of the argument.  Since manipulating diversions during argument
11448 collection is inherently unsafe, @code{m4_expand} issues an error if
11449 @var{arg} attempts to change the current diversion (@pxref{Diversion
11450 support}).
11452 @example
11453 m4_define([active], [ACT, IVE])dnl
11454 m4_define([active2], [[ACT, IVE]])dnl
11455 m4_quote(active, active)
11456 @result{}ACT,IVE,ACT,IVE
11457 m4_expand([active, active])
11458 @result{}ACT, IVE, ACT, IVE
11459 m4_quote(active2, active2)
11460 @result{}ACT, IVE,ACT, IVE
11461 m4_expand([active2, active2])
11462 @result{}ACT, IVE, ACT, IVE
11463 m4_expand([# m4_echo])
11464 @result{}# m4_echo
11465 m4_quote(# m4_echo)
11467 @result{}# m4_echo)
11468 @result{}
11469 @end example
11471 Note that @code{m4_expand} cannot handle an @var{arg} that expands to
11472 literal unbalanced quotes, but that quadrigraphs can be used when
11473 unbalanced output is necessary.  Likewise, unbalanced parentheses should
11474 be supplied with double quoting or a quadrigraph.
11476 @example
11477 m4_define([pattern], [[!@@<:@@]])dnl
11478 m4_define([bar], [BAR])dnl
11479 m4_expand([case $foo in
11480   m4_defn([pattern])@@:@}@@ bar ;;
11481   *[)] blah ;;
11482 esac])
11483 @result{}case $foo in
11484 @result{}  [![]) BAR ;;
11485 @result{}  *) blah ;;
11486 @result{}esac
11487 @end example
11488 @end defmac
11490 @defmac m4_ignore (@dots{})
11491 @msindex{ignore}
11492 This macro was introduced in Autoconf 2.62.  Expands to nothing,
11493 ignoring all of its arguments.  By itself, this isn't very useful.
11494 However, it can be used to conditionally ignore an arbitrary number of
11495 arguments, by deciding which macro name to apply to a list of arguments.
11496 @example
11497 dnl foo outputs a message only if [debug] is defined.
11498 m4_define([foo],
11499 [m4_ifdef([debug],[AC_MSG_NOTICE],[m4_ignore])([debug message])])
11500 @end example
11502 Note that for earlier versions of Autoconf, the macro @code{__gnu__} can
11503 serve the same purpose, although it is less readable.
11504 @end defmac
11506 @defmac m4_make_list (@var{arg}, @dots{})
11507 @msindex{make_list}
11508 This macro exists to aid debugging of M4sugar algorithms.  Its net
11509 effect is similar to @code{m4_dquote}---it produces a quoted list of
11510 quoted arguments, for each @var{arg}.  The difference is that this
11511 version uses a comma-newline separator instead of just comma, to improve
11512 readability of the list; with the result that it is less efficient than
11513 @code{m4_dquote}.
11514 @example
11515 m4_define([zero],[0])m4_define([one],[1])m4_define([two],[2])dnl
11516 m4_dquote(zero, [one], [[two]])
11517 @result{}[0],[one],[[two]]
11518 m4_make_list(zero, [one], [[two]])
11519 @result{}[0],
11520 @result{}[one],
11521 @result{}[[two]]
11522 m4_foreach([number], m4_dquote(zero, [one], [[two]]), [ number])
11523 @result{} 0 1 two
11524 m4_foreach([number], m4_make_list(zero, [one], [[two]]), [ number])
11525 @result{} 0 1 two
11526 @end example
11527 @end defmac
11529 @c m4_noquote is too dangerous to document - it invokes macros that
11530 @c probably rely on @samp{[]} nested quoting for proper operation.  The
11531 @c user should generally prefer m4_unquote instead.
11533 @defmac m4_quote (@var{arg}, @dots{})
11534 @msindex{quote}
11535 Return the arguments as a single entity, i.e., wrap them into a pair of
11536 quotes.  This effectively collapses multiple arguments into one,
11537 although it loses whitespace after unquoted commas in the process.
11538 @end defmac
11540 @defmac m4_reverse (@var{arg}, @dots{})
11541 @msindex{reverse}
11542 Outputs each argument with the same level of quoting, but in reverse
11543 order, and with space following each comma for readability.
11545 @example
11546 m4_define([active], [ACT,IVE])
11547 @result{}
11548 m4_reverse(active, [active])
11549 @result{}active, IVE, ACT
11550 @end example
11551 @end defmac
11553 @defmac m4_unquote (@var{arg}, @dots{})
11554 @msindex{unquote}
11555 This macro was introduced in Autoconf 2.62.  Expand each argument,
11556 separated by commas.  For a single @var{arg}, this effectively removes a
11557 layer of quoting, and @code{m4_unquote([@var{arg}])} is more efficient
11558 than the equivalent @code{m4_do([@var{arg}])}.  For multiple arguments,
11559 this results in an unquoted list of expansions.  This is commonly used
11560 with @code{m4_split}, in order to convert a single quoted list into a
11561 series of quoted elements.
11562 @end defmac
11564 The following example aims at emphasizing the difference between several
11565 scenarios: not using these macros, using @code{m4_defn}, using
11566 @code{m4_quote}, using @code{m4_dquote}, and using @code{m4_expand}.
11568 @example
11569 $ @kbd{cat example.m4}
11570 dnl Overquote, so that quotes are visible.
11571 m4_define([show], [$[]1 = [$1], $[]@@ = [$@@]])
11572 m4_define([a], [A])
11573 m4_define([mkargs], [1, 2[,] 3])
11574 m4_define([arg1], [[$1]])
11575 m4_divert([0])dnl
11576 show(a, b)
11577 show([a, b])
11578 show(m4_quote(a, b))
11579 show(m4_dquote(a, b))
11580 show(m4_expand([a, b]))
11582 arg1(mkargs)
11583 arg1([mkargs])
11584 arg1(m4_defn([mkargs]))
11585 arg1(m4_quote(mkargs))
11586 arg1(m4_dquote(mkargs))
11587 arg1(m4_expand([mkargs]))
11588 $ @kbd{autom4te -l m4sugar example.m4}
11589 $1 = A, $@@ = [A],[b]
11590 $1 = a, b, $@@ = [a, b]
11591 $1 = A,b, $@@ = [A,b]
11592 $1 = [A],[b], $@@ = [[A],[b]]
11593 $1 = A, b, $@@ = [A, b]
11596 mkargs
11597 1, 2[,] 3
11598 1,2, 3
11599 [1],[2, 3]
11600 1, 2, 3
11601 @end example
11604 @node Text processing Macros
11605 @subsection String manipulation in M4
11607 The following macros may be used to manipulate strings in M4.  Many of
11608 the macros in this section intentionally result in quoted strings as
11609 output, rather than subjecting the arguments to further expansions.  As
11610 a result, if you are manipulating text that contains active M4
11611 characters, the arguments are passed with single quoting rather than
11612 double.
11614 @defmac m4_append (@var{macro-name}, @var{string}, @ovar{separator})
11615 @defmacx m4_append_uniq (@var{macro-name}, @var{string}, @ovar{separator} @
11616   @ovar{if-uniq}, @ovar{if-duplicate})
11617 @msindex{append}
11618 @msindex{append_uniq}
11619 Redefine @var{macro-name} to its former contents with @var{separator}
11620 and @var{string} added at the end.  If @var{macro-name} was undefined
11621 before (but not if it was defined but empty), then no @var{separator} is
11622 added.  As of Autoconf 2.62, neither @var{string} nor @var{separator}
11623 are expanded during this macro; instead, they are expanded when
11624 @var{macro-name} is invoked.
11626 @code{m4_append} can be used to grow strings, and @code{m4_append_uniq}
11627 to grow strings without duplicating substrings.  Additionally,
11628 @code{m4_append_uniq} takes two optional parameters as of Autoconf 2.62;
11629 @var{if-uniq} is expanded if @var{string} was appended, and
11630 @var{if-duplicate} is expanded if @var{string} was already present.
11631 Also, @code{m4_append_uniq} warns if @var{separator} is not empty, but
11632 occurs within @var{string}, since that can lead to duplicates.
11634 Note that @code{m4_append} can scale linearly in the length of the final
11635 string, depending on the quality of the underlying M4 implementation,
11636 while @code{m4_append_uniq} has an inherent quadratic scaling factor.
11637 If an algorithm can tolerate duplicates in the final string, use the
11638 former for speed.  If duplicates must be avoided, consider using
11639 @code{m4_set_add} instead (@pxref{Set manipulation Macros}).
11641 @example
11642 m4_define([active], [ACTIVE])dnl
11643 m4_append([sentence], [This is an])dnl
11644 m4_append([sentence], [ active ])dnl
11645 m4_append([sentence], [symbol.])dnl
11646 sentence
11647 @result{}This is an ACTIVE symbol.
11648 m4_undefine([active])dnl
11649 @result{}This is an active symbol.
11650 m4_append_uniq([list], [one], [, ], [new], [existing])
11651 @result{}new
11652 m4_append_uniq([list], [one], [, ], [new], [existing])
11653 @result{}existing
11654 m4_append_uniq([list], [two], [, ], [new], [existing])
11655 @result{}new
11656 m4_append_uniq([list], [three], [, ], [new], [existing])
11657 @result{}new
11658 m4_append_uniq([list], [two], [, ], [new], [existing])
11659 @result{}existing
11660 list
11661 @result{}one, two, three
11662 m4_dquote(list)
11663 @result{}[one],[two],[three]
11664 m4_append([list2], [one], [[, ]])dnl
11665 m4_append_uniq([list2], [two], [[, ]])dnl
11666 m4_append([list2], [three], [[, ]])dnl
11667 list2
11668 @result{}one, two, three
11669 m4_dquote(list2)
11670 @result{}[one, two, three]
11671 @end example
11672 @end defmac
11674 @defmac m4_append_uniq_w (@var{macro-name}, @var{strings})
11675 @msindex{append_uniq_w}
11676 This macro was introduced in Autoconf 2.62.  It is similar to
11677 @code{m4_append_uniq}, but treats @var{strings} as a whitespace
11678 separated list of words to append, and only appends unique words.
11679 @var{macro-name} is updated with a single space between new words.
11680 @example
11681 m4_append_uniq_w([numbers], [1 1 2])dnl
11682 m4_append_uniq_w([numbers], [ 2 3 ])dnl
11683 numbers
11684 @result{}1 2 3
11685 @end example
11686 @end defmac
11688 @defmac m4_chomp (@var{string})
11689 @defmacx m4_chomp_all (@var{string})
11690 @msindex{chomp}
11691 @msindex{chomp_all}
11692 Output @var{string} in quotes, but without a trailing newline.  The
11693 macro @code{m4_chomp} is slightly faster, and removes at most one
11694 newline; the macro @code{m4_chomp_all} removes all consecutive trailing
11695 newlines.  Unlike @code{m4_flatten}, embedded newlines are left intact,
11696 and backslash does not influence the result.
11697 @end defmac
11699 @defmac m4_combine (@ovar{separator}, @var{prefix-list}, @ovar{infix}, @
11700   @var{suffix-1}, @ovar{suffix-2}, @dots{})
11701 @msindex{combine}
11702 This macro produces a quoted string containing the pairwise combination
11703 of every element of the quoted, comma-separated @var{prefix-list}, and
11704 every element from the @var{suffix} arguments.  Each pairwise
11705 combination is joined with @var{infix} in the middle, and successive
11706 pairs are joined by @var{separator}.  No expansion occurs on any of the
11707 arguments.  No output occurs if either the @var{prefix} or @var{suffix}
11708 list is empty, but the lists can contain empty elements.
11709 @example
11710 m4_define([a], [oops])dnl
11711 m4_combine([, ], [[a], [b], [c]], [-], [1], [2], [3])
11712 @result{}a-1, a-2, a-3, b-1, b-2, b-3, c-1, c-2, c-3
11713 m4_combine([, ], [[a], [b]], [-])
11714 @result{}
11715 m4_combine([, ], [[a], [b]], [-], [])
11716 @result{}a-, b-
11717 m4_combine([, ], [], [-], [1], [2])
11718 @result{}
11719 m4_combine([, ], [[]], [-], [1], [2])
11720 @result{}-1, -2
11721 @end example
11722 @end defmac
11724 @defmac m4_flatten (@var{string})
11725 @msindex{flatten}
11726 Flatten @var{string} into a single line.  Delete all backslash-newline
11727 pairs, and replace all remaining newlines with a space.  The result is
11728 still a quoted string.
11729 @end defmac
11731 @defmac m4_join (@ovar{separator}, @var{args}@dots{})
11732 @defmacx m4_joinall (@ovar{separator}, @var{args}@dots{})
11733 @msindex{join}
11734 @msindex{joinall}
11735 Concatenate each @var{arg}, separated by @var{separator}.
11736 @code{joinall} uses every argument, while @code{join} omits empty
11737 arguments so that there are no back-to-back separators in the output.
11738 The result is a quoted string.
11739 @example
11740 m4_define([active], [ACTIVE])dnl
11741 m4_join([|], [one], [], [active], [two])
11742 @result{}one|active|two
11743 m4_joinall([|], [one], [], [active], [two])
11744 @result{}one||active|two
11745 @end example
11747 Note that if all you intend to do is join @var{args} with commas between
11748 them, to form a quoted list suitable for @code{m4_foreach}, it is more
11749 efficient to use @code{m4_dquote}.
11750 @end defmac
11752 @defmac m4_newline (@ovar{text})
11753 @msindex{newline}
11754 This macro was introduced in Autoconf 2.62, and expands to a newline,
11755 followed by any @var{text}.
11756 It is primarily useful for maintaining macro formatting, and ensuring
11757 that M4 does not discard leading whitespace during argument collection.
11758 @end defmac
11760 @defmac m4_normalize (@var{string})
11761 @msindex{normalize}
11762 Remove leading and trailing spaces and tabs, sequences of
11763 backslash-then-newline, and replace multiple spaces, tabs, and newlines
11764 with a single space.  This is a combination of @code{m4_flatten} and
11765 @code{m4_strip}.
11766 @end defmac
11768 @defmac m4_re_escape (@var{string})
11769 @msindex{re_escape}
11770 Backslash-escape all characters in @var{string} that are active in
11771 regexps.
11772 @end defmac
11774 @defmac m4_split (@var{string}, @dvar{regexp, [\t ]+})
11775 @msindex{split}
11776 Split @var{string} into an M4 list of elements quoted by @samp{[} and
11777 @samp{]}, while keeping white space at the beginning and at the end.
11778 If @var{regexp} is given, use it instead of @samp{[\t ]+} for splitting.
11779 If @var{string} is empty, the result is an empty list.
11780 @end defmac
11782 @defmac m4_strip (@var{string})
11783 @msindex{strip}
11784 Strip whitespace from @var{string}.  Sequences of spaces and tabs are
11785 reduced to a single space, then leading and trailing spaces are removed.
11786 The result is still a quoted string.  Note that this does not interfere
11787 with newlines; if you want newlines stripped as well, consider
11788 @code{m4_flatten}, or do it all at once with @code{m4_normalize}.
11789 @end defmac
11791 @defmac m4_text_box (@var{message}, @dvar{frame, -})
11792 @msindex{text_box}
11793 Add a text box around @var{message}, using @var{frame} as the border
11794 character above and below the message.  The frame correctly accounts for
11795 the subsequent expansion of @var{message}.  For example:
11796 @example
11797 m4_define([macro], [abc])dnl
11798 m4_text_box([macro])
11799 @result{}## --- ##
11800 @result{}## abc ##
11801 @result{}## --- ##
11802 @end example
11804 The @var{message} must contain balanced quotes and parentheses, although
11805 quadrigraphs can be used to work around this.
11806 @end defmac
11808 @defmac m4_text_wrap (@var{string}, @ovar{prefix}, @
11809   @dvar{prefix1, @var{prefix}}, @dvar{width, 79})
11810 @msindex{text_wrap}
11811 Break @var{string} into a series of whitespace-separated words, then
11812 output those words separated by spaces, and wrapping lines any time the
11813 output would exceed @var{width} columns.  If given, @var{prefix1} begins
11814 the first line, and @var{prefix} begins all wrapped lines.  If
11815 @var{prefix1} is longer than @var{prefix}, then the first line consists
11816 of just @var{prefix1}.  If @var{prefix} is longer than @var{prefix1},
11817 padding is inserted so that the first word of @var{string} begins at the
11818 same indentation as all wrapped lines.  Note that using literal tab
11819 characters in any of the arguments will interfere with the calculation
11820 of width.  No expansions occur on @var{prefix}, @var{prefix1}, or the
11821 words of @var{string}, although quadrigraphs are recognized.
11823 For some examples:
11824 @example
11825 m4_text_wrap([Short string */], [   ], [/* ], [20])
11826 @result{}/* Short string */
11827 m4_text_wrap([Much longer string */], [   ], [/* ], [20])
11828 @result{}/* Much longer
11829 @result{}   string */
11830 m4_text_wrap([Short doc.], [          ], [  --short ], [30])
11831 @result{}  --short Short doc.
11832 m4_text_wrap([Short doc.], [          ], [  --too-wide ], [30])
11833 @result{}  --too-wide
11834 @result{}          Short doc.
11835 m4_text_wrap([Super long documentation.], [     ],
11836              [  --too-wide ], 30)
11837 @result{}  --too-wide
11838 @result{}     Super long
11839 @result{}     documentation.
11840 @end example
11841 @end defmac
11843 @defmac m4_tolower (@var{string})
11844 @defmacx m4_toupper (@var{string})
11845 @msindex{tolower}
11846 @msindex{toupper}
11847 Return @var{string} with letters converted to upper or lower case,
11848 respectively.
11849 @end defmac
11851 @node Number processing Macros
11852 @subsection Arithmetic computation in M4
11854 The following macros facilitate integer arithmetic operations.
11855 Where a parameter is documented as taking an arithmetic expression, you
11856 can use anything that can be parsed by @code{m4_eval}.
11858 @defmac m4_cmp (@var{expr-1}, @var{expr-2})
11859 @msindex{cmp}
11860 Compare the arithmetic expressions @var{expr-1} and @var{expr-2}, and
11861 expand to @samp{-1} if @var{expr-1} is smaller, @samp{0} if they are
11862 equal, and @samp{1} if @var{expr-1} is larger.
11863 @end defmac
11865 @defmac m4_list_cmp (@var{list-1}, @var{list-2})
11866 @msindex{list_cmp}
11867 Compare the two M4 lists consisting of comma-separated arithmetic
11868 expressions, left to right.  Expand to @samp{-1} for the first element
11869 pairing where the value from @var{list-1} is smaller, @samp{1} where the
11870 value from @var{list-2} is smaller, or @samp{0} if both lists have the
11871 same values.  If one list is shorter than the other, the remaining
11872 elements of the longer list are compared against zero.
11873 @example
11874 m4_list_cmp([1, 0],       [1])
11875 @result{}0
11876 m4_list_cmp([1, [1 * 0]], [1, 0])
11877 @result{}0
11878 m4_list_cmp([1, 2],       [1, 0])
11879 @result{}1
11880 m4_list_cmp([1, [1+1], 3],[1, 2])
11881 @result{}1
11882 m4_list_cmp([1, 2, -3],   [1, 2])
11883 @result{}-1
11884 m4_list_cmp([1, 0],       [1, 2])
11885 @result{}-1
11886 m4_list_cmp([1],          [1, 2])
11887 @result{}-1
11888 @end example
11889 @end defmac
11891 @defmac m4_max (@var{arg}, @dots{})
11892 @msindex{max}
11893 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11894 of the maximum arithmetic expression among all the arguments.
11895 @end defmac
11897 @defmac m4_min (@var{arg}, @dots{})
11898 @msindex{min}
11899 This macro was introduced in Autoconf 2.62.  Expand to the decimal value
11900 of the minimum arithmetic expression among all the arguments.
11901 @end defmac
11903 @defmac m4_sign (@var{expr})
11904 @msindex{sign}
11905 Expand to @samp{-1} if the arithmetic expression @var{expr} is negative,
11906 @samp{1} if it is positive, and @samp{0} if it is zero.
11907 @end defmac
11909 @anchor{m4_version_compare}
11910 @defmac m4_version_compare (@var{version-1}, @var{version-2})
11911 @msindex{version_compare}
11912 This macro was introduced in Autoconf 2.53, but had a number of
11913 usability limitations that were not lifted until Autoconf 2.62.  Compare
11914 the version strings @var{version-1} and @var{version-2}, and expand to
11915 @samp{-1} if @var{version-1} is smaller, @samp{0} if they are the same,
11916 or @samp{1} @var{version-2} is smaller.  Version strings must be a list
11917 of elements separated by @samp{.}, @samp{,} or @samp{-}, where each
11918 element is a number along with optional case-insensitive letters
11919 designating beta releases.  The comparison stops at the leftmost element
11920 that contains a difference, although a 0 element compares equal to a
11921 missing element.
11923 It is permissible to include commit identifiers in @var{version}, such
11924 as an abbreviated SHA1 of the commit, provided there is still a
11925 monotonically increasing prefix to allow for accurate version-based
11926 comparisons.  For example, this paragraph was written when the
11927 development snapshot of autoconf claimed to be at version
11928 @samp{2.61a-248-dc51}, or 248 commits after the 2.61a release, with an
11929 abbreviated commit identification of @samp{dc51}.
11931 @example
11932 m4_version_compare([1.1], [2.0])
11933 @result{}-1
11934 m4_version_compare([2.0b], [2.0a])
11935 @result{}1
11936 m4_version_compare([1.1.1], [1.1.1a])
11937 @result{}-1
11938 m4_version_compare([1.2], [1.1.1a])
11939 @result{}1
11940 m4_version_compare([1.0], [1])
11941 @result{}0
11942 m4_version_compare([1.1pre], [1.1PRE])
11943 @result{}0
11944 m4_version_compare([1.1a], [1,10])
11945 @result{}-1
11946 m4_version_compare([2.61a], [2.61a-248-dc51])
11947 @result{}-1
11948 m4_version_compare([2.61b], [2.61a-248-dc51])
11949 @result{}1
11950 @end example
11951 @end defmac
11953 @defmac m4_version_prereq (@var{version}, @ovar{if-new-enough}, @
11954   @dvar{if-old, m4_fatal})
11955 @msindex{version_prereq}
11956 Compares @var{version} against the version of Autoconf currently
11957 running.  If the running version is at @var{version} or newer, expand
11958 @var{if-new-enough}, but if @var{version} is larger than the version
11959 currently executing, expand @var{if-old}, which defaults to printing an
11960 error message and exiting m4sugar with status 63.  When given only one
11961 argument, this behaves like @code{AC_PREREQ} (@pxref{Versioning}).
11962 Remember that the autoconf philosophy favors feature checks over version
11963 checks.
11964 @end defmac
11966 @node Set manipulation Macros
11967 @subsection Set manipulation in M4
11968 @cindex Set manipulation
11969 @cindex Data structure, set
11970 @cindex Unordered set manipulation
11972 Sometimes, it is necessary to track a set of data, where the order does
11973 not matter and where there are no duplicates in the set.  The following
11974 macros facilitate set manipulations.  Each set is an opaque object,
11975 which can only be accessed via these basic operations.  The underlying
11976 implementation guarantees linear scaling for set creation, which is more
11977 efficient than using the quadratic @code{m4_append_uniq}.  Both set
11978 names and values can be arbitrary strings, except for unbalanced quotes.
11979 This implementation ties up memory for removed elements until the next
11980 operation that must traverse all the elements of a set; and although
11981 that may slow down some operations until the memory for removed elements
11982 is pruned, it still guarantees linear performance.
11984 @defmac m4_set_add (@var{set}, @var{value}, @ovar{if-uniq}, @ovar{if-dup})
11985 @msindex{set_add}
11986 Adds the string @var{value} as a member of set @var{set}.  Expand
11987 @var{if-uniq} if the element was added, or @var{if-dup} if it was
11988 previously in the set.  Operates in amortized constant time, so that set
11989 creation scales linearly.
11990 @end defmac
11992 @defmac m4_set_add_all (@var{set}, @var{value}@dots{})
11993 @msindex{set_add_all}
11994 Adds each @var{value} to the set @var{set}.  This is slightly more
11995 efficient than repeatedly invoking @code{m4_set_add}.
11996 @end defmac
11998 @defmac m4_set_contains (@var{set}, @var{value}, @ovar{if-present}, @
11999  @ovar{if-absent})
12000 @msindex{set_contains}
12001 Expands @var{if-present} if the string @var{value} is a member of
12002 @var{set}, otherwise @var{if-absent}.
12004 @example
12005 m4_set_contains([a], [1], [yes], [no])
12006 @result{}no
12007 m4_set_add([a], [1], [added], [dup])
12008 @result{}added
12009 m4_set_add([a], [1], [added], [dup])
12010 @result{}dup
12011 m4_set_contains([a], [1], [yes], [no])
12012 @result{}yes
12013 m4_set_remove([a], [1], [removed], [missing])
12014 @result{}removed
12015 m4_set_contains([a], [1], [yes], [no])
12016 @result{}no
12017 m4_set_remove([a], [1], [removed], [missing])
12018 @result{}missing
12019 @end example
12020 @end defmac
12022 @defmac m4_set_contents (@var{set}, @ovar{sep})
12023 @defmacx m4_set_dump (@var{set}, @ovar{sep})
12024 @msindex{set_contents}
12025 @msindex{set_dump}
12026 Expands to a single string consisting of all the members of the set
12027 @var{set}, each separated by @var{sep}, which is not expanded.
12028 @code{m4_set_contents} leaves the elements in @var{set} but reclaims any
12029 memory occupied by removed elements, while @code{m4_set_dump} is a
12030 faster one-shot action that also deletes the set.  No provision is made
12031 for disambiguating members that contain a non-empty @var{sep} as a
12032 substring; use @code{m4_set_empty} to distinguish between an empty set
12033 and the set containing only the empty string.  The order of the output
12034 is unspecified; in the current implementation, part of the speed of
12035 @code{m4_set_dump} results from using a different output order than
12036 @code{m4_set_contents}.  These macros scale linearly in the size of the
12037 set before memory pruning, and @code{m4_set_contents([@var{set}],
12038 [@var{sep}])} is faster than
12039 @code{m4_joinall([@var{sep}]m4_set_listc([@var{set}]))}.
12041 @example
12042 m4_set_add_all([a], [1], [2], [3])
12043 @result{}
12044 m4_set_contents([a], [-])
12045 @result{}1-2-3
12046 m4_joinall([-]m4_set_listc([a]))
12047 @result{}1-2-3
12048 m4_set_dump([a], [-])
12049 @result{}3-2-1
12050 m4_set_contents([a])
12051 @result{}
12052 m4_set_add([a], [])
12053 @result{}
12054 m4_set_contents([a], [-])
12055 @result{}
12056 @end example
12057 @end defmac
12059 @defmac m4_set_delete (@var{set})
12060 @msindex{set_delete}
12061 Delete all elements and memory associated with @var{set}.  This is
12062 linear in the set size, and faster than removing one element at a time.
12063 @end defmac
12065 @defmac m4_set_difference (@var{seta}, @var{setb})
12066 @defmacx m4_set_intersection (@var{seta}, @var{setb})
12067 @defmacx m4_set_union (@var{seta}, @var{setb})
12068 @msindex{set_difference}
12069 @msindex{set_intersection}
12070 @msindex{set_union}
12071 Compute the relation between @var{seta} and @var{setb}, and output the
12072 result as a list of quoted arguments without duplicates and with a
12073 leading comma.  Set difference selects the elements in @var{seta} but
12074 not @var{setb}, intersection selects only elements in both sets, and
12075 union selects elements in either set.  These actions are linear in the
12076 sum of the set sizes.  The leading comma is necessary to distinguish
12077 between no elements and the empty string as the only element.
12079 @example
12080 m4_set_add_all([a], [1], [2], [3])
12081 @result{}
12082 m4_set_add_all([b], [3], [], [4])
12083 @result{}
12084 m4_set_difference([a], [b])
12085 @result{},1,2
12086 m4_set_difference([b], [a])
12087 @result{},,4
12088 m4_set_intersection([a], [b])
12089 @result{},3
12090 m4_set_union([a], [b])
12091 @result{},1,2,3,,4
12092 @end example
12093 @end defmac
12095 @defmac m4_set_empty (@var{set}, @ovar{if-empty}, @ovar{if-elements})
12096 @msindex{set_empty}
12097 Expand @var{if-empty} if the set @var{set} has no elements, otherwise
12098 expand @var{if-elements}.  This macro operates in constant time.  Using
12099 this macro can help disambiguate output from @code{m4_set_contents} or
12100 @code{m4_set_list}.
12101 @end defmac
12103 @defmac m4_set_foreach (@var{set}, @var{variable}, @var{action})
12104 @msindex{set_foreach}
12105 For each element in the set @var{set}, expand @var{action} with the
12106 macro @var{variable} defined as the set element.  Behavior is
12107 unspecified if @var{action} recursively lists the contents of @var{set}
12108 (although listing other sets is acceptable), or if it modifies the set
12109 in any way other than removing the element currently contained in
12110 @var{variable}.  This macro is faster than the corresponding
12111 @code{m4_foreach([@var{variable}],
12112 m4_indir([m4_dquote]m4_set_listc([@var{set}])), [@var{action}])},
12113 although @code{m4_set_map} might be faster still.
12115 @example
12116 m4_set_add_all([a]m4_for([i], [1], [5], [], [,i]))
12117 @result{}
12118 m4_set_contents([a])
12119 @result{}12345
12120 m4_set_foreach([a], [i],
12121   [m4_if(m4_eval(i&1), [0], [m4_set_remove([a], i, [i])])])
12122 @result{}24
12123 m4_set_contents([a])
12124 @result{}135
12125 @end example
12126 @end defmac
12128 @defmac m4_set_list (@var{set})
12129 @defmacx m4_set_listc (@var{set})
12130 @msindex{set_list}
12131 @msindex{set_listc}
12132 Produce a list of arguments, where each argument is a quoted element
12133 from the set @var{set}.  The variant @code{m4_set_listc} is unambiguous,
12134 by adding a leading comma if there are any set elements, whereas the
12135 variant @code{m4_set_list} cannot distinguish between an empty set and a
12136 set containing only the empty string.  These can be directly used in
12137 macros that take multiple arguments, such as @code{m4_join} or
12138 @code{m4_set_add_all}, or wrapped by @code{m4_dquote} for macros that
12139 take a quoted list, such as @code{m4_map} or @code{m4_foreach}.  Any
12140 memory occupied by removed elements is reclaimed during these macros.
12142 @example
12143 m4_set_add_all([a], [1], [2], [3])
12144 @result{}
12145 m4_set_list([a])
12146 @result{}1,2,3
12147 m4_set_list([b])
12148 @result{}
12149 m4_set_listc([b])
12150 @result{}
12151 m4_count(m4_set_list([b]))
12152 @result{}1
12153 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12154 @result{}0
12155 m4_set_add([b], [])
12156 @result{}
12157 m4_set_list([b])
12158 @result{}
12159 m4_set_listc([b])
12160 @result{},
12161 m4_count(m4_set_list([b]))
12162 @result{}1
12163 m4_set_empty([b], [0], [m4_count(m4_set_list([b]))])
12164 @result{}1
12165 @end example
12166 @end defmac
12168 @defmac m4_set_map (@var{set}, @var{action})
12169 @msindex{set_map}
12170 For each element in the set @var{set}, expand @var{action} with a single
12171 argument of the set element.  Behavior is unspecified if @var{action}
12172 recursively lists the contents of @var{set} (although listing other sets
12173 is acceptable), or if it modifies the set in any way other than removing
12174 the element passed as an argument.  This macro is faster than either
12175 corresponding counterpart of
12176 @code{m4_map_args([@var{action}]m4_set_listc([@var{set}]))} or
12177 @code{m4_set_foreach([@var{set}], [var],
12178 [@var{action}(m4_defn([var]))])}.  It is possible to use @code{m4_curry}
12179 if more than one argument is needed for @var{action}, although it is
12180 more efficient to use @code{m4_set_map_sep} in that case.
12181 @end defmac
12183 @defmac m4_set_map_sep (@var{set}, @ovar{pre}, @ovar{post}, @ovar{sep})
12184 @msindex{set_map_sep}
12185 For each element in the set @var{set}, expand
12186 @code{@var{pre}[element]@var{post}}, additionally expanding @var{sep}
12187 between elements.  Behavior is unspecified if the expansion recursively
12188 lists the contents of @var{set} (although listing other sets
12189 is acceptable), or if it modifies the set in any way other than removing
12190 the element visited by the expansion.  This macro provides the most
12191 efficient means for non-destructively visiting the elements of a set; in
12192 particular, @code{m4_set_map([@var{set}], [@var{action}])} is equivalent
12193 to @code{m4_set_map_sep([@var{set}], [@var{action}(], [)])}.
12194 @end defmac
12196 @defmac m4_set_remove (@var{set}, @var{value}, @ovar{if-present}, @
12197  @ovar{if-absent})
12198 @msindex{set_remove}
12199 If @var{value} is an element in the set @var{set}, then remove it and
12200 expand @var{if-present}.  Otherwise expand @var{if-absent}.  This macro
12201 operates in constant time so that multiple removals will scale linearly
12202 rather than quadratically; but when used outside of
12203 @code{m4_set_foreach} or @code{m4_set_map}, it leaves memory occupied
12204 until the set is later
12205 compacted by @code{m4_set_contents} or @code{m4_set_list}.  Several
12206 other set operations are then less efficient between the time of element
12207 removal and subsequent memory compaction, but still maintain their
12208 guaranteed scaling performance.
12209 @end defmac
12211 @defmac m4_set_size (@var{set})
12212 @msindex{set_size}
12213 Expand to the size of the set @var{set}.  This implementation operates
12214 in constant time, and is thus more efficient than
12215 @code{m4_eval(m4_count(m4_set_listc([set])) - 1)}.
12216 @end defmac
12219 @node Forbidden Patterns
12220 @subsection Forbidden Patterns
12221 @cindex Forbidden patterns
12222 @cindex Patterns, forbidden
12224 M4sugar provides a means to define suspicious patterns, patterns
12225 describing tokens which should not be found in the output.  For
12226 instance, if an Autoconf @file{configure} script includes tokens such as
12227 @samp{AC_DEFINE}, or @samp{dnl}, then most probably something went
12228 wrong (typically a macro was not evaluated because of overquotation).
12230 M4sugar forbids all the tokens matching @samp{^_?m4_} and @samp{^dnl$}.
12231 Additional layers, such as M4sh and Autoconf, add additional forbidden
12232 patterns to the list.
12234 @defmac m4_pattern_forbid (@var{pattern})
12235 @msindex{pattern_forbid}
12236 Declare that no token matching @var{pattern} must be found in the output.
12237 Comments are not checked; this can be a problem if, for instance, you
12238 have some macro left unexpanded after an @samp{#include}.  No consensus
12239 is currently found in the Autoconf community, as some people consider it
12240 should be valid to name macros in comments (which doesn't make sense to
12241 the authors of this documentation: input, such as macros, should be
12242 documented by @samp{dnl} comments; reserving @samp{#}-comments to
12243 document the output).
12244 @end defmac
12246 Of course, you might encounter exceptions to these generic rules, for
12247 instance you might have to refer to @samp{$m4_flags}.
12249 @defmac m4_pattern_allow (@var{pattern})
12250 @msindex{pattern_allow}
12251 Any token matching @var{pattern} is allowed, including if it matches an
12252 @code{m4_pattern_forbid} pattern.
12253 @end defmac
12255 @node Programming in M4sh
12256 @chapter Programming in M4sh
12258 M4sh, pronounced ``mash'', is aiming at producing portable Bourne shell
12259 scripts.  This name was coined by Lars J. Aas, who notes that,
12260 according to the Webster's Revised Unabridged Dictionary (1913):
12262 @quotation
12263 Mash \Mash\, n.  [Akin to G. meisch, maisch, meische, maische, mash,
12264 wash, and prob.@: to AS. miscian to mix.  See ``Mix''.]
12266 @enumerate 1
12267 @item
12268 A mass of mixed ingredients reduced to a soft pulpy state by beating or
12269 pressure@enddots{}
12271 @item
12272 A mixture of meal or bran and water fed to animals.
12274 @item
12275 A mess; trouble.  [Obs.] --Beau.@: & Fl.
12276 @end enumerate
12277 @end quotation
12279 M4sh reserves the M4 macro namespace @samp{^_AS_} for internal use, and
12280 the namespace @samp{^AS_} for M4sh macros.  It also reserves the shell
12281 and environment variable namespace @samp{^as_}, and the here-doc
12282 delimiter namespace @samp{^_AS[A-Z]} in the output file.  You should not
12283 define your own macros or output shell code that conflicts with these
12284 namespaces.
12286 @menu
12287 * Common Shell Constructs::     Portability layer for common shell constructs
12288 * Polymorphic Variables::       Support for indirect variable names
12289 * Initialization Macros::       Macros to establish a sane shell environment
12290 * File Descriptor Macros::      File descriptor macros for input and output
12291 @end menu
12293 @node Common Shell Constructs
12294 @section Common Shell Constructs
12296 M4sh provides portable alternatives for some common shell constructs
12297 that unfortunately are not portable in practice.
12299 @c Deprecated, to be replaced by a better API
12300 @ignore
12301 @defmac AS_BASENAME (@var{file-name})
12302 @asindex{BASENAME}
12303 Output the non-directory portion of @var{file-name}.  For example,
12304 if @code{$file} is @samp{/one/two/three}, the command
12305 @code{base=`AS_BASENAME(["$file"])`} sets @code{base} to @samp{three}.
12306 @end defmac
12307 @end ignore
12309 @defmac AS_CASE (@var{word}, @ovar{pattern1}, @ovar{if-matched1}, @
12310   @dots{}, @ovar{default})
12311 @asindex{CASE}
12312 Expand into a shell @samp{case} statement, where @var{word} is matched
12313 against one or more patterns.  @var{if-matched} is run if the
12314 corresponding pattern matched @var{word}, else @var{default} is run.
12315 Avoids several portability issues (@pxref{case, , Limitations of Shell
12316 Builtins}).
12317 @end defmac
12319 @c Deprecated, to be replaced by a better API
12320 @ignore
12321 @defmac AS_DIRNAME (@var{file-name})
12322 @asindex{DIRNAME}
12323 Output the directory portion of @var{file-name}.  For example,
12324 if @code{$file} is @samp{/one/two/three}, the command
12325 @code{dir=`AS_DIRNAME(["$file"])`} sets @code{dir} to @samp{/one/two}.
12326 @end defmac
12327 @end ignore
12329 @defmac AS_ECHO (@var{word})
12330 @asindex{ECHO}
12331 Emits @var{word} to the standard output, followed by a newline.  @var{word}
12332 must be a single shell word (typically a quoted string).  The bytes of
12333 @var{word} are output as-is, even if it starts with "-" or contains "\".
12334 Redirections can be placed outside the macro invocation.  This is much
12335 more portable than using @command{echo} (@pxref{echo, , Limitations of
12336 Shell Builtins}).
12337 @end defmac
12339 @defmac AS_ECHO_N (@var{word})
12340 @asindex{ECHO_N}
12341 Emits @var{word} to the standard output, without a following newline.
12342 @var{word} must be a single shell word (typically a quoted string) and,
12343 for portability, should not include more than one newline.  The bytes of
12344 @var{word} are output as-is, even if it starts with "-" or contains "\".
12345 Redirections can be placed outside the macro invocation.
12346 @end defmac
12348 @defmac AS_ESCAPE (@var{string}, @dvar{chars, `\"$})
12349 @asindex{ESCAPE}
12350 Expands to @var{string}, with any characters in @var{chars} escaped with
12351 a backslash (@samp{\}).  @var{chars} should be at most four bytes long,
12352 and only contain characters from the set @samp{`\"$}; however,
12353 characters may be safely listed more than once in @var{chars} for the
12354 sake of syntax highlighting editors.  The current implementation expands
12355 @var{string} after adding escapes; if @var{string} contains macro calls
12356 that in turn expand to text needing shell quoting, you can use
12357 @code{AS_ESCAPE(m4_dquote(m4_expand([string])))}.
12359 The default for @var{chars} (@samp{\"$`}) is the set of characters
12360 needing escapes when @var{string} will be used literally within double
12361 quotes.  One common variant is the set of characters to protect when
12362 @var{string} will be used literally within back-ticks or an unquoted
12363 here-doc (@samp{\$`}).  Another common variant is @samp{""}, which can
12364 be used to form a double-quoted string containing the same expansions
12365 that would have occurred if @var{string} were expanded in an unquoted
12366 here-doc; however, when using this variant, care must be taken that
12367 @var{string} does not use double quotes within complex variable
12368 expansions (such as @samp{$@{foo-`echo "hi"`@}}) that would be broken
12369 with improper escapes.
12371 This macro is often used with @code{AS_ECHO}.  For an example, observe
12372 the output generated by the shell code generated from this snippet:
12374 @example
12375 foo=bar
12376 AS_ECHO(["AS_ESCAPE(["$foo" = ])AS_ESCAPE(["$foo"], [""])"])
12377 @result{}"$foo" = "bar"
12378 m4_define([macro], [a, [\b]])
12379 AS_ECHO(["AS_ESCAPE([[macro]])"])
12380 @result{}macro
12381 AS_ECHO(["AS_ESCAPE([macro])"])
12382 @result{}a, b
12383 AS_ECHO(["AS_ESCAPE(m4_dquote(m4_expand([macro])))"])
12384 @result{}a, \b
12385 @end example
12387 @comment Should we add AS_ESCAPE_SINGLE? If we do, we can optimize in
12388 @comment the case of @var{string} that does not contain '.
12389 To escape a string that will be placed within single quotes, use:
12391 @example
12392 m4_bpatsubst([[@var{string}]], ['], ['\\''])
12393 @end example
12394 @end defmac
12396 @defmac AS_EXIT (@dvar{status, $?})
12397 @asindex{EXIT}
12398 Emit code to exit the shell with @var{status}, defaulting to @samp{$?}.
12399 This macro
12400 works around shells that see the exit status of the command prior to
12401 @code{exit} inside a @samp{trap 0} handler (@pxref{trap, , Limitations
12402 of Shell Builtins}).
12403 @end defmac
12405 @defmac AS_IF (@var{test1}, @ovar{run-if-true1}, @dots{}, @ovar{run-if-false})
12406 @asindex{IF}
12407 Run shell code @var{test1}.  If @var{test1} exits with a zero status then
12408 run shell code @var{run-if-true1}, else examine further tests.  If no test
12409 exits with a zero status, run shell code @var{run-if-false}, with
12410 simplifications if either @var{run-if-true1} or @var{run-if-false}
12411 is empty.  For example,
12413 @example
12414 AS_IF([test "$foo" = yes], [HANDLE_FOO([yes])],
12415       [test "$foo" != no], [HANDLE_FOO([maybe])],
12416       [echo foo not specified])
12417 @end example
12419 @noindent
12420 ensures any required macros of @code{HANDLE_FOO}
12421 are expanded before the first test.
12422 @end defmac
12424 @defmac AS_MKDIR_P (@var{file-name})
12425 @asindex{MKDIR_P}
12426 Make the directory @var{file-name}, including intervening directories
12427 as necessary.  This is equivalent to @samp{mkdir -p -- @var{file-name}},
12428 except that it is portable to older versions of @command{mkdir} that
12429 lack support for the @option{-p} option or for the @option{--}
12430 delimiter (@pxref{mkdir, , Limitations of Usual Tools}).  Also,
12431 @code{AS_MKDIR_P}
12432 succeeds if @var{file-name} is a symbolic link to an existing directory,
12433 even though Posix is unclear whether @samp{mkdir -p} should
12434 succeed in that case.  If creation of @var{file-name} fails, exit the
12435 script.
12437 Also see the @code{AC_PROG_MKDIR_P} macro (@pxref{Particular Programs}).
12438 @end defmac
12440 @defmac AS_SET_STATUS (@var{status})
12441 @asindex{SET_STATUS}
12442 Emit shell code to set the value of @samp{$?} to @var{status}, as
12443 efficiently as possible.  However, this is not guaranteed to abort a
12444 shell running with @code{set -e} (@pxref{set, , Limitations of Shell
12445 Builtins}).
12446 @end defmac
12448 @defmac AS_TR_CPP (@var{expression})
12449 @asindex{TR_CPP}
12450 Transform @var{expression} into a valid right-hand side for a C @code{#define}.
12451 For example:
12453 @example
12454 # This outputs "#define HAVE_CHAR_P 1".
12455 type="char *"
12456 echo "#define AS_TR_CPP([HAVE_$type]) 1"
12457 @end example
12458 @end defmac
12460 @defmac AS_TR_SH (@var{expression})
12461 @asindex{TR_SH}
12462 Transform @var{expression} into a valid shell variable name.  For example:
12464 @example
12465 # This outputs "Have it!".
12466 header="sys/some file.h"
12467 AS_TR_SH([HAVE_$header])=yes
12468 if test "$HAVE_sys_some_file_h" = yes; then echo "Have it!"; fi
12469 @end example
12470 @end defmac
12472 @defmac AS_SET_CATFILE (@var{var}, @var{dir}, @var{file})
12473 @asindex{SET_CATFILE}
12474 Set the shell variable @var{var} to @var{dir}/@var{file}, but
12475 optimizing the common cases (@var{dir} or @var{file} is @samp{.},
12476 @var{file} is absolute, etc.).
12477 @end defmac
12479 @defmac AS_UNSET (@var{var})
12480 @asindex{UNSET}
12481 Unsets the shell variable @var{var}, working around bugs in older
12482 shells (@pxref{unset, , Limitations of Shell
12483 Builtins}).  @var{var} can be a literal or indirect variable name.
12484 @end defmac
12486 @defmac AS_VERSION_COMPARE (@var{version-1}, @var{version-2}, @
12487   @ovar{action-if-less}, @ovar{action-if-equal}, @ovar{action-if-greater})
12488 @asindex{VERSION_COMPARE}
12489 Compare two strings @var{version-1} and @var{version-2}, possibly
12490 containing shell variables, as version strings, and expand
12491 @var{action-if-less}, @var{action-if-equal}, or @var{action-if-greater}
12492 depending upon the result.
12493 The algorithm to compare is similar to the one used by strverscmp in
12494 glibc (@pxref{String/Array Comparison, , String/Array Comparison, libc,
12495 The @acronym{GNU} C Library}).
12496 @end defmac
12498 @node Polymorphic Variables
12499 @section Support for indirect variable names
12500 @cindex variable name indirection
12501 @cindex polymorphic variable name
12502 @cindex indirection, variable name
12504 Often, it is convenient to write a macro that will emit shell code
12505 operating on a shell variable.  The simplest case is when the variable
12506 name is known.  But a more powerful idiom is writing shell code that can
12507 work through an indirection, where another variable or command
12508 substitution produces the name of the variable to actually manipulate.
12509 M4sh supports the notion of polymorphic shell variables, making it easy
12510 to write a macro that can deal with either literal or indirect variable
12511 names and output shell code appropriate for both use cases.  Behavior is
12512 undefined if expansion of an indirect variable does not result in a
12513 literal variable name.
12515 @defmac AS_LITERAL_IF (@var{expression}, @ovar{if-literal}, @ovar{if-not})
12516 @asindex{LITERAL_IF}
12517 If the expansion of @var{expression} is definitely a shell literal,
12518 expand @var{if-literal}.  If the expansion of @var{expression} looks
12519 like it might contain shell indirections (such as @code{$var} or
12520 @code{`expr`}), then @var{if-not} is expanded.  In order to reduce the
12521 time spent deciding whether an expression is literal, the implementation
12522 is somewhat conservative (for example, @samp{'[$]'} is a single-quoted
12523 shell literal, but causes @var{if-not} to be expanded).  While this
12524 macro is often used for recognizing shell variable names, it can also be
12525 used in other contexts.
12527 @example
12528 AC_DEFUN([MY_ACTION],
12529 [AS_LITERAL_IF([$1],
12530 [echo "$1"],
12531 [AS_VAR_COPY([tmp], [$1])
12532 echo "$tmp"])])
12533 @end example
12534 @end defmac
12536 @defmac AS_VAR_APPEND (@var{var}, @var{text})
12537 @asindex{APPEND}
12538 Emit shell code to append the shell expansion of @var{text} to the end
12539 of the current contents of the polymorphic shell variable @var{var},
12540 taking advantage of shells that provide the @samp{+=} extension for more
12541 efficient scaling.
12543 For situations where the final contents of @var{var} are relatively
12544 short (less than 256 bytes), it is more efficient to use the simpler
12545 code sequence of @code{@var{var}=$@{@var{var}@}@var{text}} (or its
12546 polymorphic equivalent of @code{AS_VAR_COPY([tmp], [@var{var}])} and
12547 @code{AS_VAR_SET([@var{var}], ["$tmp"@var{text}])}).  But in the case
12548 when the script will be repeatedly appending text into @code{var},
12549 issues of scaling start to become apparent.  A naive implementation
12550 requires execution time linear to the length of the current contents of
12551 @var{var} as well as the length of @var{text} for a single append, for
12552 an overall quadratic scaling with multiple appends.  This macro takes
12553 advantage of shells which provide the extension
12554 @code{@var{var}+=@var{text}}, which can provide amortized constant time
12555 for a single append, for an overall linear scaling with multiple
12556 appends.  Note that unlike @code{AS_VAR_SET}, this macro requires that
12557 @var{text} be quoted properly to avoid field splitting and file name
12558 expansion.
12559 @end defmac
12561 @defmac AS_VAR_ARITH (@var{var}, @var{expression})
12562 @asindex{ARITH}
12563 Emit shell code to compute the arithmetic expansion of @var{expression},
12564 assigning the result as the contents of the polymorphic shell variable
12565 @var{var}.  The code takes advantage of shells that provide @samp{$(())}
12566 for fewer forks, but uses @command{expr} as a fallback.  Therefore, the
12567 syntax for a valid @var{expression} is rather limited: all operators
12568 must occur as separate shell arguments and with proper quoting, there is
12569 no portable equality operator, all variables containing numeric values
12570 must be expanded prior to the computation, all numeric values must be
12571 provided in decimal without leading zeroes, and the first shell argument
12572 should not be a negative number.  In the following example, this snippet
12573 will print @samp{(2+3)*4 == 20}.
12575 @example
12576 bar=3
12577 AS_VAR_ARITH([foo], [\( 2 + $bar \) \* 4])
12578 echo "(2+$bar)*4 == $foo"
12579 @end example
12580 @end defmac
12582 @defmac AS_VAR_COPY (@var{dest}, @var{source})
12583 @asindex{VAR_COPY}
12584 Emit shell code to assign the contents of the polymorphic shell variable
12585 @var{source} to the polymorphic shell variable @var{dest}.  For example,
12586 executing this M4sh snippet will output @samp{bar hi}:
12588 @example
12589 foo=bar bar=hi
12590 AS_VAR_COPY([a], [foo])
12591 AS_VAR_COPY([b], [$foo])
12592 echo "$a $b"
12593 @end example
12595 When it is necessary to access the contents of an indirect variable
12596 inside a shell double-quoted context, the recommended idiom is to first
12597 copy the contents into a temporary literal shell variable.
12599 @smallexample
12600 for header in stdint_h inttypes_h ; do
12601   AS_VAR_COPY([var], [ac_cv_header_$header])
12602   echo "$header detected: $var"
12603 done
12604 @end smallexample
12605 @end defmac
12607 @comment AS_VAR_GET is intentionally undocumented; it can't handle
12608 @comment trailing newlines uniformly, and forks too much.
12610 @defmac AS_VAR_IF (@var{var}, @ovar{value}, @ovar{if-equal}, @
12611   @ovar{if-not-equal})
12612 @asindex{VAR_IF}
12613 Output a shell conditional statement.  If the contents of the
12614 polymorphic shell variable @var{var} match the string @var{value},
12615 execute @var{if-equal}; otherwise execute @var{if-not-equal}.  Avoids
12616 shell bugs if an interrupt signal arrives while a command substitution
12617 in @var{var} is being expanded.
12618 @end defmac
12620 @defmac AS_VAR_PUSHDEF (@var{m4-name}, @var{value})
12621 @defmacx AS_VAR_POPDEF (@var{m4-name})
12622 @asindex{VAR_PUSHDEF}
12623 @asindex{VAR_POPDEF}
12624 @cindex composing variable names
12625 @cindex variable names, composing
12626 A common M4sh idiom involves composing shell variable names from an m4
12627 argument (for example, writing a macro that uses a cache variable).
12628 @var{value} can be an arbitrary string, which will be transliterated
12629 into a valid shell name by @code{AS_TR_SH}.  In order to access the
12630 composed variable name based on @var{value}, it is easier to declare a
12631 temporary m4 macro @var{m4-name} with @code{AS_VAR_PUSHDEF}, then use
12632 that macro as the argument to subsequent @code{AS_VAR} macros as a
12633 polymorphic variable name, and finally free the temporary macro with
12634 @code{AS_VAR_POPDEF}.  These macros are often followed with @code{dnl},
12635 to avoid excess newlines in the output.
12637 Here is an involved example, that shows the power of writing macros that
12638 can handle composed shell variable names:
12640 @example
12641 m4_define([MY_CHECK_HEADER],
12642 [AS_VAR_PUSHDEF([my_Header], [ac_cv_header_$1])dnl
12643 AS_VAR_IF([my_Header], [yes], [echo "header $1 available"])dnl
12644 AS_VAR_POPDEF([my_Header])dnl
12646 MY_CHECK_HEADER([stdint.h])
12647 for header in inttypes.h stdlib.h ; do
12648   MY_CHECK_HEADER([$header])
12649 done
12650 @end example
12652 @noindent
12653 In the above example, @code{MY_CHECK_HEADER} can operate on polymorphic
12654 variable names.  In the first invocation, the m4 argument is
12655 @code{stdint.h}, which transliterates into a literal @code{stdint_h}.
12656 As a result, the temporary macro @code{my_Header} expands to the literal
12657 shell name @samp{ac_cv_header_stdint_h}.  In the second invocation, the
12658 m4 argument to @code{MY_CHECK_HEADER} is @code{$header}, and the
12659 temporary macro @code{my_Header} expands to the indirect shell name
12660 @samp{$as_my_Header}.  During the shell execution of the for loop, when
12661 @samp{$header} contains @samp{inttypes.h}, then @samp{$as_my_Header}
12662 contains @samp{ac_cv_header_inttypes_h}.  If this script is then run on a
12663 platform where all three headers have been previously detected, the
12664 output of the script will include:
12666 @smallexample
12667 header stdint.h detected
12668 header inttypes.h detected
12669 header stdlib.h detected
12670 @end smallexample
12671 @end defmac
12673 @defmac AS_VAR_SET (@var{var}, @ovar{value})
12674 @asindex{VAR_SET}
12675 Emit shell code to assign the contents of the polymorphic shell variable
12676 @var{var} to the shell expansion of @var{value}.  @var{value} is not
12677 subject to field splitting or file name expansion, so if command
12678 substitution is used, it may be done with @samp{`""`} rather than using
12679 an intermediate variable (@pxref{Shell Substitutions}).  However,
12680 @var{value} does undergo rescanning for additional macro names; behavior
12681 is unspecified if late expansion results in any shell meta-characters.
12682 @end defmac
12684 @defmac AS_VAR_SET_IF (@var{var}, @ovar{if-set}, @ovar{if-undef})
12685 @asindex{VAR_SET_IF}
12686 Emit a shell conditional statement, which executes @var{if-set} if the
12687 polymorphic shell variable @code{var} is set to any value, and
12688 @var{if-undef} otherwise.
12689 @end defmac
12691 @defmac AS_VAR_TEST_SET (@var{var})
12692 @asindex{VAR_TEST_SET}
12693 Emit a shell statement that results in a successful exit status only if
12694 the polymorphic shell variable @code{var} is set.
12695 @end defmac
12697 @node Initialization Macros
12698 @section Initialization Macros
12700 @defmac AS_BOURNE_COMPATIBLE
12701 @asindex{BOURNE_COMPATIBLE}
12702 Set up the shell to be more compatible with the Bourne shell as
12703 standardized by Posix, if possible.  This may involve setting
12704 environment variables, or setting options, or similar
12705 implementation-specific actions.  This macro is deprecated, since
12706 @code{AS_INIT} already invokes it.
12707 @end defmac
12709 @defmac AS_INIT
12710 @asindex{INIT}
12711 @evindex LC_ALL
12712 @evindex SHELL
12713 Initialize the M4sh environment.  This macro calls @code{m4_init}, then
12714 outputs the @code{#! /bin/sh} line, a notice about where the output was
12715 generated from, and code to sanitize the environment for the rest of the
12716 script.  Among other initializations, this sets @env{SHELL} to the shell
12717 chosen to run the script (@pxref{CONFIG_SHELL}), and @env{LC_ALL} to
12718 ensure the C locale.  Finally, it changes the current diversion to
12719 @code{BODY}.
12720 @end defmac
12722 @defmac AS_INIT_GENERATED (@var{file}, @ovar{comment})
12723 @asindex{INIT_GENERATED}
12724 Emit shell code to start the creation of a subsidiary shell script in
12725 @var{file}, including changing @var{file} to be executable.  This macro
12726 populates the child script with information learned from the parent
12727 (thus, the emitted code is equivalent in effect, but more efficient,
12728 than the code output by @code{AS_INIT}, @code{AS_BOURNE_COMPATIBLE}, and
12729 @code{AS_SHELL_SANITIZE}).  If present, @var{comment} is output near the
12730 beginning of the child, prior to the shell initialization code, and is
12731 subject to parameter expansion, command substitution, and backslash
12732 quote removal.  The
12733 parent script should check the exit status after this macro, in case
12734 @var{file} could not be properly created (for example, if the disk was
12735 full).  If successfully created, the parent script can then proceed to
12736 append additional M4sh constructs into the child script.
12738 Note that the child script starts life without a log file open, so if
12739 the parent script uses logging (@pxref{AS_MESSAGE_LOG_FD}), you
12740 must temporarily disable any attempts to use the log file until after
12741 emitting code to open a log within the child.  On the other hand, if the
12742 parent script has @code{AS_MESSAGE_FD} redirected somewhere besides
12743 @samp{1}, then the child script already has code that copies stdout to
12744 that descriptor.  Currently, the suggested
12745 idiom for writing a M4sh shell script from within another script is:
12747 @example
12748 AS_INIT_GENERATED([@var{file}], [[# My child script.
12749 ]]) || @{ AS_ECHO(["Failed to create child script"]); AS_EXIT; @}
12750 m4_pushdef([AS_MESSAGE_LOG_FD])dnl
12751 cat >> "@var{file}" <<\__EOF__
12752 # Code to initialize AS_MESSAGE_LOG_FD
12753 m4_popdef([AS_MESSAGE_LOG_FD])dnl
12754 # Additional code
12755 __EOF__
12756 @end example
12758 This, however, may change in the future as the M4sh interface is
12759 stabilized further.
12761 Also, be aware that use of @env{LINENO} within the child script may
12762 report line numbers relative to their location in the parent script,
12763 even when using @code{AS_LINENO_PREPARE}, if the parent script was
12764 unable to locate a shell with working @env{LINENO} support.
12765 @end defmac
12767 @defmac AS_LINENO_PREPARE
12768 @asindex{LINENO_PREPARE}
12769 @evindex LINENO
12770 Find a shell that supports the special variable @env{LINENO}, which
12771 contains the number of the currently executing line.  This macro is
12772 automatically invoked by @code{AC_INIT} in configure scripts.
12773 @end defmac
12775 @defmac AS_ME_PREPARE
12776 @asindex{ME_PREPARE}
12777 Set up variable @env{as_me} to be the basename of the currently executing
12778 script.  This macro is automatically invoked by @code{AC_INIT} in
12779 configure scripts.
12780 @end defmac
12782 @defmac AS_SHELL_SANITIZE
12783 @asindex{SHELL_SANITIZE}
12784 Initialize the shell suitably for @command{configure} scripts.  This has
12785 the effect of @code{AS_BOURNE_COMPATIBLE}, and sets some other
12786 environment variables for predictable results from configuration tests.
12787 For example, it sets @env{LC_ALL} to change to the default C locale.
12788 @xref{Special Shell Variables}.  This macro is deprecated, since
12789 @code{AS_INIT} already invokes it.
12790 @end defmac
12793 @node File Descriptor Macros
12794 @section File Descriptor Macros
12795 @cindex input
12796 @cindex standard input
12797 @cindex file descriptors
12798 @cindex descriptors
12799 @cindex low-level output
12800 @cindex output, low-level
12802 The following macros define file descriptors used to output messages
12803 (or input values) from @file{configure} scripts.
12804 For example:
12806 @example
12807 echo "$wombats found" >&AS_MESSAGE_LOG_FD
12808 echo 'Enter desired kangaroo count:' >&AS_MESSAGE_FD
12809 read kangaroos <&AS_ORIGINAL_STDIN_FD`
12810 @end example
12812 @noindent
12813 However doing so is seldom needed, because Autoconf provides higher
12814 level macros as described below.
12816 @defmac AS_MESSAGE_FD
12817 @asindex{MESSAGE_FD}
12818 The file descriptor for @samp{checking for...}  messages and results.
12819 By default, @code{AS_INIT} sets this to @samp{1} for standalone M4sh
12820 clients.  However, @code{AC_INIT} shuffles things around to another file
12821 descriptor, in order to allow the @option{-q} option of
12822 @command{configure} to choose whether messages should go to the script's
12823 standard output or be discarded.
12825 If you want to display some messages, consider using one of the printing
12826 macros (@pxref{Printing Messages}) instead.  Copies of messages output
12827 via these macros are also recorded in @file{config.log}.
12828 @end defmac
12830 @anchor{AS_MESSAGE_LOG_FD}
12831 @defmac AS_MESSAGE_LOG_FD
12832 @asindex{MESSAGE_LOG_FD}
12833 This must either be empty, or expand to a file descriptor for log
12834 messages.  By default, @code{AS_INIT} sets this macro to the empty
12835 string for standalone M4sh clients, thus disabling logging.  However,
12836 @code{AC_INIT} shuffles things around so that both @command{configure}
12837 and @command{config.status} use @file{config.log} for log messages.
12838 Macros that run tools, like @code{AC_COMPILE_IFELSE} (@pxref{Running the
12839 Compiler}), redirect all output to this descriptor.  You may want to do
12840 so if you develop such a low-level macro.
12841 @end defmac
12843 @defmac AS_ORIGINAL_STDIN_FD
12844 @asindex{ORIGINAL_STDIN_FD}
12845 This must expand to a file descriptor for the original standard input.
12846 By default, @code{AS_INIT} sets this macro to @samp{0} for standalone
12847 M4sh clients.  However, @code{AC_INIT} shuffles things around for
12848 safety.
12850 When @command{configure} runs, it may accidentally execute an
12851 interactive command that has the same name as the non-interactive meant
12852 to be used or checked.  If the standard input was the terminal, such
12853 interactive programs would cause @command{configure} to stop, pending
12854 some user input.  Therefore @command{configure} redirects its standard
12855 input from @file{/dev/null} during its initialization.  This is not
12856 normally a problem, since @command{configure} normally does not need
12857 user input.
12859 In the extreme case where your @file{configure} script really needs to
12860 obtain some values from the original standard input, you can read them
12861 explicitly from @code{AS_ORIGINAL_STDIN_FD}.
12862 @end defmac
12865 @c =================================================== Writing Autoconf Macros.
12867 @node Writing Autoconf Macros
12868 @chapter Writing Autoconf Macros
12870 When you write a feature test that could be applicable to more than one
12871 software package, the best thing to do is encapsulate it in a new macro.
12872 Here are some instructions and guidelines for writing Autoconf macros.
12874 @menu
12875 * Macro Definitions::           Basic format of an Autoconf macro
12876 * Macro Names::                 What to call your new macros
12877 * Reporting Messages::          Notifying @command{autoconf} users
12878 * Dependencies Between Macros::  What to do when macros depend on other macros
12879 * Obsoleting Macros::           Warning about old ways of doing things
12880 * Coding Style::                Writing Autoconf macros @`a la Autoconf
12881 @end menu
12883 @node Macro Definitions
12884 @section Macro Definitions
12886 @defmac AC_DEFUN (@var{name}, @ovar{body})
12887 @acindex{DEFUN}
12888 Autoconf macros are defined using the @code{AC_DEFUN} macro, which is
12889 similar to the M4 builtin @code{m4_define} macro; this creates a macro
12890 named @var{name} and with @var{body} as its expansion.  In addition to
12891 defining a macro, @code{AC_DEFUN} adds to it some code that is used to
12892 constrain the order in which macros are called, while avoiding redundant
12893 output (@pxref{Prerequisite Macros}).
12894 @end defmac
12896 An Autoconf macro definition looks like this:
12898 @example
12899 AC_DEFUN(@var{macro-name}, @var{macro-body})
12900 @end example
12902 You can refer to any arguments passed to the macro as @samp{$1},
12903 @samp{$2}, etc.  @xref{Definitions, , How to define new macros, m4.info,
12904 @acronym{GNU} M4}, for more complete information on writing M4 macros.
12906 Most macros fall in one of two general categories.  The first category
12907 includes macros which take arguments, in order to generate output
12908 parameterized by those arguments.  Macros in this category are designed
12909 to be directly expanded, often multiple times, and should not be used as
12910 the argument to @code{AC_REQUIRE}.  The other category includes macros
12911 which are shorthand for a fixed block of text, and therefore do not take
12912 arguments.  For this category of macros, directly expanding the macro
12913 multiple times results in redundant output, so it is more common to use
12914 the macro as the argument to @code{AC_REQUIRE}, or to declare the macro
12915 with @code{AC_DEFUN_ONCE} (@pxref{One-Shot Macros}).
12917 Be sure to properly quote both the @var{macro-body} @emph{and} the
12918 @var{macro-name} to avoid any problems if the macro happens to have
12919 been previously defined.
12921 Each macro should have a header comment that gives its prototype, and a
12922 brief description.  When arguments have default values, display them in
12923 the prototype.  For example:
12925 @example
12926 # AC_MSG_ERROR(ERROR, [EXIT-STATUS = 1])
12927 # --------------------------------------
12928 m4_define([AC_MSG_ERROR],
12929   [@{ AS_MESSAGE([error: $1], [2])
12930      exit m4_default([$2], [1]); @}])
12931 @end example
12933 Comments about the macro should be left in the header comment.  Most
12934 other comments make their way into @file{configure}, so just keep
12935 using @samp{#} to introduce comments.
12937 @cindex @code{dnl}
12938 If you have some special comments about pure M4 code, comments
12939 that make no sense in @file{configure} and in the header comment, then
12940 use the builtin @code{dnl}: it causes M4 to discard the text
12941 through the next newline.
12943 Keep in mind that @code{dnl} is rarely needed to introduce comments;
12944 @code{dnl} is more useful to get rid of the newlines following macros
12945 that produce no output, such as @code{AC_REQUIRE}.
12948 @node Macro Names
12949 @section Macro Names
12951 All of the public Autoconf macros have all-uppercase names in the
12952 namespace @samp{^AC_} to prevent them from accidentally conflicting with
12953 other text; Autoconf also reserves the namespace @samp{^_AC_} for
12954 internal macros.  All shell variables that they use for internal
12955 purposes have mostly-lowercase names starting with @samp{ac_}.  Autoconf
12956 also uses here-doc delimiters in the namespace @samp{^_AC[A-Z]}.  During
12957 @command{configure}, files produced by Autoconf make heavy use of the
12958 file system namespace @samp{^conf}.
12960 Since Autoconf is built on top of M4sugar (@pxref{Programming in
12961 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
12962 of those namespaces (@samp{^_?\(m4\|AS\)_}).  And since
12963 @file{configure.ac} is also designed to be scanned by Autoheader,
12964 Autoscan, Autoupdate, and Automake, you should be aware of the
12965 @samp{^_?A[HNUM]_} namespaces.  In general, you @emph{should not use}
12966 the namespace of a package that does not own the macro or shell code you
12967 are writing.
12969 To ensure that your macros don't conflict with present or future
12970 Autoconf macros, you should prefix your own macro names and any shell
12971 variables they use with some other sequence.  Possibilities include your
12972 initials, or an abbreviation for the name of your organization or
12973 software package.  Historically, people have not always followed the
12974 rule of using a namespace appropriate for their package, and this has
12975 made it difficult for determining the origin of a macro (and where to
12976 report bugs about that macro), as well as difficult for the true
12977 namespace owner to add new macros without interference from pre-existing
12978 uses of third-party macros.  Perhaps the best example of this confusion
12979 is the @code{AM_GNU_GETTEXT} macro, which belongs, not to Automake, but
12980 to Gettext.
12982 Most of the Autoconf macros' names follow a structured naming convention
12983 that indicates the kind of feature check by the name.  The macro names
12984 consist of several words, separated by underscores, going from most
12985 general to most specific.  The names of their cache variables use the
12986 same convention (@pxref{Cache Variable Names}, for more information on
12987 them).
12989 The first word of the name after the namespace initials (such as
12990 @samp{AC_}) usually tells the category
12991 of the feature being tested.  Here are the categories used in Autoconf for
12992 specific test macros, the kind of macro that you are more likely to
12993 write.  They are also used for cache variables, in all-lowercase.  Use
12994 them where applicable; where they're not, invent your own categories.
12996 @table @code
12997 @item C
12998 C language builtin features.
12999 @item DECL
13000 Declarations of C variables in header files.
13001 @item FUNC
13002 Functions in libraries.
13003 @item GROUP
13004 Posix group owners of files.
13005 @item HEADER
13006 Header files.
13007 @item LIB
13008 C libraries.
13009 @item PROG
13010 The base names of programs.
13011 @item MEMBER
13012 Members of aggregates.
13013 @item SYS
13014 Operating system features.
13015 @item TYPE
13016 C builtin or declared types.
13017 @item VAR
13018 C variables in libraries.
13019 @end table
13021 After the category comes the name of the particular feature being
13022 tested.  Any further words in the macro name indicate particular aspects
13023 of the feature.  For example, @code{AC_PROG_CC_STDC} checks whether the
13024 C compiler supports @acronym{ISO} Standard C.
13026 An internal macro should have a name that starts with an underscore;
13027 Autoconf internals should therefore start with @samp{_AC_}.
13028 Additionally, a macro that is an internal subroutine of another macro
13029 should have a name that starts with an underscore and the name of that
13030 other macro, followed by one or more words saying what the internal
13031 macro does.  For example, @code{AC_PATH_X} has internal macros
13032 @code{_AC_PATH_X_XMKMF} and @code{_AC_PATH_X_DIRECT}.
13034 @node Reporting Messages
13035 @section Reporting Messages
13036 @cindex Messages, from @command{autoconf}
13038 When macros statically diagnose abnormal situations, benign or fatal, it
13039 is possible to make @command{autoconf} detect the problem, and refuse to
13040 create @file{configure} in the case of an error.  The macros in this
13041 section are considered obsolescent, and new code should use M4sugar
13042 macros for this purpose, see @ref{Diagnostic Macros}.
13044 On the other hand, it is possible to want to detect errors when
13045 @command{configure} is run, which are dependent on the environment of
13046 the user rather than the maintainer.  For dynamic diagnostics, see
13047 @ref{Printing Messages}.
13049 @defmac AC_DIAGNOSE (@var{category}, @var{message})
13050 @acindex{DIAGNOSE}
13051 Report @var{message} as a warning (or as an error if requested by the
13052 user) if warnings of the @var{category} are turned on.  This macro is
13053 obsolescent; you are encouraged to use:
13054 @example
13055 m4_warn([@var{category}], [@var{message}])
13056 @end example
13057 @noindent
13058 instead.  @xref{m4_warn}, for more details, including valid
13059 @var{category} names.
13060 @end defmac
13062 @defmac AC_WARNING (@var{message})
13063 @acindex{WARNING}
13064 Report @var{message} as a syntax warning.  This macro is obsolescent;
13065 you are encouraged to use:
13066 @example
13067 m4_warn([syntax], [@var{message}])
13068 @end example
13069 @noindent
13070 instead.  @xref{m4_warn}, for more details, as well as better
13071 finer-grained categories of warnings (not all problems have to do with
13072 syntax).
13073 @end defmac
13075 @defmac AC_FATAL (@var{message})
13076 @acindex{FATAL}
13077 Report a severe error @var{message}, and have @command{autoconf} die.
13078 This macro is obsolescent; you are encouraged to use:
13079 @example
13080 m4_fatal([@var{message}])
13081 @end example
13082 @noindent
13083 instead.  @xref{m4_fatal}, for more details.
13084 @end defmac
13086 When the user runs @samp{autoconf -W error}, warnings from
13087 @code{m4_warn} (including those issued through @code{AC_DIAGNOSE} and
13088 @code{AC_WARNING}) are reported as errors, see @ref{autoconf Invocation}.
13090 @node Dependencies Between Macros
13091 @section Dependencies Between Macros
13092 @cindex Dependencies between macros
13094 Some Autoconf macros depend on other macros having been called first in
13095 order to work correctly.  Autoconf provides a way to ensure that certain
13096 macros are called if needed and a way to warn the user if macros are
13097 called in an order that might cause incorrect operation.
13099 @menu
13100 * Prerequisite Macros::         Ensuring required information
13101 * Suggested Ordering::          Warning about possible ordering problems
13102 * One-Shot Macros::             Ensuring a macro is called only once
13103 @end menu
13105 @node Prerequisite Macros
13106 @subsection Prerequisite Macros
13107 @cindex Prerequisite macros
13108 @cindex Macros, prerequisites
13110 A macro that you write might need to use values that have previously
13111 been computed by other macros.  For example, @code{AC_DECL_YYTEXT}
13112 examines the output of @code{flex} or @code{lex}, so it depends on
13113 @code{AC_PROG_LEX} having been called first to set the shell variable
13114 @code{LEX}.
13116 Rather than forcing the user of the macros to keep track of the
13117 dependencies between them, you can use the @code{AC_REQUIRE} macro to do
13118 it automatically.  @code{AC_REQUIRE} can ensure that a macro is only
13119 called if it is needed, and only called once.
13121 @defmac AC_REQUIRE (@var{macro-name})
13122 @acindex{REQUIRE}
13123 If the M4 macro @var{macro-name} has not already been called, call it
13124 (without any arguments).  Make sure to quote @var{macro-name} with
13125 square brackets.  @var{macro-name} must have been defined using
13126 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13127 that it has been called.
13129 @code{AC_REQUIRE} must be used inside a macro defined by @code{AC_DEFUN}; it
13130 must not be called from the top level.  Also, it does not make sense to
13131 require a macro that takes parameters.
13132 @end defmac
13134 @code{AC_REQUIRE} is often misunderstood.  It really implements
13135 dependencies between macros in the sense that if one macro depends upon
13136 another, the latter is expanded @emph{before} the body of the
13137 former.  To be more precise, the required macro is expanded before
13138 the outermost defined macro in the current expansion stack.
13139 In particular, @samp{AC_REQUIRE([FOO])} is not replaced with the body of
13140 @code{FOO}.  For instance, this definition of macros:
13142 @example
13143 @group
13144 AC_DEFUN([TRAVOLTA],
13145 [test "$body_temperature_in_celsius" -gt "38" &&
13146   dance_floor=occupied])
13147 AC_DEFUN([NEWTON_JOHN],
13148 [test "$hair_style" = "curly" &&
13149   dance_floor=occupied])
13150 @end group
13152 @group
13153 AC_DEFUN([RESERVE_DANCE_FLOOR],
13154 [if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13155   AC_REQUIRE([TRAVOLTA])
13156   AC_REQUIRE([NEWTON_JOHN])
13157 fi])
13158 @end group
13159 @end example
13161 @noindent
13162 with this @file{configure.ac}
13164 @example
13165 AC_INIT([Dance Manager], [1.0], [bug-dance@@example.org])
13166 RESERVE_DANCE_FLOOR
13167 if test "$dance_floor" = occupied; then
13168   AC_MSG_ERROR([cannot pick up here, let's move])
13170 @end example
13172 @noindent
13173 does not leave you with a better chance to meet a kindred soul at
13174 other times than Saturday night since it expands into:
13176 @example
13177 @group
13178 test "$body_temperature_in_Celsius" -gt "38" &&
13179   dance_floor=occupied
13180 test "$hair_style" = "curly" &&
13181   dance_floor=occupied
13183 if date | grep '^Sat.*pm' >/dev/null 2>&1; then
13187 @end group
13188 @end example
13190 This behavior was chosen on purpose: (i) it prevents messages in
13191 required macros from interrupting the messages in the requiring macros;
13192 (ii) it avoids bad surprises when shell conditionals are used, as in:
13194 @example
13195 @group
13196 if @dots{}; then
13197   AC_REQUIRE([SOME_CHECK])
13199 @dots{}
13200 SOME_CHECK
13201 @end group
13202 @end example
13204 However, this implementation can lead to another class of problems.
13205 Consider the case where an outer macro first expands, then indirectly
13206 requires, an inner macro:
13208 @example
13209 AC_DEFUN([TESTA], [[echo in A
13210 if test -n "$SEEN_A" ; then echo duplicate ; fi
13211 SEEN_A=:]])
13212 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
13213 if test -z "$SEEN_A" ; then echo bug ; fi]])
13214 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13215 AC_DEFUN([OUTER], [[echo in OUTER]
13218 OUTER
13219 @end example
13221 @noindent
13222 Prior to Autoconf 2.64, the implementation of @code{AC_REQUIRE}
13223 recognized that @code{TESTB} needed to be hoisted prior to the expansion
13224 of @code{OUTER}, but because @code{TESTA} had already been directly
13225 expanded, it failed to hoist @code{TESTA}.  Therefore, the expansion of
13226 @code{TESTB} occurs prior to its prerequisites, leading to the following
13227 output:
13229 @example
13230 in B
13232 in OUTER
13233 in A
13234 in C
13235 @end example
13237 @noindent
13238 Newer Autoconf is smart enough to recognize this situation, and hoists
13239 @code{TESTA} even though it has already been expanded, but issues a
13240 syntax warning in the process.  This is because the hoisted expansion of
13241 @code{TESTA} defeats the purpose of using @code{AC_REQUIRE} to avoid
13242 redundant code, and causes its own set of problems if the hoisted macro
13243 is not idempotent:
13245 @example
13246 in A
13247 in B
13248 in OUTER
13249 in A
13250 duplicate
13251 in C
13252 @end example
13254 The bug is not in Autoconf, but in the macro definitions.  If you ever
13255 pass a particular macro name to @code{AC_REQUIRE}, then you are implying
13256 that the macro only needs to be expanded once.  But to enforce this,
13257 either the macro must be declared with @code{AC_DEFUN_ONCE} (although
13258 this only helps in Autoconf 2.64 or newer), or all
13259 uses of that macro should be through @code{AC_REQUIRE}; directly
13260 expanding the macro defeats the point of using @code{AC_REQUIRE} to
13261 eliminate redundant expansion.  In the example, this rule of thumb was
13262 violated because @code{TESTB} requires @code{TESTA} while @code{OUTER}
13263 directly expands it.  One way of fixing the bug is to factor
13264 @code{TESTA} into two macros, the portion designed for direct and
13265 repeated use (here, named @code{TESTA}), and the portion designed for
13266 one-shot output and used only inside @code{AC_REQUIRE} (here, named
13267 @code{TESTA_PREREQ}).  Then, by fixing all clients to use the correct
13268 calling convention according to their needs:
13270 @example
13271 AC_DEFUN([TESTA], [AC_REQUIRE([TESTA_PREREQ])[echo in A]])
13272 AC_DEFUN([TESTA_PREREQ], [[echo in A_PREREQ
13273 if test -n "$SEEN_A" ; then echo duplicate ; fi
13274 SEEN_A=:]])
13275 AC_DEFUN([TESTB], [AC_REQUIRE([TESTA_PREREQ])[echo in B
13276 if test -z "$SEEN_A" ; then echo bug ; fi]])
13277 AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
13278 AC_DEFUN([OUTER], [[echo in OUTER]
13279 TESTA
13280 TESTC])
13281 OUTER
13282 @end example
13284 @noindent
13285 the resulting output will then obey all dependency rules and avoid any
13286 syntax warnings, whether the script is built with old or new Autoconf
13287 versions:
13289 @example
13290 in A_PREREQ
13291 in B
13292 in OUTER
13293 in A
13294 in C
13295 @end example
13297 The helper macros @code{AS_IF} and @code{AS_CASE} may be used to
13298 enforce expansion of required macros outside of shell conditional
13299 constructs.  You are furthermore encouraged, although not required, to
13300 put all @code{AC_REQUIRE} calls
13301 at the beginning of a macro.  You can use @code{dnl} to avoid the empty
13302 lines they leave.
13304 @node Suggested Ordering
13305 @subsection Suggested Ordering
13306 @cindex Macros, ordering
13307 @cindex Ordering macros
13309 Some macros should be run before another macro if both are called, but
13310 neither @emph{requires} that the other be called.  For example, a macro
13311 that changes the behavior of the C compiler should be called before any
13312 macros that run the C compiler.  Many of these dependencies are noted in
13313 the documentation.
13315 Autoconf provides the @code{AC_BEFORE} macro to warn users when macros
13316 with this kind of dependency appear out of order in a
13317 @file{configure.ac} file.  The warning occurs when creating
13318 @command{configure} from @file{configure.ac}, not when running
13319 @command{configure}.
13321 For example, @code{AC_PROG_CPP} checks whether the C compiler
13322 can run the C preprocessor when given the @option{-E} option.  It should
13323 therefore be called after any macros that change which C compiler is
13324 being used, such as @code{AC_PROG_CC}.  So @code{AC_PROG_CC} contains:
13326 @example
13327 AC_BEFORE([$0], [AC_PROG_CPP])dnl
13328 @end example
13330 @noindent
13331 This warns the user if a call to @code{AC_PROG_CPP} has already occurred
13332 when @code{AC_PROG_CC} is called.
13334 @defmac AC_BEFORE (@var{this-macro-name}, @var{called-macro-name})
13335 @acindex{BEFORE}
13336 Make M4 print a warning message to the standard error output if
13337 @var{called-macro-name} has already been called.  @var{this-macro-name}
13338 should be the name of the macro that is calling @code{AC_BEFORE}.  The
13339 macro @var{called-macro-name} must have been defined using
13340 @code{AC_DEFUN} or else contain a call to @code{AC_PROVIDE} to indicate
13341 that it has been called.
13342 @end defmac
13344 @node One-Shot Macros
13345 @subsection One-Shot Macros
13346 @cindex One-shot macros
13347 @cindex Macros, called once
13349 Some macros should be called only once, either because calling them
13350 multiple time is unsafe, or because it is bad style.  For instance
13351 Autoconf ensures that @code{AC_CANONICAL_BUILD} and cousins
13352 (@pxref{Canonicalizing}) are evaluated only once, because it makes no
13353 sense to run these expensive checks more than once.  Such one-shot
13354 macros can be defined using @code{AC_DEFUN_ONCE}.
13356 @defmac AC_DEFUN_ONCE (@var{macro-name}, @var{macro-body})
13357 @acindex{DEFUN_ONCE}
13358 Declare macro @var{macro-name} like @code{AC_DEFUN} would (@pxref{Macro
13359 Definitions}), but add additional logic that guarantees that only the
13360 first use of the macro (whether by direct expansion or
13361 @code{AC_REQUIRE}) causes an expansion of @var{macro-body}; the
13362 expansion will occur before the start of any enclosing macro defined by
13363 @code{AC_DEFUN}.  Subsequent expansions are silently ignored.
13364 Generally, it does not make sense for @var{macro-body} to use parameters
13365 such as @code{$1}.
13366 @end defmac
13368 Prior to Autoconf 2.64, a macro defined by @code{AC_DEFUN_ONCE} would
13369 emit a warning if it was directly expanded a second time, so for
13370 portability, it is better to use @code{AC_REQUIRE} than direct
13371 invocation of @var{macro-name} inside a macro defined by @code{AC_DEFUN}
13372 (@pxref{Prerequisite Macros}).
13374 @node Obsoleting Macros
13375 @section Obsoleting Macros
13376 @cindex Obsoleting macros
13377 @cindex Macros, obsoleting
13379 Configuration and portability technology has evolved over the years.
13380 Often better ways of solving a particular problem are developed, or
13381 ad-hoc approaches are systematized.  This process has occurred in many
13382 parts of Autoconf.  One result is that some of the macros are now
13383 considered @dfn{obsolete}; they still work, but are no longer considered
13384 the best thing to do, hence they should be replaced with more modern
13385 macros.  Ideally, @command{autoupdate} should replace the old macro calls
13386 with their modern implementation.
13388 Autoconf provides a simple means to obsolete a macro.
13390 @anchor{AU_DEFUN}
13391 @defmac AU_DEFUN (@var{old-macro}, @var{implementation}, @ovar{message})
13392 @auindex{DEFUN}
13393 Define @var{old-macro} as @var{implementation}.  The only difference
13394 with @code{AC_DEFUN} is that the user is warned that
13395 @var{old-macro} is now obsolete.
13397 If she then uses @command{autoupdate}, the call to @var{old-macro} is
13398 replaced by the modern @var{implementation}.  @var{message} should
13399 include information on what to do after running @command{autoupdate};
13400 @command{autoupdate} prints it as a warning, and includes it
13401 in the updated @file{configure.ac} file.
13403 The details of this macro are hairy: if @command{autoconf} encounters an
13404 @code{AU_DEFUN}ed macro, all macros inside its second argument are expanded
13405 as usual.  However, when @command{autoupdate} is run, only M4 and M4sugar
13406 macros are expanded here, while all other macros are disabled and
13407 appear literally in the updated @file{configure.ac}.
13408 @end defmac
13410 @defmac AU_ALIAS (@var{old-name}, @var{new-name})
13411 @auindex{ALIAS}
13412 Used if the @var{old-name} is to be replaced by a call to @var{new-macro}
13413 with the same parameters.  This happens for example if the macro was renamed.
13414 @end defmac
13416 @node Coding Style
13417 @section Coding Style
13418 @cindex Coding style
13420 The Autoconf macros follow a strict coding style.  You are encouraged to
13421 follow this style, especially if you intend to distribute your macro,
13422 either by contributing it to Autoconf itself, or via other means.
13424 The first requirement is to pay great attention to the quotation.  For
13425 more details, see @ref{Autoconf Language}, and @ref{M4 Quotation}.
13427 Do not try to invent new interfaces.  It is likely that there is a macro
13428 in Autoconf that resembles the macro you are defining: try to stick to
13429 this existing interface (order of arguments, default values, etc.).  We
13430 @emph{are} conscious that some of these interfaces are not perfect;
13431 nevertheless, when harmless, homogeneity should be preferred over
13432 creativity.
13434 Be careful about clashes both between M4 symbols and between shell
13435 variables.
13437 If you stick to the suggested M4 naming scheme (@pxref{Macro Names}),
13438 you are unlikely to generate conflicts.  Nevertheless, when you need to
13439 set a special value, @emph{avoid using a regular macro name}; rather,
13440 use an ``impossible'' name.  For instance, up to version 2.13, the macro
13441 @code{AC_SUBST} used to remember what @var{symbol} macros were already defined
13442 by setting @code{AC_SUBST_@var{symbol}}, which is a regular macro name.
13443 But since there is a macro named @code{AC_SUBST_FILE}, it was just
13444 impossible to @samp{AC_SUBST(FILE)}!  In this case,
13445 @code{AC_SUBST(@var{symbol})} or @code{_AC_SUBST(@var{symbol})} should
13446 have been used (yes, with the parentheses).
13447 @c or better yet, high-level macros such as @code{m4_expand_once}
13449 No Autoconf macro should ever enter the user-variable name space; i.e.,
13450 except for the variables that are the actual result of running the
13451 macro, all shell variables should start with @code{ac_}.  In
13452 addition, small macros or any macro that is likely to be embedded in
13453 other macros should be careful not to use obvious names.
13455 @cindex @code{dnl}
13456 Do not use @code{dnl} to introduce comments: most of the comments you
13457 are likely to write are either header comments which are not output
13458 anyway, or comments that should make their way into @file{configure}.
13459 There are exceptional cases where you do want to comment special M4
13460 constructs, in which case @code{dnl} is right, but keep in mind that it
13461 is unlikely.
13463 M4 ignores the leading blanks and newlines before each argument.
13464 Use this feature to
13465 indent in such a way that arguments are (more or less) aligned with the
13466 opening parenthesis of the macro being called.  For instance, instead of
13468 @example
13469 AC_CACHE_CHECK(for EMX OS/2 environment,
13470 ac_cv_emxos2,
13471 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, [return __EMX__;])],
13472 [ac_cv_emxos2=yes], [ac_cv_emxos2=no])])
13473 @end example
13475 @noindent
13476 write
13478 @example
13479 AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
13480 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
13481                    [ac_cv_emxos2=yes],
13482                    [ac_cv_emxos2=no])])
13483 @end example
13485 @noindent
13486 or even
13488 @example
13489 AC_CACHE_CHECK([for EMX OS/2 environment],
13490                [ac_cv_emxos2],
13491                [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
13492                                                    [return __EMX__;])],
13493                                   [ac_cv_emxos2=yes],
13494                                   [ac_cv_emxos2=no])])
13495 @end example
13497 When using @code{AC_RUN_IFELSE} or any macro that cannot work when
13498 cross-compiling, provide a pessimistic value (typically @samp{no}).
13500 Feel free to use various tricks to prevent auxiliary tools, such as
13501 syntax-highlighting editors, from behaving improperly.  For instance,
13502 instead of:
13504 @example
13505 m4_bpatsubst([$1], [$"])
13506 @end example
13508 @noindent
13511 @example
13512 m4_bpatsubst([$1], [$""])
13513 @end example
13515 @noindent
13516 so that Emacsen do not open an endless ``string'' at the first quote.
13517 For the same reasons, avoid:
13519 @example
13520 test $[#] != 0
13521 @end example
13523 @noindent
13524 and use:
13526 @example
13527 test $[@@%:@@] != 0
13528 @end example
13530 @noindent
13531 Otherwise, the closing bracket would be hidden inside a @samp{#}-comment,
13532 breaking the bracket-matching highlighting from Emacsen.  Note the
13533 preferred style to escape from M4: @samp{$[1]}, @samp{$[@@]}, etc.  Do
13534 not escape when it is unnecessary.  Common examples of useless quotation
13535 are @samp{[$]$1} (write @samp{$$1}), @samp{[$]var} (use @samp{$var}),
13536 etc.  If you add portability issues to the picture, you'll prefer
13537 @samp{$@{1+"$[@@]"@}} to @samp{"[$]@@"}, and you'll prefer do something
13538 better than hacking Autoconf @code{:-)}.
13540 When using @command{sed}, don't use @option{-e} except for indenting
13541 purposes.  With the @code{s} and @code{y} commands, the preferred
13542 separator is @samp{/} unless @samp{/} itself might appear in the pattern
13543 or replacement, in which case you should use @samp{|}, or optionally
13544 @samp{,} if you know the pattern and replacement cannot contain a file
13545 name.  If none of these characters will do, choose a printable character
13546 that cannot appear in the pattern or replacement.  Characters from the
13547 set @samp{"#$&'()*;<=>?`|~} are good choices if the pattern or
13548 replacement might contain a file name, since they have special meaning
13549 to the shell and are less likely to occur in file names.
13551 @xref{Macro Definitions}, for details on how to define a macro.  If a
13552 macro doesn't use @code{AC_REQUIRE}, is expected to never be the object
13553 of an @code{AC_REQUIRE} directive, and macros required by other macros
13554 inside arguments do not need to be expanded before this macro, then
13555 use @code{m4_define}.  In case of doubt, use @code{AC_DEFUN}.
13556 All the @code{AC_REQUIRE} statements should be at the beginning of the
13557 macro, and each statement should be followed by @code{dnl}.
13559 You should not rely on the number of arguments: instead of checking
13560 whether an argument is missing, test that it is not empty.  It provides
13561 both a simpler and a more predictable interface to the user, and saves
13562 room for further arguments.
13564 Unless the macro is short, try to leave the closing @samp{])} at the
13565 beginning of a line, followed by a comment that repeats the name of the
13566 macro being defined.  This introduces an additional newline in
13567 @command{configure}; normally, that is not a problem, but if you want to
13568 remove it you can use @samp{[]dnl} on the last line.  You can similarly
13569 use @samp{[]dnl} after a macro call to remove its newline.  @samp{[]dnl}
13570 is recommended instead of @samp{dnl} to ensure that M4 does not
13571 interpret the @samp{dnl} as being attached to the preceding text or
13572 macro output.  For example, instead of:
13574 @example
13575 AC_DEFUN([AC_PATH_X],
13576 [AC_MSG_CHECKING([for X])
13577 AC_REQUIRE_CPP()
13578 @r{# @dots{}omitted@dots{}}
13579   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
13580 fi])
13581 @end example
13583 @noindent
13584 you would write:
13586 @example
13587 AC_DEFUN([AC_PATH_X],
13588 [AC_REQUIRE_CPP()[]dnl
13589 AC_MSG_CHECKING([for X])
13590 @r{# @dots{}omitted@dots{}}
13591   AC_MSG_RESULT([libraries $x_libraries, headers $x_includes])
13592 fi[]dnl
13593 ])# AC_PATH_X
13594 @end example
13596 If the macro is long, try to split it into logical chunks.  Typically,
13597 macros that check for a bug in a function and prepare its
13598 @code{AC_LIBOBJ} replacement should have an auxiliary macro to perform
13599 this setup.  Do not hesitate to introduce auxiliary macros to factor
13600 your code.
13602 In order to highlight the recommended coding style, here is a macro
13603 written the old way:
13605 @example
13606 dnl Check for EMX on OS/2.
13607 dnl _AC_EMXOS2
13608 AC_DEFUN(_AC_EMXOS2,
13609 [AC_CACHE_CHECK(for EMX OS/2 environment, ac_cv_emxos2,
13610 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM(, return __EMX__;)],
13611 ac_cv_emxos2=yes, ac_cv_emxos2=no)])
13612 test "$ac_cv_emxos2" = yes && EMXOS2=yes])
13613 @end example
13615 @noindent
13616 and the new way:
13618 @example
13619 # _AC_EMXOS2
13620 # ----------
13621 # Check for EMX on OS/2.
13622 m4_define([_AC_EMXOS2],
13623 [AC_CACHE_CHECK([for EMX OS/2 environment], [ac_cv_emxos2],
13624 [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [return __EMX__;])],
13625                    [ac_cv_emxos2=yes],
13626                    [ac_cv_emxos2=no])])
13627 test "$ac_cv_emxos2" = yes && EMXOS2=yes[]dnl
13628 ])# _AC_EMXOS2
13629 @end example
13634 @c ============================================= Portable Shell Programming
13636 @node Portable Shell
13637 @chapter Portable Shell Programming
13638 @cindex Portable shell programming
13640 When writing your own checks, there are some shell-script programming
13641 techniques you should avoid in order to make your code portable.  The
13642 Bourne shell and upward-compatible shells like the Korn shell and Bash
13643 have evolved over the years, and many features added to the original
13644 System7 shell are now supported on all interesting porting targets.
13645 However, the following discussion between Russ Allbery and Robert Lipe
13646 is worth reading:
13648 @noindent
13649 Russ Allbery:
13651 @quotation
13652 The @acronym{GNU} assumption that @command{/bin/sh} is the one and only shell
13653 leads to a permanent deadlock.  Vendors don't want to break users'
13654 existing shell scripts, and there are some corner cases in the Bourne
13655 shell that are not completely compatible with a Posix shell.  Thus,
13656 vendors who have taken this route will @emph{never} (OK@dots{}``never say
13657 never'') replace the Bourne shell (as @command{/bin/sh}) with a
13658 Posix shell.
13659 @end quotation
13661 @noindent
13662 Robert Lipe:
13664 @quotation
13665 This is exactly the problem.  While most (at least most System V's) do
13666 have a Bourne shell that accepts shell functions most vendor
13667 @command{/bin/sh} programs are not the Posix shell.
13669 So while most modern systems do have a shell @emph{somewhere} that meets the
13670 Posix standard, the challenge is to find it.
13671 @end quotation
13673 For this reason, part of the job of M4sh (@pxref{Programming in M4sh})
13674 is to find such a shell.  But to prevent trouble, if you're not using
13675 M4sh you should not take advantage of features that were added after Unix
13676 version 7, circa 1977 (@pxref{Systemology}); you should not use aliases,
13677 negated character classes, or even @command{unset}.  @code{#} comments,
13678 while not in Unix version 7, were retrofitted in the original Bourne
13679 shell and can be assumed to be part of the least common denominator.
13681 On the other hand, if you're using M4sh you can assume that the shell
13682 has the features that were added in SVR2 (circa 1984), including shell
13683 functions,
13684 @command{return}, @command{unset}, and I/O redirection for builtins.  For
13685 more information, refer to @uref{http://@/www.in-ulm.de/@/~mascheck/@/bourne/}.
13686 However, some pitfalls have to be avoided for portable use of these
13687 constructs; these will be documented in the rest of this chapter.
13688 See in particular @ref{Shell Functions} and @ref{Limitations of
13689 Builtins, , Limitations of Shell Builtins}.
13691 Some ancient systems have quite
13692 small limits on the length of the @samp{#!} line; for instance, 32
13693 bytes (not including the newline) on SunOS 4.
13694 A few ancient 4.2@acronym{BSD} based systems (such as Dynix circa 1984)
13695 required a single space between the @samp{#!} and the @samp{/}.
13696 However, these ancient systems are no longer of practical concern.
13698 The set of external programs you should run in a @command{configure} script
13699 is fairly small.  @xref{Utilities in Makefiles, , Utilities in
13700 Makefiles, standards, @acronym{GNU} Coding Standards}, for the list.  This
13701 restriction allows users to start out with a fairly small set of
13702 programs and build the rest, avoiding too many interdependencies between
13703 packages.
13705 Some of these external utilities have a portable subset of features; see
13706 @ref{Limitations of Usual Tools}.
13708 There are other sources of documentation about shells.  The
13709 specification for the Posix
13710 @uref{http://@/www.opengroup.org/@/susv3/@/utilities/@/xcu_chap02@/.html, Shell
13711 Command Language}, though more generous than the restrictive shell
13712 subset described above, is fairly portable nowadays.  Also please see
13713 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/, the Shell FAQs}.
13715 @menu
13716 * Shellology::                  A zoology of shells
13717 * Here-Documents::              Quirks and tricks
13718 * File Descriptors::            FDs and redirections
13719 * File System Conventions::     File names
13720 * Shell Pattern Matching::      Pattern matching
13721 * Shell Substitutions::         Variable and command expansions
13722 * Assignments::                 Varying side effects of assignments
13723 * Parentheses::                 Parentheses in shell scripts
13724 * Slashes::                     Slashes in shell scripts
13725 * Special Shell Variables::     Variables you should not change
13726 * Shell Functions::             What to look out for if you use them
13727 * Limitations of Builtins::     Portable use of not so portable /bin/sh
13728 * Limitations of Usual Tools::  Portable use of portable tools
13729 @end menu
13731 @node Shellology
13732 @section Shellology
13733 @cindex Shellology
13735 There are several families of shells, most prominently the Bourne family
13736 and the C shell family which are deeply incompatible.  If you want to
13737 write portable shell scripts, avoid members of the C shell family.  The
13738 @uref{http://@/www.faqs.org/@/faqs/@/unix-faq/@/shell/@/shell-differences/, the
13739 Shell difference FAQ} includes a small history of Posix shells, and a
13740 comparison between several of them.
13742 Below we describe some of the members of the Bourne shell family.
13744 @table @asis
13745 @item Ash
13746 @cindex Ash
13747 Ash is often used on @acronym{GNU}/Linux and @acronym{BSD}
13748 systems as a light-weight Bourne-compatible shell.  Ash 0.2 has some
13749 bugs that are fixed in the 0.3.x series, but portable shell scripts
13750 should work around them, since version 0.2 is still shipped with many
13751 @acronym{GNU}/Linux distributions.
13753 To be compatible with Ash 0.2:
13755 @itemize @minus
13756 @item
13757 don't use @samp{$?} after expanding empty or unset variables,
13758 or at the start of an @command{eval}:
13760 @example
13761 foo=
13762 false
13763 $foo
13764 echo "Do not use it: $?"
13765 false
13766 eval 'echo "Do not use it: $?"'
13767 @end example
13769 @item
13770 don't use command substitution within variable expansion:
13772 @example
13773 cat $@{FOO=`bar`@}
13774 @end example
13776 @item
13777 beware that single builtin substitutions are not performed by a
13778 subshell, hence their effect applies to the current shell!  @xref{Shell
13779 Substitutions}, item ``Command Substitution''.
13780 @end itemize
13782 @item Bash
13783 @cindex Bash
13784 To detect whether you are running Bash, test whether
13785 @code{BASH_VERSION} is set.  To require
13786 Posix compatibility, run @samp{set -o posix}.  @xref{Bash POSIX
13787 Mode, , Bash Posix Mode, bash, The @acronym{GNU} Bash Reference
13788 Manual}, for details.
13790 @item Bash 2.05 and later
13791 @cindex Bash 2.05 and later
13792 Versions 2.05 and later of Bash use a different format for the
13793 output of the @command{set} builtin, designed to make evaluating its
13794 output easier.  However, this output is not compatible with earlier
13795 versions of Bash (or with many other shells, probably).  So if
13796 you use Bash 2.05 or higher to execute @command{configure},
13797 you'll need to use Bash 2.05 for all other build tasks as well.
13799 @item Ksh
13800 @cindex Ksh
13801 @cindex Korn shell
13802 @prindex @samp{ksh}
13803 @prindex @samp{ksh88}
13804 @prindex @samp{ksh93}
13805 The Korn shell is compatible with the Bourne family and it mostly
13806 conforms to Posix.  It has two major variants commonly
13807 called @samp{ksh88} and @samp{ksh93}, named after the years of initial
13808 release.  It is usually called @command{ksh}, but is called @command{sh}
13809 on some hosts if you set your path appropriately.
13811 Solaris systems have three variants:
13812 @prindex @command{/usr/bin/ksh} on Solaris
13813 @command{/usr/bin/ksh} is @samp{ksh88}; it is
13814 standard on Solaris 2.0 and later.
13815 @prindex @command{/usr/xpg4/bin/sh} on Solaris
13816 @command{/usr/xpg4/bin/sh} is a Posix-compliant variant of
13817 @samp{ksh88}; it is standard on Solaris 9 and later.
13818 @prindex @command{/usr/dt/bin/dtksh} on Solaris
13819 @command{/usr/dt/bin/dtksh} is @samp{ksh93}.
13820 Variants that are not standard may be parts of optional
13821 packages.  There is no extra charge for these packages, but they are
13822 not part of a minimal OS install and therefore some installations may
13823 not have it.
13825 Starting with Tru64 Version 4.0, the Korn shell @command{/usr/bin/ksh}
13826 is also available as @command{/usr/bin/posix/sh}.  If the environment
13827 variable @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
13828 the standard shell conform to Posix.
13830 @item Pdksh
13831 @prindex @samp{pdksh}
13832 A public-domain clone of the Korn shell called @command{pdksh} is widely
13833 available: it has most of the @samp{ksh88} features along with a few of
13834 its own.  It usually sets @code{KSH_VERSION}, except if invoked as
13835 @command{/bin/sh} on Open@acronym{BSD}, and similarly to Bash you can require
13836 Posix compatibility by running @samp{set -o posix}.  Unfortunately, with
13837 @command{pdksh} 5.2.14 (the latest stable version as of January 2007)
13838 Posix mode is buggy and causes @command{pdksh} to depart from Posix in
13839 at least one respect:
13841 @example
13842 $ @kbd{echo "`echo \"hello\"`"}
13843 hello
13844 $ @kbd{set -o posix}
13845 $ @kbd{echo "`echo \"hello\"`"}
13846 "hello"
13847 @end example
13849 The last line of output contains spurious quotes.  This is yet another
13850 reason why portable shell code should not contain
13851 @code{"`@dots{}\"@dots{}\"@dots{}`"} constructs (@pxref{Shell
13852 Substitutions}).
13854 @item Zsh
13855 @cindex Zsh
13856 To detect whether you are running @command{zsh}, test whether
13857 @code{ZSH_VERSION} is set.  By default @command{zsh} is @emph{not}
13858 compatible with the Bourne shell: you must execute @samp{emulate sh},
13859 and for @command{zsh} versions before 3.1.6-dev-18 you must also
13860 set @code{NULLCMD} to @samp{:}.  @xref{Compatibility, , Compatibility,
13861 zsh, The Z Shell Manual}, for details.
13863 The default Mac OS X @command{sh} was originally Zsh; it was changed to
13864 Bash in Mac OS X 10.2.
13865 @end table
13867 @node Here-Documents
13868 @section Here-Documents
13869 @cindex Here-documents
13870 @cindex Shell here-documents
13872 Don't rely on @samp{\} being preserved just because it has no special
13873 meaning together with the next symbol.  In the native @command{sh}
13874 on Open@acronym{BSD} 2.7 @samp{\"} expands to @samp{"} in here-documents with
13875 unquoted delimiter.  As a general rule, if @samp{\\} expands to @samp{\}
13876 use @samp{\\} to get @samp{\}.
13878 With Open@acronym{BSD} 2.7's @command{sh}
13880 @example
13881 @group
13882 $ @kbd{cat <<EOF
13883 > \" \\
13884 > EOF}
13885 " \
13886 @end group
13887 @end example
13889 @noindent
13890 and with Bash:
13892 @example
13893 @group
13894 bash-2.04$ @kbd{cat <<EOF
13895 > \" \\
13896 > EOF}
13897 \" \
13898 @end group
13899 @end example
13901 Some shells mishandle large here-documents: for example,
13902 Solaris 10 @command{dtksh} and the UnixWare 7.1.1 Posix shell, which are
13903 derived from Korn shell version M-12/28/93d, mishandle braced variable
13904 expansion that crosses a 1024- or 4096-byte buffer boundary
13905 within a here-document.  Only the part of the variable name after the boundary
13906 is used.  For example, @code{$@{variable@}} could be replaced by the expansion
13907 of @code{$@{ble@}}.  If the end of the variable name is aligned with the block
13908 boundary, the shell reports an error, as if you used @code{$@{@}}.
13909 Instead of @code{$@{variable-default@}}, the shell may expand
13910 @code{$@{riable-default@}}, or even @code{$@{fault@}}.  This bug can often
13911 be worked around by omitting the braces: @code{$variable}.  The bug was
13912 fixed in
13913 @samp{ksh93g} (1998-04-30) but as of 2006 many operating systems were
13914 still shipping older versions with the bug.
13916 Many shells (including the Bourne shell) implement here-documents
13917 inefficiently.  In particular, some shells can be extremely inefficient when
13918 a single statement contains many here-documents.  For instance if your
13919 @file{configure.ac} includes something like:
13921 @example
13922 @group
13923 if <cross_compiling>; then
13924   assume this and that
13925 else
13926   check this
13927   check that
13928   check something else
13929   @dots{}
13930   on and on forever
13931   @dots{}
13933 @end group
13934 @end example
13936 A shell parses the whole @code{if}/@code{fi} construct, creating
13937 temporary files for each here-document in it.  Some shells create links
13938 for such here-documents on every @code{fork}, so that the clean-up code
13939 they had installed correctly removes them.  It is creating the links
13940 that can take the shell forever.
13942 Moving the tests out of the @code{if}/@code{fi}, or creating multiple
13943 @code{if}/@code{fi} constructs, would improve the performance
13944 significantly.  Anyway, this kind of construct is not exactly the
13945 typical use of Autoconf.  In fact, it's even not recommended, because M4
13946 macros can't look into shell conditionals, so we may fail to expand a
13947 macro when it was expanded before in a conditional path, and the
13948 condition turned out to be false at runtime, and we end up not
13949 executing the macro at all.
13951 @node File Descriptors
13952 @section File Descriptors
13953 @cindex Descriptors
13954 @cindex File descriptors
13955 @cindex Shell file descriptors
13957 Most shells, if not all (including Bash, Zsh, Ash), output traces on
13958 stderr, even for subshells.  This might result in undesirable content
13959 if you meant to capture the standard-error output of the inner command:
13961 @example
13962 $ @kbd{ash -x -c '(eval "echo foo >&2") 2>stderr'}
13963 $ @kbd{cat stderr}
13964 + eval echo foo >&2
13965 + echo foo
13967 $ @kbd{bash -x -c '(eval "echo foo >&2") 2>stderr'}
13968 $ @kbd{cat stderr}
13969 + eval 'echo foo >&2'
13970 ++ echo foo
13972 $ @kbd{zsh -x -c '(eval "echo foo >&2") 2>stderr'}
13973 @i{# Traces on startup files deleted here.}
13974 $ @kbd{cat stderr}
13975 +zsh:1> eval echo foo >&2
13976 +zsh:1> echo foo
13978 @end example
13980 @noindent
13981 One workaround is to grep out uninteresting lines, hoping not to remove
13982 good ones.
13984 If you intend to redirect both standard error and standard output,
13985 redirect standard output first.  This works better with @acronym{HP-UX},
13986 since its shell mishandles tracing if standard error is redirected
13987 first:
13989 @example
13990 $ @kbd{sh -x -c ': 2>err >out'}
13991 + :
13992 + 2> err $ @kbd{cat err}
13993 1> out
13994 @end example
13996 Don't try to redirect the standard error of a command substitution.  It
13997 must be done @emph{inside} the command substitution.  When running
13998 @samp{: `cd /zorglub` 2>/dev/null} expect the error message to
13999 escape, while @samp{: `cd /zorglub 2>/dev/null`} works properly.
14001 It is worth noting that Zsh (but not Ash nor Bash) makes it possible
14002 in assignments though: @samp{foo=`cd /zorglub` 2>/dev/null}.
14004 When catering to old systems, don't redirect the same file descriptor
14005 several times, as you are doomed to failure under Ultrix.
14007 @example
14008 ULTRIX V4.4 (Rev. 69) System #31: Thu Aug 10 19:42:23 GMT 1995
14009 UWS V4.4 (Rev. 11)
14010 $ @kbd{eval 'echo matter >fullness' >void}
14011 illegal io
14012 $ @kbd{eval '(echo matter >fullness)' >void}
14013 illegal io
14014 $ @kbd{(eval '(echo matter >fullness)') >void}
14015 Ambiguous output redirect.
14016 @end example
14018 @noindent
14019 In each case the expected result is of course @file{fullness} containing
14020 @samp{matter} and @file{void} being empty.  However, this bug is
14021 probably not of practical concern to modern platforms.
14023 Solaris 10 @command{sh} will try to optimize away a @command{:} command
14024 in a loop after the first iteration, even if it is redirected:
14026 @example
14027 $ @kbd{for i in 1 2 3 ; do : >x$i; done}
14028 $ @kbd{ls}
14030 @end example
14032 @noindent
14033 As a workaround, @command{echo} or @command{eval} can be used.
14035 Don't rely on file descriptors 0, 1, and 2 remaining closed in a
14036 subsidiary program.  If any of these descriptors is closed, the
14037 operating system may open an unspecified file for the descriptor in the
14038 new process image.  Posix says this may be done only if the subsidiary
14039 program is set-user-ID or set-group-ID, but @acronym{HP-UX} 11.23 does
14040 it even for ordinary programs.
14042 Don't rely on open file descriptors being open in child processes.  In
14043 @command{ksh}, file descriptors above 2 which are opened using
14044 @samp{exec @var{n}>file} are closed by a subsequent @samp{exec} (such as
14045 that involved in the fork-and-exec which runs a program or script).
14046 Thus, using @command{sh}, we have:
14048 @example
14049 $ @kbd{cat ./descrips}
14050 #!/bin/sh -
14051 echo hello >&5
14052 $ @kbd{exec 5>t}
14053 $ @kbd{./descrips}
14054 $ @kbd{cat t}
14055 hello
14057 @end example
14059 @noindent
14060 But using ksh:
14062 @example
14063 $ @kbd{exec 5>t}
14064 $ @kbd{./descrips}
14065 hello
14066 $ @kbd{cat t}
14068 @end example
14070 @noindent
14071 Within the process which runs the @samp{descrips} script, file
14072 descriptor 5 is closed.
14074 Don't rely on redirection to a closed file descriptor to cause an
14075 error.  With Solaris @command{/bin/sh}, when the redirection fails, the
14076 output goes to the original file descriptor.
14078 @example
14079 $ @kbd{bash -c 'echo hi >&3' 3>&-; echo $?}
14080 bash: 3: Bad file descriptor
14082 $ @kbd{/bin/sh -c 'echo hi >&3' 3>&-; echo $?}
14085 @end example
14087 @acronym{DOS} variants cannot rename or remove open files, such as in
14088 @samp{mv foo bar >foo} or @samp{rm foo >foo}, even though this is
14089 perfectly portable among Posix hosts.
14091 A few ancient systems reserved some file descriptors.  By convention,
14092 file descriptor 3 was opened to @file{/dev/tty} when you logged into
14093 Eighth Edition (1985) through Tenth Edition Unix (1989).  File
14094 descriptor 4 had a special use on the Stardent/Kubota Titan (circa
14095 1990), though we don't now remember what it was.  Both these systems are
14096 obsolete, so it's now safe to treat file descriptors 3 and 4 like any
14097 other file descriptors.
14099 @node File System Conventions
14100 @section File System Conventions
14101 @cindex File system conventions
14103 Autoconf uses shell-script processing extensively, so the file names
14104 that it processes should not contain characters that are special to the
14105 shell.  Special characters include space, tab, newline, @sc{nul}, and
14106 the following:
14108 @example
14109 " # $ & ' ( ) * ; < = > ? [ \ ` |
14110 @end example
14112 Also, file names should not begin with @samp{~} or @samp{-}, and should
14113 contain neither @samp{-} immediately after @samp{/} nor @samp{~}
14114 immediately after @samp{:}.  On Posix-like platforms, directory names
14115 should not contain @samp{:}, as this runs afoul of @samp{:} used as the
14116 path separator.
14118 These restrictions apply not only to the files that you distribute, but
14119 also to the absolute file names of your source, build, and destination
14120 directories.
14122 On some Posix-like platforms, @samp{!} and @samp{^} are special too, so
14123 they should be avoided.
14125 Posix lets implementations treat leading @file{//} specially, but
14126 requires leading @file{///} and beyond to be equivalent to @file{/}.
14127 Most Unix variants treat @file{//} like @file{/}.  However, some treat
14128 @file{//} as a ``super-root'' that can provide access to files that are
14129 not otherwise reachable from @file{/}.  The super-root tradition began
14130 with Apollo Domain/OS, which died out long ago, but unfortunately Cygwin
14131 has revived it.
14133 While @command{autoconf} and friends are usually run on some Posix
14134 variety, they can be used on other systems, most notably @acronym{DOS}
14135 variants.  This impacts several assumptions regarding file names.
14137 @noindent
14138 For example, the following code:
14140 @example
14141 case $foo_dir in
14142   /*) # Absolute
14143      ;;
14144   *)
14145      foo_dir=$dots$foo_dir ;;
14146 esac
14147 @end example
14149 @noindent
14150 fails to properly detect absolute file names on those systems, because
14151 they can use a drivespec, and usually use a backslash as directory
14152 separator.  If you want to be portable to @acronym{DOS} variants (at the
14153 price of rejecting valid but oddball Posix file names like @file{a:\b}),
14154 you can check for absolute file names like this:
14156 @cindex absolute file names, detect
14157 @example
14158 case $foo_dir in
14159   [\\/]* | ?:[\\/]* ) # Absolute
14160      ;;
14161   *)
14162      foo_dir=$dots$foo_dir ;;
14163 esac
14164 @end example
14166 @noindent
14167 Make sure you quote the brackets if appropriate and keep the backslash as
14168 first character (@pxref{case, , Limitations of Shell Builtins}).
14170 Also, because the colon is used as part of a drivespec, these systems don't
14171 use it as path separator.  When creating or accessing paths, you can use the
14172 @code{PATH_SEPARATOR} output variable instead.  @command{configure} sets this
14173 to the appropriate value for the build system (@samp{:} or @samp{;}) when it
14174 starts up.
14176 File names need extra care as well.  While @acronym{DOS} variants
14177 that are Posixy enough to run @command{autoconf} (such as @acronym{DJGPP})
14178 are usually able to handle long file names properly, there are still
14179 limitations that can seriously break packages.  Several of these issues
14180 can be easily detected by the
14181 @uref{ftp://@/ftp.gnu.org/@/gnu/@/non-gnu/@/doschk/@/doschk-1.1.tar.gz, doschk}
14182 package.
14184 A short overview follows; problems are marked with @sc{sfn}/@sc{lfn} to
14185 indicate where they apply: @sc{sfn} means the issues are only relevant to
14186 plain @acronym{DOS}, not to @acronym{DOS} under Microsoft Windows
14187 variants, while @sc{lfn} identifies problems that exist even under
14188 Microsoft Windows variants.
14190 @table @asis
14191 @item No multiple dots (@sc{sfn})
14192 @acronym{DOS} cannot handle multiple dots in file names.  This is an especially
14193 important thing to remember when building a portable configure script,
14194 as @command{autoconf} uses a .in suffix for template files.
14196 This is perfectly OK on Posix variants:
14198 @example
14199 AC_CONFIG_HEADERS([config.h])
14200 AC_CONFIG_FILES([source.c foo.bar])
14201 AC_OUTPUT
14202 @end example
14204 @noindent
14205 but it causes problems on @acronym{DOS}, as it requires @samp{config.h.in},
14206 @samp{source.c.in} and @samp{foo.bar.in}.  To make your package more portable
14207 to @acronym{DOS}-based environments, you should use this instead:
14209 @example
14210 AC_CONFIG_HEADERS([config.h:config.hin])
14211 AC_CONFIG_FILES([source.c:source.cin foo.bar:foobar.in])
14212 AC_OUTPUT
14213 @end example
14215 @item No leading dot (@sc{sfn})
14216 @acronym{DOS} cannot handle file names that start with a dot.  This is usually
14217 not important for @command{autoconf}.
14219 @item Case insensitivity (@sc{lfn})
14220 @acronym{DOS} is case insensitive, so you cannot, for example, have both a
14221 file called @samp{INSTALL} and a directory called @samp{install}.  This
14222 also affects @command{make}; if there's a file called @samp{INSTALL} in
14223 the directory, @samp{make install} does nothing (unless the
14224 @samp{install} target is marked as PHONY).
14226 @item The 8+3 limit (@sc{sfn})
14227 Because the @acronym{DOS} file system only stores the first 8 characters of
14228 the file name and the first 3 of the extension, those must be unique.
14229 That means that @file{foobar-part1.c}, @file{foobar-part2.c} and
14230 @file{foobar-prettybird.c} all resolve to the same file name
14231 (@file{FOOBAR-P.C}).  The same goes for @file{foo.bar} and
14232 @file{foo.bartender}.
14234 The 8+3 limit is not usually a problem under Microsoft Windows, as it
14235 uses numeric
14236 tails in the short version of file names to make them unique.  However, a
14237 registry setting can turn this behavior off.  While this makes it
14238 possible to share file trees containing long file names between @sc{sfn}
14239 and @sc{lfn} environments, it also means the above problem applies there
14240 as well.
14242 @item Invalid characters (@sc{lfn})
14243 Some characters are invalid in @acronym{DOS} file names, and should therefore
14244 be avoided.  In a @sc{lfn} environment, these are @samp{/}, @samp{\},
14245 @samp{?}, @samp{*}, @samp{:}, @samp{<}, @samp{>}, @samp{|} and @samp{"}.
14246 In a @sc{sfn} environment, other characters are also invalid.  These
14247 include @samp{+}, @samp{,}, @samp{[} and @samp{]}.
14249 @item Invalid names (@sc{lfn})
14250 Some @acronym{DOS} file names are reserved, and cause problems if you
14251 try to use files with those names.  These names include @file{CON},
14252 @file{AUX}, @file{COM1}, @file{COM2}, @file{COM3}, @file{COM4},
14253 @file{LPT1}, @file{LPT2}, @file{LPT3}, @file{NUL}, and @file{PRN}.
14254 File names are case insensitive, so even names like
14255 @file{aux/config.guess} are disallowed.
14257 @end table
14259 @node Shell Pattern Matching
14260 @section Shell Pattern Matching
14261 @cindex Shell pattern matching
14263 Nowadays portable patterns can use negated character classes like
14264 @samp{[!-aeiou]}.  The older syntax @samp{[^-aeiou]} is supported by
14265 some shells but not others; hence portable scripts should never use
14266 @samp{^} as the first character of a bracket pattern.
14268 Outside the C locale, patterns like @samp{[a-z]} are problematic since
14269 they may match characters that are not lower-case letters.
14271 @node Shell Substitutions
14272 @section Shell Substitutions
14273 @cindex Shell substitutions
14275 Contrary to a persistent urban legend, the Bourne shell does not
14276 systematically split variables and back-quoted expressions, in particular
14277 on the right-hand side of assignments and in the argument of @code{case}.
14278 For instance, the following code:
14280 @example
14281 case "$given_srcdir" in
14282 .)  top_srcdir="`echo "$dots" | sed 's|/$||'`" ;;
14283 *)  top_srcdir="$dots$given_srcdir" ;;
14284 esac
14285 @end example
14287 @noindent
14288 is more readable when written as:
14290 @example
14291 case $given_srcdir in
14292 .)  top_srcdir=`echo "$dots" | sed 's|/$||'` ;;
14293 *)  top_srcdir=$dots$given_srcdir ;;
14294 esac
14295 @end example
14297 @noindent
14298 and in fact it is even @emph{more} portable: in the first case of the
14299 first attempt, the computation of @code{top_srcdir} is not portable,
14300 since not all shells properly understand @code{"`@dots{}"@dots{}"@dots{}`"}.
14301 Worse yet, not all shells understand @code{"`@dots{}\"@dots{}\"@dots{}`"}
14302 the same way.  There is just no portable way to use double-quoted
14303 strings inside double-quoted back-quoted expressions (pfew!).
14305 @table @code
14306 @item $@@
14307 @cindex @samp{"$@@"}
14308 One of the most famous shell-portability issues is related to
14309 @samp{"$@@"}.  When there are no positional arguments, Posix says
14310 that @samp{"$@@"} is supposed to be equivalent to nothing, but the
14311 original Unix version 7 Bourne shell treated it as equivalent to
14312 @samp{""} instead, and this behavior survives in later implementations
14313 like Digital Unix 5.0.
14315 The traditional way to work around this portability problem is to use
14316 @samp{$@{1+"$@@"@}}.  Unfortunately this method does not work with
14317 Zsh (3.x and 4.x), which is used on Mac OS X@.  When emulating
14318 the Bourne shell, Zsh performs word splitting on @samp{$@{1+"$@@"@}}:
14320 @example
14321 zsh $ @kbd{emulate sh}
14322 zsh $ @kbd{for i in "$@@"; do echo $i; done}
14323 Hello World
14325 zsh $ @kbd{for i in $@{1+"$@@"@}; do echo $i; done}
14326 Hello
14327 World
14329 @end example
14331 @noindent
14332 Zsh handles plain @samp{"$@@"} properly, but we can't use plain
14333 @samp{"$@@"} because of the portability problems mentioned above.
14334 One workaround relies on Zsh's ``global aliases'' to convert
14335 @samp{$@{1+"$@@"@}} into @samp{"$@@"} by itself:
14337 @example
14338 test "$@{ZSH_VERSION+set@}" = set && alias -g '$@{1+"$@@"@}'='"$@@"'
14339 @end example
14341 Zsh only recognizes this alias when a shell word matches it exactly;
14342 @samp{"foo"$@{1+"$@@"@}} remains subject to word splitting.  Since this
14343 case always yields at least one shell word, use plain @samp{"$@@"}.
14345 A more conservative workaround is to avoid @samp{"$@@"} if it is
14346 possible that there may be no positional arguments.  For example,
14347 instead of:
14349 @example
14350 cat conftest.c "$@@"
14351 @end example
14353 you can use this instead:
14355 @example
14356 case $# in
14357 0) cat conftest.c;;
14358 *) cat conftest.c "$@@";;
14359 esac
14360 @end example
14362 Autoconf macros often use the @command{set} command to update
14363 @samp{$@@}, so if you are writing shell code intended for
14364 @command{configure} you should not assume that the value of @samp{$@@}
14365 persists for any length of time.
14368 @item $@{10@}
14369 @cindex positional parameters
14370 The 10th, 11th, @dots{} positional parameters can be accessed only after
14371 a @code{shift}.  The 7th Edition shell reported an error if given
14372 @code{$@{10@}}, and
14373 Solaris 10 @command{/bin/sh} still acts that way:
14375 @example
14376 $ @kbd{set 1 2 3 4 5 6 7 8 9 10}
14377 $ @kbd{echo $@{10@}}
14378 bad substitution
14379 @end example
14381 @item $@{@var{var}:-@var{value}@}
14382 @c Info cannot handle `:' in index entries.
14383 @c @cindex $@{@var{var}:-@var{value}@}
14384 Old @acronym{BSD} shells, including the Ultrix @code{sh}, don't accept the
14385 colon for any shell substitution, and complain and die.
14386 Similarly for $@{@var{var}:=@var{value}@}, $@{@var{var}:?@var{value}@}, etc.
14388 @item $@{@var{var}=@var{literal}@}
14389 @cindex $@{@var{var}=@var{literal}@}
14390 Be sure to quote:
14392 @example
14393 : $@{var='Some words'@}
14394 @end example
14396 @noindent
14397 otherwise some shells, such as on Digital Unix V 5.0, die because
14398 of a ``bad substitution''.
14400 @sp 1
14402 Solaris @command{/bin/sh} has a frightening bug in its interpretation
14403 of this.  Imagine you need set a variable to a string containing
14404 @samp{@}}.  This @samp{@}} character confuses Solaris @command{/bin/sh}
14405 when the affected variable was already set.  This bug can be exercised
14406 by running:
14408 @example
14409 $ @kbd{unset foo}
14410 $ @kbd{foo=$@{foo='@}'@}}
14411 $ @kbd{echo $foo}
14413 $ @kbd{foo=$@{foo='@}'   # no error; this hints to what the bug is}
14414 $ @kbd{echo $foo}
14416 $ @kbd{foo=$@{foo='@}'@}}
14417 $ @kbd{echo $foo}
14418 @}@}
14419  ^ ugh!
14420 @end example
14422 It seems that @samp{@}} is interpreted as matching @samp{$@{}, even
14423 though it is enclosed in single quotes.  The problem doesn't happen
14424 using double quotes.
14426 @item $@{@var{var}=@var{expanded-value}@}
14427 @cindex $@{@var{var}=@var{expanded-value}@}
14428 On Ultrix,
14429 running
14431 @example
14432 default="yu,yaa"
14433 : $@{var="$default"@}
14434 @end example
14436 @noindent
14437 sets @var{var} to @samp{M-yM-uM-,M-yM-aM-a}, i.e., the 8th bit of
14438 each char is set.  You don't observe the phenomenon using a simple
14439 @samp{echo $var} since apparently the shell resets the 8th bit when it
14440 expands $var.  Here are two means to make this shell confess its sins:
14442 @example
14443 $ @kbd{cat -v <<EOF
14444 $var
14445 EOF}
14446 @end example
14448 @noindent
14451 @example
14452 $ @kbd{set | grep '^var=' | cat -v}
14453 @end example
14455 One classic incarnation of this bug is:
14457 @example
14458 default="a b c"
14459 : $@{list="$default"@}
14460 for c in $list; do
14461   echo $c
14462 done
14463 @end example
14465 @noindent
14466 You'll get @samp{a b c} on a single line.  Why?  Because there are no
14467 spaces in @samp{$list}: there are @samp{M- }, i.e., spaces with the 8th
14468 bit set, hence no IFS splitting is performed!!!
14470 One piece of good news is that Ultrix works fine with @samp{:
14471 $@{list=$default@}}; i.e., if you @emph{don't} quote.  The bad news is
14472 then that @acronym{QNX} 4.25 then sets @var{list} to the @emph{last} item of
14473 @var{default}!
14475 The portable way out consists in using a double assignment, to switch
14476 the 8th bit twice on Ultrix:
14478 @example
14479 list=$@{list="$default"@}
14480 @end example
14482 @noindent
14483 @dots{}but beware of the @samp{@}} bug from Solaris (see above).  For safety,
14484 use:
14486 @example
14487 test "$@{var+set@}" = set || var=@var{@{value@}}
14488 @end example
14490 @item $@{#@var{var}@}
14491 @itemx $@{@var{var}%@var{word}@}
14492 @itemx $@{@var{var}%%@var{word}@}
14493 @itemx $@{@var{var}#@var{word}@}
14494 @itemx $@{@var{var}##@var{word}@}
14495 @cindex $@{#@var{var}@}
14496 @cindex $@{@var{var}%@var{word}@}
14497 @cindex $@{@var{var}%%@var{word}@}
14498 @cindex $@{@var{var}#@var{word}@}
14499 @cindex $@{@var{var}##@var{word}@}
14500 Posix requires support for these usages, but they do not work with many
14501 traditional shells, e.g., Solaris 10 @command{/bin/sh}.
14503 Also, @command{pdksh} 5.2.14 mishandles some @var{word} forms.  For
14504 example if @samp{$1} is @samp{a/b} and @samp{$2} is @samp{a}, then
14505 @samp{$@{1#$2@}} should yield @samp{/b}, but with @command{pdksh} it
14506 yields the empty string.
14509 @item `@var{commands}`
14510 @cindex `@var{commands}`
14511 @cindex Command Substitution
14512 Posix requires shells to trim all trailing newlines from command
14513 output before substituting it, so assignments like
14514 @samp{dir=`echo "$file" | tr a A`} do not work as expected if
14515 @samp{$file} ends in a newline.
14517 While in general it makes no sense, do not substitute a single builtin
14518 with side effects, because Ash 0.2, trying to optimize, does not fork a
14519 subshell to perform the command.
14521 For instance, if you wanted to check that @command{cd} is silent, do not
14522 use @samp{test -z "`cd /`"} because the following can happen:
14524 @example
14525 $ @kbd{pwd}
14526 /tmp
14527 $ @kbd{test -z "`cd /`" && pwd}
14529 @end example
14531 @noindent
14532 The result of @samp{foo=`exit 1`} is left as an exercise to the reader.
14534 The MSYS shell leaves a stray byte in the expansion of a double-quoted
14535 command substitution of a native program, if the end of the substitution
14536 is not aligned with the end of the double quote.  This may be worked
14537 around by inserting another pair of quotes:
14539 @example
14540 $ @kbd{echo "`printf 'foo\r\n'` bar" > broken}
14541 $ @kbd{echo "`printf 'foo\r\n'`"" bar" | cmp - broken}
14542 - broken differ: char 4, line 1
14543 @end example
14545 Upon interrupt or SIGTERM, some shells may abort a command substitution,
14546 replace it with a null string, and wrongly evaluate the enclosing
14547 command before entering the trap or ending the script.  This can lead to
14548 spurious errors:
14550 @example
14551 $ @kbd{sh -c 'if test `sleep 5; echo hi` = hi; then echo yes; fi'}
14552 $ @kbd{^C}
14553 sh: test: hi: unexpected operator/operand
14554 @end example
14556 @noindent
14557 You can avoid this by assigning the command substitution to a temporary
14558 variable:
14560 @example
14561 $ @kbd{sh -c 'res=`sleep 5; echo hi`
14562          if test "x$res" = xhi; then echo yes; fi'}
14563 $ @kbd{^C}
14564 @end example
14566 @item $(@var{commands})
14567 @cindex $(@var{commands})
14568 This construct is meant to replace @samp{`@var{commands}`},
14569 and it has most of the problems listed under @code{`@var{commands}`}.
14571 This construct can be
14572 nested while this is impossible to do portably with back quotes.
14573 Unfortunately it is not yet universally supported.  Most notably, even recent
14574 releases of Solaris don't support it:
14576 @example
14577 $ @kbd{showrev -c /bin/sh | grep version}
14578 Command version: SunOS 5.10 Generic 121005-03 Oct 2006
14579 $ @kbd{echo $(echo blah)}
14580 syntax error: `(' unexpected
14581 @end example
14583 @noindent
14584 nor does @sc{irix} 6.5's Bourne shell:
14585 @example
14586 $ @kbd{uname -a}
14587 IRIX firebird-image 6.5 07151432 IP22
14588 $ @kbd{echo $(echo blah)}
14589 $(echo blah)
14590 @end example
14592 If you do use @samp{$(@var{commands})}, make sure that the commands
14593 do not start with a parenthesis, as that would cause confusion with
14594 a different notation @samp{$((@var{expression}))} that in modern
14595 shells is an arithmetic expression not a command.  To avoid the
14596 confusion, insert a space between the two opening parentheses.
14598 Avoid @var{commands} that contain unbalanced parentheses in
14599 here-documents, comments, or case statement patterns, as many shells
14600 mishandle them.  For example, Bash 3.1, @samp{ksh88}, @command{pdksh}
14601 5.2.14, and Zsh 4.2.6 all mishandle the following valid command:
14603 @example
14604 echo $(case x in x) echo hello;; esac)
14605 @end example
14608 @item $((@var{expression}))
14609 @cindex $((@var{expression}))
14610 Arithmetic expansion is not portable as some shells (most
14611 notably Solaris 10 @command{/bin/sh}) don't support it.
14613 Among shells that do support @samp{$(( ))}, not all of them obey the
14614 Posix rule that octal and hexadecimal constants must be recognized:
14616 @example
14617 $ @kbd{bash -c 'echo $(( 010 + 0x10 ))'}
14619 $ @kbd{zsh -c 'echo $(( 010 + 0x10 ))'}
14621 $ @kbd{zsh -c 'emulate sh; echo $(( 010 + 0x10 ))'}
14623 $ @kbd{pdksh -c 'echo $(( 010 + 0x10 ))'}
14624 pdksh:  010 + 0x10 : bad number `0x10'
14625 $ @kbd{pdksh -c 'echo $(( 010 ))'}
14627 @end example
14629 When it is available, using arithmetic expansion provides a noticeable
14630 speedup in script execution; but testing for support requires
14631 @command{eval} to avoid syntax errors.  The following construct is used
14632 by @code{AS_VAR_ARITH} to provide arithmetic computation when all
14633 arguments are provided in decimal and without a leading zero, and all
14634 operators are properly quoted and appear as distinct arguments:
14636 @example
14637 if ( eval 'test $(( 1 + 1 )) = 2' ) 2>/dev/null; then
14638   eval 'func_arith ()
14639   @{
14640     func_arith_result=$(( $* ))
14641   @}'
14642 else
14643   func_arith ()
14644   @{
14645     func_arith_result=`expr "$@@"`
14646   @}
14648 func_arith 1 + 1
14649 foo=$func_arith_result
14650 @end example
14653 @item ^
14654 @cindex ^ quoting
14655 Always quote @samp{^}, otherwise traditional shells such as
14656 @command{/bin/sh} on Solaris 10 treat this like @samp{|}.
14658 @end table
14661 @node Assignments
14662 @section Assignments
14663 @cindex Shell assignments
14665 When setting several variables in a row, be aware that the order of the
14666 evaluation is undefined.  For instance @samp{foo=1 foo=2; echo $foo}
14667 gives @samp{1} with Solaris @command{/bin/sh}, but @samp{2} with Bash.
14668 You must use
14669 @samp{;} to enforce the order: @samp{foo=1; foo=2; echo $foo}.
14671 Don't rely on the following to find @file{subdir/program}:
14673 @example
14674 PATH=subdir$PATH_SEPARATOR$PATH program
14675 @end example
14677 @noindent
14678 as this does not work with Zsh 3.0.6.  Use something like this
14679 instead:
14681 @example
14682 (PATH=subdir$PATH_SEPARATOR$PATH; export PATH; exec program)
14683 @end example
14685 Don't rely on the exit status of an assignment: Ash 0.2 does not change
14686 the status and propagates that of the last statement:
14688 @example
14689 $ @kbd{false || foo=bar; echo $?}
14691 $ @kbd{false || foo=`:`; echo $?}
14693 @end example
14695 @noindent
14696 and to make things even worse, @acronym{QNX} 4.25 just sets the exit status
14697 to 0 in any case:
14699 @example
14700 $ @kbd{foo=`exit 1`; echo $?}
14702 @end example
14704 To assign default values, follow this algorithm:
14706 @enumerate
14707 @item
14708 If the default value is a literal and does not contain any closing
14709 brace, use:
14711 @example
14712 : $@{var='my literal'@}
14713 @end example
14715 @item
14716 If the default value contains no closing brace, has to be expanded, and
14717 the variable being initialized is not intended to be IFS-split
14718 (i.e., it's not a list), then use:
14720 @example
14721 : $@{var="$default"@}
14722 @end example
14724 @item
14725 If the default value contains no closing brace, has to be expanded, and
14726 the variable being initialized is intended to be IFS-split (i.e., it's a list),
14727 then use:
14729 @example
14730 var=$@{var="$default"@}
14731 @end example
14733 @item
14734 If the default value contains a closing brace, then use:
14736 @example
14737 test "$@{var+set@}" = set || var="has a '@}'"
14738 @end example
14739 @end enumerate
14741 In most cases @samp{var=$@{var="$default"@}} is fine, but in case of
14742 doubt, just use the last form.  @xref{Shell Substitutions}, items
14743 @samp{$@{@var{var}:-@var{value}@}} and @samp{$@{@var{var}=@var{value}@}}
14744 for the rationale.
14746 @node Parentheses
14747 @section Parentheses in Shell Scripts
14748 @cindex Shell parentheses
14750 Beware of two opening parentheses in a row, as many shell
14751 implementations treat them specially.  Posix requires that the command
14752 @samp{((cat))} must behave like @samp{(cat)}, but many shells, including
14753 Bash and the Korn shell, treat @samp{((cat))} as an arithmetic
14754 expression equivalent to @samp{let "cat"}, and may or may not report an
14755 error when they detect that @samp{cat} is not a number.  As another
14756 example, @samp{pdksh} 5.2.14 misparses the following code:
14758 @example
14759 if ((true) || false); then
14760   echo ok
14762 @end example
14764 @noindent
14765 To work around this problem, insert a space between the two opening
14766 parentheses.  There is a similar problem and workaround with
14767 @samp{$((}; see @ref{Shell Substitutions}.
14769 @node Slashes
14770 @section Slashes in Shell Scripts
14771 @cindex Shell slashes
14773 Unpatched Tru64 5.1 @command{sh} omits the last slash of command-line
14774 arguments that contain two trailing slashes:
14776 @example
14777 $ @kbd{echo / // /// //// .// //.}
14778 / / // /// ./ //.
14779 $ @kbd{x=//}
14780 $ @kbd{eval "echo \$x"}
14782 $ @kbd{set -x}
14783 $ @kbd{echo abc | tr -t ab //}
14784 + echo abc
14785 + tr -t ab /
14787 @end example
14789 Unpatched Tru64 4.0 @command{sh} adds a slash after @samp{"$var"} if the
14790 variable is empty and the second double-quote is followed by a word that
14791 begins and ends with slash:
14793 @example
14794 $ @kbd{sh -xc 'p=; echo "$p"/ouch/'}
14796 + echo //ouch/
14797 //ouch/
14798 @end example
14800 However, our understanding is that patches are available, so perhaps
14801 it's not worth worrying about working around these horrendous bugs.
14803 @node Special Shell Variables
14804 @section Special Shell Variables
14805 @cindex Shell variables
14806 @cindex Special shell variables
14808 Some shell variables should not be used, since they can have a deep
14809 influence on the behavior of the shell.  In order to recover a sane
14810 behavior from the shell, some variables should be unset; M4sh takes
14811 care of this and provides fallback values, whenever needed, to cater
14812 for a very old @file{/bin/sh} that does not support @command{unset}.
14813 (@pxref{Portable Shell, , Portable Shell Programming}).
14815 As a general rule, shell variable names containing a lower-case letter
14816 are safe; you can define and use these variables without worrying about
14817 their effect on the underlying system, and without worrying about
14818 whether the shell changes them unexpectedly.  (The exception is the
14819 shell variable @code{status}, as described below.)
14821 Here is a list of names that are known to cause trouble.  This list is
14822 not exhaustive, but you should be safe if you avoid the name
14823 @code{status} and names containing only upper-case letters and
14824 underscores.
14826 @c Alphabetical order, case insensitive, `A' before `a'.
14827 @table @code
14828 @item _
14829 Many shells reserve @samp{$_} for various purposes, e.g., the name of
14830 the last command executed.
14832 @item BIN_SH
14833 @evindex BIN_SH
14834 In Tru64, if @env{BIN_SH} is set to @code{xpg4}, subsidiary invocations of
14835 the standard shell conform to Posix.
14837 @item CDPATH
14838 @evindex CDPATH
14839 When this variable is set it specifies a list of directories to search
14840 when invoking @code{cd} with a relative file name that did not start
14841 with @samp{./} or @samp{../}.  Posix
14842 1003.1-2001 says that if a nonempty directory name from @env{CDPATH}
14843 is used successfully, @code{cd} prints the resulting absolute
14844 file name.  Unfortunately this output can break idioms like
14845 @samp{abs=`cd src && pwd`} because @code{abs} receives the name twice.
14846 Also, many shells do not conform to this part of Posix; for
14847 example, @command{zsh} prints the result only if a directory name
14848 other than @file{.} was chosen from @env{CDPATH}.
14850 In practice the shells that have this problem also support
14851 @command{unset}, so you can work around the problem as follows:
14853 @example
14854 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
14855 @end example
14857 You can also avoid output by ensuring that your directory name is
14858 absolute or anchored at @samp{./}, as in @samp{abs=`cd ./src && pwd`}.
14860 Configure scripts use M4sh, which automatically unsets @env{CDPATH} if
14861 possible, so you need not worry about this problem in those scripts.
14863 @item DUALCASE
14864 @evindex DUALCASE
14865 In the MKS shell, case statements and file name generation are
14866 case-insensitive unless @env{DUALCASE} is nonzero.
14867 Autoconf-generated scripts export this variable when they start up.
14869 @item ENV
14870 @itemx MAIL
14871 @itemx MAILPATH
14872 @itemx PS1
14873 @itemx PS2
14874 @itemx PS4
14875 @evindex ENV
14876 @evindex MAIL
14877 @evindex MAILPATH
14878 @evindex PS1
14879 @evindex PS2
14880 @evindex PS4
14881 These variables should not matter for shell scripts, since they are
14882 supposed to affect only interactive shells.  However, at least one
14883 shell (the pre-3.0 @sc{uwin} Korn shell) gets confused about
14884 whether it is interactive, which means that (for example) a @env{PS1}
14885 with a side effect can unexpectedly modify @samp{$?}.  To work around
14886 this bug, M4sh scripts (including @file{configure} scripts) do something
14887 like this:
14889 @example
14890 (unset ENV) >/dev/null 2>&1 && unset ENV MAIL MAILPATH
14891 PS1='$ '
14892 PS2='> '
14893 PS4='+ '
14894 @end example
14896 @noindent
14897 (actually, there is some complication due to bugs in @command{unset};
14898 see @pxref{unset, , Limitations of Shell Builtins}).
14900 @item FPATH
14901 The Korn shell uses @env{FPATH} to find shell functions, so avoid
14902 @env{FPATH} in portable scripts.  @env{FPATH} is consulted after
14903 @env{PATH}, but you still need to be wary of tests that use @env{PATH}
14904 to find whether a command exists, since they might report the wrong
14905 result if @env{FPATH} is also set.
14907 @item IFS
14908 @evindex IFS
14909 Long ago, shell scripts inherited @env{IFS} from the environment,
14910 but this caused many problems so modern shells ignore any environment
14911 settings for @env{IFS}.
14913 Don't set the first character of @code{IFS} to backslash.  Indeed,
14914 Bourne shells use the first character (backslash) when joining the
14915 components in @samp{"$@@"} and some shells then reinterpret (!)@: the
14916 backslash escapes, so you can end up with backspace and other strange
14917 characters.
14919 The proper value for @code{IFS} (in regular code, not when performing
14920 splits) is @samp{@key{SPC}@key{TAB}@key{RET}}.  The first character is
14921 especially important, as it is used to join the arguments in @samp{$*};
14922 however, note that traditional shells, but also bash-2.04, fail to adhere
14923 to this and join with a space anyway.
14925 @item LANG
14926 @itemx LC_ALL
14927 @itemx LC_COLLATE
14928 @itemx LC_CTYPE
14929 @itemx LC_MESSAGES
14930 @itemx LC_MONETARY
14931 @itemx LC_NUMERIC
14932 @itemx LC_TIME
14933 @evindex LANG
14934 @evindex LC_ALL
14935 @evindex LC_COLLATE
14936 @evindex LC_CTYPE
14937 @evindex LC_MESSAGES
14938 @evindex LC_MONETARY
14939 @evindex LC_NUMERIC
14940 @evindex LC_TIME
14942 You should set all these variables to @samp{C} because so much
14943 configuration code assumes the C locale and Posix requires that locale
14944 environment variables be set to @samp{C} if the C locale is desired;
14945 @file{configure} scripts and M4sh do that for you.
14946 Export these variables after setting them.
14948 @c  However, some older, nonstandard
14949 @c  systems (notably @acronym{SCO}) break if locale environment variables
14950 @c  are set to @samp{C}, so when running on these systems
14951 @c  Autoconf-generated scripts unset the variables instead.
14953 @item LANGUAGE
14954 @evindex LANGUAGE
14956 @env{LANGUAGE} is not specified by Posix, but it is a @acronym{GNU}
14957 extension that overrides @env{LC_ALL} in some cases, so you (or M4sh)
14958 should set it too.
14960 @item LC_ADDRESS
14961 @itemx LC_IDENTIFICATION
14962 @itemx LC_MEASUREMENT
14963 @itemx LC_NAME
14964 @itemx LC_PAPER
14965 @itemx LC_TELEPHONE
14966 @evindex LC_ADDRESS
14967 @evindex LC_IDENTIFICATION
14968 @evindex LC_MEASUREMENT
14969 @evindex LC_NAME
14970 @evindex LC_PAPER
14971 @evindex LC_TELEPHONE
14973 These locale environment variables are @acronym{GNU} extensions.  They
14974 are treated like their Posix brethren (@env{LC_COLLATE},
14975 etc.)@: as described above.
14977 @item LINENO
14978 Most modern shells provide the current line number in @code{LINENO}.
14979 Its value is the line number of the beginning of the current command.
14980 M4sh, and hence Autoconf, attempts to execute @command{configure} with
14981 a shell that supports @code{LINENO}.  If no such shell is available, it
14982 attempts to implement @code{LINENO} with a Sed prepass that replaces each
14983 instance of the string @code{$LINENO} (not followed by an alphanumeric
14984 character) with the line's number.  In M4sh scripts you should execute
14985 @code{AS_LINENO_PREPARE} so that these workarounds are included in
14986 your script; configure scripts do this automatically in @code{AC_INIT}.
14988 You should not rely on @code{LINENO} within @command{eval} or shell
14989 functions, as the behavior differs in practice.  The presence of a
14990 quoted newline within simple commands can alter which line number is
14991 used as the starting point for @code{$LINENO} substitutions within that
14992 command.  Also, the possibility of the Sed prepass means that you should
14993 not rely on @code{$LINENO} when quoted, when in here-documents, or when
14994 line continuations are used.  Subshells should be OK, though.  In the
14995 following example, lines 1, 9, and 14 are portable, but the other
14996 instances of @code{$LINENO} do not have deterministic values:
14998 @example
14999 @group
15000 $ @kbd{cat lineno}
15001 echo 1. $LINENO
15002 echo "2. $LINENO
15003 3. $LINENO"
15004 cat <<EOF
15005 5. $LINENO
15006 6. $LINENO
15007 7. \$LINENO
15009 ( echo 9. $LINENO )
15010 eval 'echo 10. $LINENO'
15011 eval 'echo 11. $LINENO
15012 echo 12. $LINENO'
15013 echo 13. '$LINENO'
15014 echo 14. $LINENO '
15015 15.' $LINENO
15016 f () @{ echo $1 $LINENO;
15017 echo $1 $LINENO @}
15018 f 18.
15019 echo 19. \
15020 $LINENO
15021 @end group
15022 @group
15023 $ @kbd{bash-3.2 ./lineno}
15024 1. 1
15025 2. 3
15026 3. 3
15027 5. 4
15028 6. 4
15029 7. $LINENO
15030 9. 9
15031 10. 10
15032 11. 12
15033 12. 13
15034 13. $LINENO
15035 14. 14
15036 15. 14
15037 18. 16
15038 18. 17
15039 19. 19
15040 @end group
15041 @group
15042 $ @kbd{zsh-4.3.4 ./lineno}
15043 1. 1
15044 2. 2
15045 3. 2
15046 5. 4
15047 6. 4
15048 7. $LINENO
15049 9. 9
15050 10. 1
15051 11. 1
15052 12. 2
15053 13. $LINENO
15054 14. 14
15055 15. 14
15056 18. 0
15057 18. 1
15058 19. 19
15059 @end group
15060 @group
15061 $ @kbd{pdksh-5.2.14 ./lineno}
15062 1. 1
15063 2. 2
15064 3. 2
15065 5. 4
15066 6. 4
15067 7. $LINENO
15068 9. 9
15069 10. 0
15070 11. 0
15071 12. 0
15072 13. $LINENO
15073 14. 14
15074 15. 14
15075 18. 16
15076 18. 17
15077 19. 19
15078 @end group
15079 @group
15080 $ @kbd{sed '=' <lineno |}
15081 > @kbd{  sed '}
15082 > @kbd{    N}
15083 > @kbd{    s,$,-,}
15084 > @kbd{    t loop}
15085 > @kbd{    :loop}
15086 > @kbd{    s,^\([0-9]*\)\(.*\)[$]LINENO\([^a-zA-Z0-9_]\),\1\2\1\3,}
15087 > @kbd{    t loop}
15088 > @kbd{    s,-$,,}
15089 > @kbd{    s,^[0-9]*\n,,}
15090 > @kbd{  ' |}
15091 > @kbd{  sh}
15092 1. 1
15093 2. 2
15094 3. 3
15095 5. 5
15096 6. 6
15097 7. \7
15098 9. 9
15099 10. 10
15100 11. 11
15101 12. 12
15102 13. 13
15103 14. 14
15104 15. 15
15105 18. 16
15106 18. 17
15107 19. 20
15108 @end group
15109 @end example
15111 In particular, note that @file{config.status} (and any other subsidiary
15112 script created by @code{AS_INIT_GENERATED}) might report line numbers
15113 relative to the parent script as a result of the potential Sed pass.
15115 @item NULLCMD
15116 @evindex NULLCMD
15117 When executing the command @samp{>foo}, @command{zsh} executes
15118 @samp{$NULLCMD >foo} unless it is operating in Bourne shell
15119 compatibility mode and the @command{zsh} version is newer
15120 than 3.1.6-dev-18.  If you are using an older @command{zsh}
15121 and forget to set @env{NULLCMD},
15122 your script might be suspended waiting for data on its standard input.
15124 @item PATH_SEPARATOR
15125 @evindex PATH_SEPARATOR
15126 On @acronym{DJGPP} systems, the @env{PATH_SEPARATOR} environment
15127 variable can be set to either @samp{:} or @samp{;} to control the path
15128 separator Bash uses to set up certain environment variables (such as
15129 @env{PATH}).  You can set this variable to @samp{;} if you want
15130 @command{configure} to use @samp{;} as a separator; this might be useful
15131 if you plan to use non-Posix shells to execute files.  @xref{File System
15132 Conventions}, for more information about @code{PATH_SEPARATOR}.
15134 @item PWD
15135 @evindex PWD
15136 Posix 1003.1-2001 requires that @command{cd} and
15137 @command{pwd} must update the @env{PWD} environment variable to point
15138 to the logical name of the current directory, but traditional shells
15139 do not support this.  This can cause confusion if one shell instance
15140 maintains @env{PWD} but a subsidiary and different shell does not know
15141 about @env{PWD} and executes @command{cd}; in this case @env{PWD}
15142 points to the wrong directory.  Use @samp{`pwd`} rather than
15143 @samp{$PWD}.
15145 @item RANDOM
15146 Many shells provide @code{RANDOM}, a variable that returns a different
15147 integer each time it is used.  Most of the time, its value does not
15148 change when it is not used, but on @sc{irix} 6.5 the value changes all
15149 the time.  This can be observed by using @command{set}.  It is common
15150 practice to use @code{$RANDOM} as part of a file name, but code
15151 shouldn't rely on @code{$RANDOM} expanding to a nonempty string.
15153 @item status
15154 This variable is an alias to @samp{$?} for @code{zsh} (at least 3.1.6),
15155 hence read-only.  Do not use it.
15156 @end table
15158 @node Shell Functions
15159 @section Shell Functions
15160 @cindex Shell Functions
15162 Nowadays, it is difficult to find a shell that does not support
15163 shell functions at all.  However, some differences should be expected.
15165 Inside a shell function, you should not rely on the error status of a
15166 subshell if the last command of that subshell was @code{exit} or
15167 @code{trap}, as this triggers bugs in zsh 4.x; while Autoconf tries to
15168 find a shell that does not exhibit the bug, zsh might be the only shell
15169 present on the user's machine.
15171 Likewise, the state of @samp{$?} is not reliable when entering a shell
15172 function.  This has the effect that using a function as the first
15173 command in a @command{trap} handler can cause problems.
15175 @example
15176 $ @kbd{bash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15179 $ @kbd{ash -c 'foo()@{ echo $?; @}; trap foo 0; (exit 2); exit 2'; echo $?}
15182 @end example
15184 Not all shells treat shell functions as simple commands impacted by
15185 @samp{set -e}, for example with Solaris 10 @command{bin/sh}:
15187 @example
15188 $ @kbd{bash -c 'f()@{ return 1; @}; set -e; f; echo oops}
15189 $ @kbd{/bin/sh -c 'f()@{ return 1; @}; set -e; f; echo oops}
15190 oops
15191 @end example
15193 Shell variables and functions may share the same namespace, for example
15194 with Solaris 10 @command{/bin/sh}:
15196 @example
15197 $ @kbd{f () @{ :; @}; f=; f}
15198 f: not found
15199 @end example
15201 @noindent
15202 For this reason, Autoconf (actually M4sh, @pxref{Programming in M4sh})
15203 uses the prefix @samp{as_fn_} for its functions.
15205 Handling of positional parameters and shell options varies among shells.
15206 For example, Korn shells reset and restore trace output (@samp{set -x})
15207 and other options upon function entry and exit.  Inside a function,
15208 @acronym{IRIX} sh sets @samp{$0} to the function name.
15210 It is not portable to pass temporary environment variables to shell
15211 functions.  Solaris @command{/bin/sh} does not see the variable.
15212 Meanwhile, not all shells follow the Posix rule that the assignment must
15213 affect the current environment in the same manner as special built-ins.
15215 @example
15216 $ @kbd{/bin/sh -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
15217 @result{}
15218 @result{}
15219 $ @kbd{ash -c 'func()@{ echo $a;@}; a=1 func; echo $a'}
15220 @result{}1
15221 @result{}
15222 $ @kbd{bash -c 'set -o posix; func()@{ echo $a;@}; a=1 func; echo $a'}
15223 @result{}1
15224 @result{}1
15225 @end example
15227 Some ancient Bourne shell variants with function support did not reset
15228 @samp{$@var{i}, @var{i} >= 0}, upon function exit, so effectively the
15229 arguments of the script were lost after the first function invocation.
15230 It is probably not worth worrying about these shells any more.
15232 With @acronym{AIX} sh, a @command{trap} on 0 installed in a shell function
15233 triggers at function exit rather than at script exit, see @xref{trap, ,
15234 Limitations of Shell Builtins}.
15236 @node Limitations of Builtins
15237 @section Limitations of Shell Builtins
15238 @cindex Shell builtins
15239 @cindex Limitations of shell builtins
15241 No, no, we are serious: some shells do have limitations!  :)
15243 You should always keep in mind that any builtin or command may support
15244 options, and therefore differ in behavior with arguments
15245 starting with a dash.  For instance, even the innocent @samp{echo "$word"}
15246 can give unexpected results when @code{word} starts with a dash.  It is
15247 often possible to avoid this problem using @samp{echo "x$word"}, taking
15248 the @samp{x} into account later in the pipe.  Many of these limitations
15249 can be worked around using M4sh (@pxref{Programming in M4sh}).
15251 @c This table includes things like `@command{test} (files)', so we can't
15252 @c use @table @command.
15253 @table @asis
15254 @item @command{.}
15255 @c --------------
15256 @prindex @command{.}
15257 Use @command{.} only with regular files (use @samp{test -f}).  Bash
15258 2.03, for instance, chokes on @samp{. /dev/null}.  Remember that
15259 @command{.} uses @env{PATH} if its argument contains no slashes.  Also,
15260 some shells, including bash 3.2, implicitly append the current directory
15261 to this @env{PATH} search, even though Posix forbids it.  So if you want
15262 to use @command{.} on a file @file{foo} in the current directory, you
15263 must use @samp{. ./foo}.
15265 @item @command{!}
15266 @c --------------
15267 @prindex @command{!}
15268 The Unix version 7 shell did not support
15269 negating the exit status of commands with @command{!}, and this feature
15270 is still absent from some shells (e.g., Solaris @command{/bin/sh}).
15271 Other shells, such as FreeBSD @command{/bin/sh} or @command{ash}, have
15272 bugs when using @command{!}:
15274 @example
15275 $ @kbd{sh -c '! : | :'; echo $?}
15277 $ @kbd{ash -c '! : | :'; echo $?}
15279 $ @kbd{sh -c '! @{ :; @}'; echo $?}
15281 $ @kbd{ash -c '! @{ :; @}'; echo $?}
15282 @{: not found
15283 Syntax error: "@}" unexpected
15285 @end example
15287 Shell code like this:
15289 @example
15290 if ! cmp file1 file2 >/dev/null 2>&1; then
15291   echo files differ or trouble
15293 @end example
15295 is therefore not portable in practice.  Typically it is easy to rewrite
15296 such code, e.g.:
15298 @example
15299 cmp file1 file2 >/dev/null 2>&1 ||
15300   echo files differ or trouble
15301 @end example
15303 More generally, one can always rewrite @samp{! @var{command}} as:
15305 @example
15306 if @var{command}; then (exit 1); else :; fi
15307 @end example
15310 @item @command{@{...@}}
15311 @c --------------------
15312 @prindex @command{@{...@}}
15313 Bash 3.2 (and earlier versions) sometimes does not properly set
15314 @samp{$?} when failing to write redirected output of a compound command.
15315 This problem is most commonly observed with @samp{@{@dots{}@}}; it does
15316 not occur with @samp{(@dots{})}.  For example:
15318 @example
15319 $ @kbd{bash -c '@{ echo foo; @} >/bad; echo $?'}
15320 bash: line 1: /bad: Permission denied
15322 $ @kbd{bash -c 'while :; do echo; done >/bad; echo $?'}
15323 bash: line 1: /bad: Permission denied
15325 @end example
15327 To work around the bug, prepend @samp{:;}:
15329 @example
15330 $ @kbd{bash -c ':;@{ echo foo; @} >/bad; echo $?'}
15331 bash: line 1: /bad: Permission denied
15333 @end example
15335 Posix requires a syntax error if a brace list has no contents.  However,
15336 not all shells obey this rule; and on shells where empty lists are
15337 permitted, the effect on @samp{$?} is inconsistent.  To avoid problems,
15338 ensure that a brace list is never empty.
15340 @example
15341 $ @kbd{bash -c 'false; @{ @}; echo $?' || echo $?}
15342 bash: line 1: syntax error near unexpected token `@}'
15343 bash: line 1: `false; @{ @}; echo $?'
15345 $ @kbd{zsh -c 'false; @{ @}; echo $?' || echo $?}
15347 $ @kbd{pdksh -c 'false; @{ @}; echo $?' || echo $?}
15349 @end example
15352 @item @command{break}
15353 @c ------------------
15354 @prindex @command{break}
15355 The use of @samp{break 2} etc.@: is safe.
15358 @anchor{case}
15359 @item @command{case}
15360 @c -----------------
15361 @prindex @command{case}
15362 You don't need to quote the argument; no splitting is performed.
15364 You don't need the final @samp{;;}, but you should use it.
15366 Posix requires support for @code{case} patterns with opening
15367 parentheses like this:
15369 @example
15370 case $file_name in
15371   (*.c) echo "C source code";;
15372 esac
15373 @end example
15375 @noindent
15376 but the @code{(} in this example is not portable to many Bourne
15377 shell implementations, which is a pity for those of us using tools that
15378 rely on balanced parentheses.  For instance, with Solaris
15379 @command{/bin/sh}:
15381 @example
15382 $ @kbd{case foo in (foo) echo foo;; esac}
15383 @error{}syntax error: `(' unexpected
15384 @end example
15386 @noindent
15387 The leading @samp{(} can be omitted safely.  Unfortunately, there are
15388 contexts where unbalanced parentheses cause other problems, such as when
15389 using a syntax-highlighting editor that searches for the balancing
15390 counterpart, or more importantly, when using a case statement as an
15391 underquoted argument to an Autoconf macro.  @xref{Balancing
15392 Parentheses}, for tradeoffs involved in various styles of dealing with
15393 unbalanced @samp{)}.
15395 Zsh handles pattern fragments derived from parameter expansions or
15396 command substitutions as though quoted:
15398 @example
15399 $ pat=\?; case aa in ?$pat) echo match;; esac
15400 $ pat=\?; case a? in ?$pat) echo match;; esac
15401 match
15402 @end example
15404 @noindent
15405 Because of a bug in its @code{fnmatch}, Bash fails to properly
15406 handle backslashes in character classes:
15408 @example
15409 bash-2.02$ @kbd{case /tmp in [/\\]*) echo OK;; esac}
15410 bash-2.02$
15411 @end example
15413 @noindent
15414 This is extremely unfortunate, since you are likely to use this code to
15415 handle Posix or @sc{ms-dos} absolute file names.  To work around this
15416 bug, always put the backslash first:
15418 @example
15419 bash-2.02$ @kbd{case '\TMP' in [\\/]*) echo OK;; esac}
15421 bash-2.02$ @kbd{case /tmp in [\\/]*) echo OK;; esac}
15423 @end example
15425 Many Bourne shells cannot handle closing brackets in character classes
15426 correctly.
15428 Some shells also have problems with backslash escaping in case you do not want
15429 to match the backslash: both a backslash and the escaped character match this
15430 pattern.  To work around this, specify the character class in a variable, so
15431 that quote removal does not apply afterwards, and the special characters don't
15432 have to be backslash-escaped:
15434 @example
15435 $ @kbd{case '\' in [\<]) echo OK;; esac}
15437 $ @kbd{scanset='[<]'; case '\' in $scanset) echo OK;; esac}
15439 @end example
15441 Even with this, Solaris @command{ksh} matches a backslash if the set
15442 contains any
15443 of the characters @samp{|}, @samp{&}, @samp{(}, or @samp{)}.
15445 Conversely, Tru64 @command{ksh} (circa 2003) erroneously always matches
15446 a closing parenthesis if not specified in a character class:
15448 @example
15449 $ @kbd{case foo in *\)*) echo fail ;; esac}
15450 fail
15451 $ @kbd{case foo in *')'*) echo fail ;; esac}
15452 fail
15453 @end example
15455 Some shells, such as Ash 0.3.8, are confused by an empty
15456 @code{case}/@code{esac}:
15458 @example
15459 ash-0.3.8 $ @kbd{case foo in esac;}
15460 @error{}Syntax error: ";" unexpected (expecting ")")
15461 @end example
15463 Posix requires @command{case} to give an exit status of 0 if no cases
15464 match.  However, @command{/bin/sh} in Solaris 10 does not obey this
15465 rule.  Meanwhile, it is unclear whether a case that matches, but
15466 contains no statements, must also change the exit status to 0.  The M4sh
15467 macro @code{AS_CASE} works around these inconsistencies.
15469 @example
15470 $ @kbd{bash -c 'case `false` in ?) ;; esac; echo $?'}
15472 $ @kbd{/bin/sh -c 'case `false` in ?) ;; esac; echo $?'}
15474 @end example
15477 @item @command{cd}
15478 @c ---------------
15479 @prindex @command{cd}
15480 Posix 1003.1-2001 requires that @command{cd} must support
15481 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
15482 with @option{-L} being the default.  However, traditional shells do
15483 not support these options, and their @command{cd} command has the
15484 @option{-P} behavior.
15486 Portable scripts should assume neither option is supported, and should
15487 assume neither behavior is the default.  This can be a bit tricky,
15488 since the Posix default behavior means that, for example,
15489 @samp{ls ..} and @samp{cd ..} may refer to different directories if
15490 the current logical directory is a symbolic link.  It is safe to use
15491 @code{cd @var{dir}} if @var{dir} contains no @file{..} components.
15492 Also, Autoconf-generated scripts check for this problem when computing
15493 variables like @code{ac_top_srcdir} (@pxref{Configuration Actions}),
15494 so it is safe to @command{cd} to these variables.
15496 See @xref{Special Shell Variables}, for portability problems involving
15497 @command{cd} and the @env{CDPATH} environment variable.
15498 Also please see the discussion of the @command{pwd} command.
15501 @anchor{echo}
15502 @item @command{echo}
15503 @c -----------------
15504 @prindex @command{echo}
15505 The simple @command{echo} is probably the most surprising source of
15506 portability troubles.  It is not possible to use @samp{echo} portably
15507 unless both options and escape sequences are omitted.  Don't expect any
15508 option.
15510 Do not use backslashes in the arguments, as there is no consensus on
15511 their handling.  For @samp{echo '\n' | wc -l}, the @command{sh} of
15512 Solaris outputs 2, but Bash and Zsh (in @command{sh} emulation mode) output 1.
15513 The problem is truly @command{echo}: all the shells
15514 understand @samp{'\n'} as the string composed of a backslash and an
15515 @samp{n}.
15517 Because of these problems, do not pass a string containing arbitrary
15518 characters to @command{echo}.  For example, @samp{echo "$foo"} is safe
15519 if you know that @var{foo}'s value cannot contain backslashes and cannot
15520 start with @samp{-}, but otherwise you should use a here-document like
15521 this:
15523 @example
15524 cat <<EOF
15525 $foo
15527 @end example
15529 New applications which are not aiming at portability should use
15530 @command{printf} instead of @command{echo}.  M4sh provides the
15531 @code{AS_ECHO} and @code{AS_ECHO_N} macros, which choose between
15532 @samp{echo -n} on implementations where that works, @command{printf} if
15533 it is available, or other creative tricks in order to work around the
15534 above problems.
15537 @item @command{eval}
15538 @c -----------------
15539 @prindex @command{eval}
15540 The @command{eval} command is useful in limited circumstances, e.g.,
15541 using commands like @samp{eval table_$key=\$value} and @samp{eval
15542 value=table_$key} to simulate a hash table when the key is known to be
15543 alphanumeric.
15545 You should also be wary of common bugs in @command{eval} implementations.
15546 In some shell implementations (e.g., older @command{ash}, Open@acronym{BSD} 3.8
15547 @command{sh}, @command{pdksh} v5.2.14 99/07/13.2, and @command{zsh}
15548 4.2.5), the arguments of @samp{eval} are evaluated in a context where
15549 @samp{$?} is 0, so they exhibit behavior like this:
15551 @example
15552 $ @kbd{false; eval 'echo $?'}
15554 @end example
15556 The correct behavior here is to output a nonzero value,
15557 but portable scripts should not rely on this.
15559 You should not rely on @code{LINENO} within @command{eval}.
15560 @xref{Special Shell Variables}.
15562 Note that, even though these bugs are easily avoided,
15563 @command{eval} is tricky to use on arbitrary arguments.
15564 It is obviously unwise to use @samp{eval $cmd} if the string value of
15565 @samp{cmd} was derived from an untrustworthy source.  But even if the
15566 string value is valid, @samp{eval $cmd} might not work as intended,
15567 since it causes field splitting and file name expansion to occur twice,
15568 once for the @command{eval} and once for the command itself.  It is
15569 therefore safer to use @samp{eval "$cmd"}.  For example, if @var{cmd}
15570 has the value @samp{cat test?.c}, @samp{eval $cmd} might expand to the
15571 equivalent of @samp{cat test;.c} if there happens to be a file named
15572 @file{test;.c} in the current directory; and this in turn
15573 mistakenly attempts to invoke @command{cat} on the file @file{test} and
15574 then execute the command @command{.c}.  To avoid this problem, use
15575 @samp{eval "$cmd"} rather than @samp{eval $cmd}.
15577 However, suppose that you want to output the text of the evaluated
15578 command just before executing it.  Assuming the previous example,
15579 @samp{echo "Executing: $cmd"} outputs @samp{Executing: cat test?.c}, but
15580 this output doesn't show the user that @samp{test;.c} is the actual name
15581 of the copied file.  Conversely, @samp{eval "echo Executing: $cmd"}
15582 works on this example, but it fails with @samp{cmd='cat foo >bar'},
15583 since it mistakenly replaces the contents of @file{bar} by the
15584 string @samp{cat foo}.  No simple, general, and portable solution to
15585 this problem is known.
15587 @item @command{exec}
15588 @c -----------------
15589 @prindex @command{exec}
15590 Posix describes several categories of shell built-ins.  Special
15591 built-ins (such as @command{exit}) must impact the environment of the
15592 current shell, and need not be available through @command{exec}.  All
15593 other built-ins are regular, and must not propagate variable assignments
15594 to the environment of the current shell.  However, the group of regular
15595 built-ins is further distinguished by commands that do not require a
15596 @env{PATH} search (such as @command{cd}), in contrast to built-ins that
15597 are offered as a more efficient version of something that must still be
15598 found in a @env{PATH} search (such as @command{echo}).  Posix is not
15599 clear on whether @command{exec} must work with the list of 17 utilities
15600 that are invoked without a @env{PATH} search, and many platforms lack an
15601 executable for some of those built-ins:
15603 @example
15604 $ @kbd{sh -c 'exec cd /tmp'}
15605 sh: line 0: exec: cd: not found
15606 @end example
15608 All other built-ins that provide utilities specified by Posix must have
15609 a counterpart executable that exists on @env{PATH}, although Posix
15610 allows @command{exec} to use the built-in instead of the executable.
15611 For example, contrast @command{bash} 3.2 and @command{pdksh} 5.2.14:
15613 @example
15614 $ @kbd{bash -c 'pwd --version' | head -n1}
15615 bash: line 0: pwd: --: invalid option
15616 pwd: usage: pwd [-LP]
15617 $ @kbd{bash -c 'exec pwd --version' | head -n1}
15618 pwd (GNU coreutils) 6.10
15619 $ @kbd{pdksh -c 'exec pwd --version' | head -n1}
15620 pdksh: pwd: --: unknown option
15621 @end example
15623 When it is desired to avoid a regular shell built-in, the workaround is
15624 to use some other forwarding command, such as @command{env} or
15625 @command{nice}, that will ensure a path search:
15627 @example
15628 $ @kbd{pdksh -c 'exec true --version' | head -n1}
15629 $ @kbd{pdksh -c 'nice true --version' | head -n1}
15630 true (GNU coreutils) 6.10
15631 $ @kbd{pdksh -c 'env true --version' | head -n1}
15632 true (GNU coreutils) 6.10
15633 @end example
15635 @item @command{exit}
15636 @c -----------------
15637 @prindex @command{exit}
15638 The default value of @command{exit} is supposed to be @code{$?};
15639 unfortunately, some shells, such as the @acronym{DJGPP} port of Bash 2.04, just
15640 perform @samp{exit 0}.
15642 @example
15643 bash-2.04$ @kbd{foo=`exit 1` || echo fail}
15644 fail
15645 bash-2.04$ @kbd{foo=`(exit 1)` || echo fail}
15646 fail
15647 bash-2.04$ @kbd{foo=`(exit 1); exit` || echo fail}
15648 bash-2.04$
15649 @end example
15651 Using @samp{exit $?} restores the expected behavior.
15653 Some shell scripts, such as those generated by @command{autoconf}, use a
15654 trap to clean up before exiting.  If the last shell command exited with
15655 nonzero status, the trap also exits with nonzero status so that the
15656 invoker can tell that an error occurred.
15658 Unfortunately, in some shells, such as Solaris @command{/bin/sh}, an exit
15659 trap ignores the @code{exit} command's argument.  In these shells, a trap
15660 cannot determine whether it was invoked by plain @code{exit} or by
15661 @code{exit 1}.  Instead of calling @code{exit} directly, use the
15662 @code{AC_MSG_ERROR} macro that has a workaround for this problem.
15665 @anchor{export}
15666 @item @command{export}
15667 @c -------------------
15668 @prindex @command{export}
15669 The builtin @command{export} dubs a shell variable @dfn{environment
15670 variable}.  Each update of exported variables corresponds to an update
15671 of the environment variables.  Conversely, each environment variable
15672 received by the shell when it is launched should be imported as a shell
15673 variable marked as exported.
15675 Alas, many shells, such as Solaris @command{/bin/sh},
15676 @sc{irix} 6.3, @sc{irix} 5.2,
15677 @acronym{AIX} 4.1.5, and Digital Unix 4.0, forget to
15678 @command{export} the environment variables they receive.  As a result,
15679 two variables coexist: the environment variable and the shell
15680 variable.  The following code demonstrates this failure:
15682 @example
15683 #!/bin/sh
15684 echo $FOO
15685 FOO=bar
15686 echo $FOO
15687 exec /bin/sh $0
15688 @end example
15690 @noindent
15691 when run with @samp{FOO=foo} in the environment, these shells print
15692 alternately @samp{foo} and @samp{bar}, although they should print only
15693 @samp{foo} and then a sequence of @samp{bar}s.
15695 Therefore you should @command{export} again each environment variable
15696 that you update; the export can occur before or after the assignment.
15698 Posix is not clear on whether the @command{export} of an undefined
15699 variable causes the variable to be defined with the value of an empty
15700 string, or merely marks any future definition of a variable by that name
15701 for export.  Various shells behave differently in this regard:
15703 @example
15704 $ @kbd{sh -c 'export foo; env | grep foo'}
15705 $ @kbd{ash -c 'export foo; env | grep foo'}
15706 foo=
15707 @end example
15709 @item @command{false}
15710 @c ------------------
15711 @prindex @command{false}
15712 Don't expect @command{false} to exit with status 1: in native
15713 Solaris @file{/bin/false} exits with status 255.
15716 @item @command{for}
15717 @c ----------------
15718 @prindex @command{for}
15719 To loop over positional arguments, use:
15721 @example
15722 for arg
15724   echo "$arg"
15725 done
15726 @end example
15728 @noindent
15729 You may @emph{not} leave the @code{do} on the same line as @code{for},
15730 since some shells improperly grok:
15732 @example
15733 for arg; do
15734   echo "$arg"
15735 done
15736 @end example
15738 If you want to explicitly refer to the positional arguments, given the
15739 @samp{$@@} bug (@pxref{Shell Substitutions}), use:
15741 @example
15742 for arg in $@{1+"$@@"@}; do
15743   echo "$arg"
15744 done
15745 @end example
15747 @noindent
15748 But keep in mind that Zsh, even in Bourne shell emulation mode, performs
15749 word splitting on @samp{$@{1+"$@@"@}}; see @ref{Shell Substitutions},
15750 item @samp{$@@}, for more.
15753 @item @command{if}
15754 @c ---------------
15755 @prindex @command{if}
15756 Using @samp{!} is not portable.  Instead of:
15758 @example
15759 if ! cmp -s file file.new; then
15760   mv file.new file
15762 @end example
15764 @noindent
15765 use:
15767 @example
15768 if cmp -s file file.new; then :; else
15769   mv file.new file
15771 @end example
15773 @noindent
15774 Or, especially if the @dfn{else} branch is short, you can use @code{||}.
15775 In M4sh, the @code{AS_IF} macro provides an easy way to write these kinds
15776 of conditionals:
15778 @example
15779 AS_IF([cmp -s file file.new], [], [mv file.new file])
15780 @end example
15782 This is especially useful in other M4 macros, where the @dfn{then} and
15783 @dfn{else} branches might be macro arguments.
15785 There are shells that do not reset the exit status from an @command{if}:
15787 @example
15788 $ @kbd{if (exit 42); then true; fi; echo $?}
15790 @end example
15792 @noindent
15793 whereas a proper shell should have printed @samp{0}.  This is especially
15794 bad in makefiles since it produces false failures.  This is why properly
15795 written makefiles, such as Automake's, have such hairy constructs:
15797 @example
15798 if test -f "$file"; then
15799   install "$file" "$dest"
15800 else
15801   :
15803 @end example
15806 @item @command{printf}
15807 @c ------------------
15808 @prindex @command{printf}
15809 A format string starting with a @samp{-} can cause problems.
15810 Bash interprets it as an option and
15811 gives an error.  And @samp{--} to mark the end of options is not good
15812 in the Net@acronym{BSD} Almquist shell (e.g., 0.4.6) which takes that
15813 literally as the format string.  Putting the @samp{-} in a @samp{%c}
15814 or @samp{%s} is probably easiest:
15816 @example
15817 printf %s -foo
15818 @end example
15820 Bash 2.03 mishandles an escape sequence that happens to evaluate to @samp{%}:
15822 @example
15823 $ @kbd{printf '\045'}
15824 bash: printf: `%': missing format character
15825 @end example
15827 Large outputs may cause trouble.  On Solaris 2.5.1 through 10, for
15828 example, @file{/usr/bin/printf} is buggy, so when using
15829 @command{/bin/sh} the command @samp{printf %010000x 123} normally dumps
15830 core.
15832 Since @command{printf} is not always a shell builtin, there is a
15833 potential speed penalty for using @code{printf %s\\n} as a replacement
15834 for an @command{echo} that does not interpret @samp{\} or leading
15835 @samp{-}. With Solaris @command{ksh}, it is possible to use @code{print
15836 -r --} for this role instead.
15839 @item @command{pwd}
15840 @c ----------------
15841 @prindex @command{pwd}
15842 With modern shells, plain @command{pwd} outputs a ``logical''
15843 directory name, some of whose components may be symbolic links.  These
15844 directory names are in contrast to ``physical'' directory names, whose
15845 components are all directories.
15847 Posix 1003.1-2001 requires that @command{pwd} must support
15848 the @option{-L} (``logical'') and @option{-P} (``physical'') options,
15849 with @option{-L} being the default.  However, traditional shells do
15850 not support these options, and their @command{pwd} command has the
15851 @option{-P} behavior.
15853 Portable scripts should assume neither option is supported, and should
15854 assume neither behavior is the default.  Also, on many hosts
15855 @samp{/bin/pwd} is equivalent to @samp{pwd -P}, but Posix
15856 does not require this behavior and portable scripts should not rely on
15859 Typically it's best to use plain @command{pwd}.  On modern hosts this
15860 outputs logical directory names, which have the following advantages:
15862 @itemize @bullet
15863 @item
15864 Logical names are what the user specified.
15865 @item
15866 Physical names may not be portable from one installation
15867 host to another due to network file system gymnastics.
15868 @item
15869 On modern hosts @samp{pwd -P} may fail due to lack of permissions to
15870 some parent directory, but plain @command{pwd} cannot fail for this
15871 reason.
15872 @end itemize
15874 Also please see the discussion of the @command{cd} command.
15877 @item @command{read}
15878 @c -----------------
15879 @prindex @command{read}
15880 No options are portable, not even support @option{-r} (Solaris
15881 @command{/bin/sh} for example).
15884 @anchor{set}
15885 @item @command{set}
15886 @c ----------------
15887 @prindex @command{set}
15888 With the Free@acronym{BSD} 6.0 shell, the @command{set} command (without
15889 any options) does not sort its output.
15891 The @command{set} builtin faces the usual problem with arguments
15892 starting with a
15893 dash.  Modern shells such as Bash or Zsh understand @option{--} to specify
15894 the end of the options (any argument after @option{--} is a parameter,
15895 even @samp{-x} for instance), but many traditional shells (e.g., Solaris
15896 10 @command{/bin/sh}) simply stop option
15897 processing as soon as a non-option argument is found.  Therefore, use
15898 @samp{dummy} or simply @samp{x} to end the option processing, and use
15899 @command{shift} to pop it out:
15901 @example
15902 set x $my_list; shift
15903 @end example
15905 Avoid @samp{set -}, e.g., @samp{set - $my_list}.  Posix no
15906 longer requires support for this command, and in traditional shells
15907 @samp{set - $my_list} resets the @option{-v} and @option{-x} options, which
15908 makes scripts harder to debug.
15910 Some nonstandard shells do not recognize more than one option
15911 (e.g., @samp{set -e -x} assigns @samp{-x} to the command line).  It is
15912 better to combine them:
15914 @example
15915 set -ex
15916 @end example
15918 The @acronym{BSD} shell has had several problems with the @option{-e}
15919 option, partly because @acronym{BSD} @command{make} traditionally used
15920 @option{-e} even though this was incompatible with Posix
15921 (@pxref{Failure in Make Rules}).  Older versions of the @acronym{BSD}
15922 shell (circa 1990) mishandled @samp{&&}, @samp{||}, @samp{if}, and
15923 @samp{case} when @option{-e} was in effect, causing the shell to exit
15924 unexpectedly in some cases.  This was particularly a problem with
15925 makefiles, and led to circumlocutions like @samp{sh -c 'test -f file ||
15926 touch file'}, where the seemingly-unnecessary @samp{sh -c '@dots{}'}
15927 wrapper works around the bug.
15929 Even relatively-recent versions of the @acronym{BSD} shell (e.g.,
15930 Open@acronym{BSD} 3.4) wrongly exit with @option{-e} if a command within
15931 @samp{&&} fails inside a compound statement.  For example:
15933 @example
15934 #! /bin/sh
15935 set -e
15936 foo=''
15937 test -n "$foo" && exit 1
15938 echo one
15939 if :; then
15940   test -n "$foo" && exit 1
15942 echo two
15943 @end example
15945 @noindent
15946 does not print @samp{two}.  One workaround is to use @samp{if test -n
15947 "$foo"; then exit 1; fi} rather than @samp{test -n "$foo" && exit 1}.
15948 Another possibility is to warn @acronym{BSD} users not to use @samp{sh -e}.
15950 Portable scripts should not use @samp{set -e} if @command{trap} is used
15951 to install an exit handler.  This is because Tru64/OSF 5.1 @command{sh}
15952 sometimes enters the trap handler with the exit status of the command
15953 prior to the one that triggered the errexit handler:
15955 @example
15956 $ @kbd{sh -ec 'trap '\''echo $?'\'' 0; false'}
15958 $ @kbd{sh -c 'set -e; trap '\''echo $?'\'' 0; false'}
15960 @end example
15962 @noindent
15963 Thus, when writing a script in M4sh, rather than trying to rely on
15964 @samp{set -e}, it is better to append @samp{|| AS_EXIT} to any
15965 statement where it is desirable to abort on failure.
15967 @item @command{shift}
15968 @c ------------------
15969 @prindex @command{shift}
15970 Not only is @command{shift}ing a bad idea when there is nothing left to
15971 shift, but in addition it is not portable: the shell of @acronym{MIPS
15972 RISC/OS} 4.52 refuses to do it.
15974 Don't use @samp{shift 2} etc.; while it in the SVR1 shell (1983),
15975 it is also absent in many pre-Posix shells.
15978 @item @command{source}
15979 @c -------------------
15980 @prindex @command{source}
15981 This command is not portable, as Posix does not require it; use
15982 @command{.} instead.
15985 @item @command{test}
15986 @c -----------------
15987 @prindex @command{test}
15988 The @code{test} program is the way to perform many file and string
15989 tests.  It is often invoked by the alternate name @samp{[}, but using
15990 that name in Autoconf code is asking for trouble since it is an M4 quote
15991 character.
15993 The @option{-a}, @option{-o}, @samp{(}, and @samp{)} operands are not
15994 portable and should be avoided.  Thus, portable uses of @command{test}
15995 should never have more than four arguments, and scripts should use shell
15996 constructs like @samp{&&} and @samp{||} instead.  If you combine
15997 @samp{&&} and @samp{||} in the same statement, keep in mind that they
15998 have equal precedence, so it is often better to parenthesize even when
15999 this is redundant.  For example:
16001 @smallexample
16002 # Not portable:
16003 test "X$a" = "X$b" -a \
16004   '(' "X$c" != "X$d" -o "X$e" = "X$f" ')'
16006 # Portable:
16007 test "X$a" = "X$b" &&
16008   @{ test "X$c" != "X$d" || test "X$e" = "X$f"; @}
16009 @end smallexample
16011 @command{test} does not process options like most other commands do; for
16012 example, it does not recognize the @option{--} argument as marking the
16013 end of options.
16015 It is safe to use @samp{!} as a @command{test} operator.  For example,
16016 @samp{if test ! -d foo; @dots{}} is portable even though @samp{if ! test
16017 -d foo; @dots{}} is not.
16020 @item @command{test} (files)
16021 @c -------------------------
16022 To enable @command{configure} scripts to support cross-compilation, they
16023 shouldn't do anything that tests features of the build system instead of
16024 the host system.  But occasionally you may find it necessary to check
16025 whether some arbitrary file exists.  To do so, use @samp{test -f} or
16026 @samp{test -r}.  Do not use @samp{test -x}, because 4.3@acronym{BSD} does not
16027 have it.  Do not use @samp{test -e} either, because Solaris @command{/bin/sh}
16028 lacks it.  To test for symbolic links on systems that have them, use
16029 @samp{test -h} rather than @samp{test -L}; either form conforms to
16030 Posix 1003.1-2001, but older shells like Solaris 8
16031 @code{/bin/sh} support only @option{-h}.
16033 @item @command{test} (strings)
16034 @c ---------------------------
16035 Posix says that @samp{test "@var{string}"} succeeds if @var{string} is
16036 not null, but this usage is not portable to traditional platforms like
16037 Solaris 10 @command{/bin/sh}, which mishandle strings like @samp{!} and
16038 @samp{-n}.
16040 Posix also says that @samp{test ! "@var{string}"},
16041 @samp{test -n "@var{string}"} and
16042 @samp{test -z "@var{string}"} work with any string, but many
16043 shells (such as Solaris, @acronym{AIX} 3.2, @sc{unicos} 10.0.0.6,
16044 Digital Unix 4, etc.)@: get confused if
16045 @var{string} looks like an operator:
16047 @example
16048 $ @kbd{test -n =}
16049 test: argument expected
16050 $ @kbd{test ! -n}
16051 test: argument expected
16052 @end example
16054 Similarly, Posix says that both @samp{test "@var{string1}" = "@var{string2"}}
16055 and @samp{test "@var{string1}" != "@var{string2"}} work for any pairs of
16056 strings, but in practice this is not true for troublesome strings that
16057 look like operators or parentheses, or that begin with @samp{-}.
16059 It is best to protect such strings with a leading @samp{X}, e.g.,
16060 @samp{test "X@var{string}" != X} rather than @samp{test -n
16061 "@var{string}"} or @samp{test ! "@var{string}"}.
16063 It is common to find variations of the following idiom:
16065 @example
16066 test -n "`echo $ac_feature | sed 's/[-a-zA-Z0-9_]//g'`" &&
16067   @var{action}
16068 @end example
16070 @noindent
16071 to take an action when a token matches a given pattern.  Such constructs
16072 should be avoided by using:
16074 @example
16075 case $ac_feature in
16076   *[!-a-zA-Z0-9_]*) @var{action};;
16077 esac
16078 @end example
16080 If the pattern is a complicated regular expression that cannot be
16081 expressed as a shell pattern, use something like this instead:
16083 @example
16084 expr "X$ac_feature" : 'X.*[^-a-zA-Z0-9_]' >/dev/null &&
16085   @var{action}
16086 @end example
16088 @samp{expr "X@var{foo}" : "X@var{bar}"} is more robust than @samp{echo
16089 "X@var{foo}" | grep "^X@var{bar}"}, because it avoids problems when
16090 @samp{@var{foo}} contains backslashes.
16093 @anchor{trap}
16094 @item @command{trap}
16095 @c -----------------
16096 @prindex @command{trap}
16097 It is safe to trap at least the signals 1, 2, 13, and 15.  You can also
16098 trap 0, i.e., have the @command{trap} run when the script ends (either via an
16099 explicit @command{exit}, or the end of the script).  The trap for 0 should be
16100 installed outside of a shell function, or @acronym{AIX} 5.3 @command{/bin/sh}
16101 will invoke the trap at the end of this function.
16103 Posix says that @samp{trap - 1 2 13 15} resets the traps for the
16104 specified signals to their default values, but many common shells (e.g.,
16105 Solaris @command{/bin/sh}) misinterpret this and attempt to execute a
16106 ``command'' named @command{-} when the specified conditions arise.
16107 There is no portable workaround, except for @samp{trap - 0}, for which
16108 @samp{trap '' 0} is a portable substitute.
16110 Although Posix is not absolutely clear on this point, it is widely
16111 admitted that when entering the trap @samp{$?} should be set to the exit
16112 status of the last command run before the trap.  The ambiguity can be
16113 summarized as: ``when the trap is launched by an @command{exit}, what is
16114 the @emph{last} command run: that before @command{exit}, or
16115 @command{exit} itself?''
16117 Bash considers @command{exit} to be the last command, while Zsh and
16118 Solaris @command{/bin/sh} consider that when the trap is run it is
16119 @emph{still} in the @command{exit}, hence it is the previous exit status
16120 that the trap receives:
16122 @example
16123 $ @kbd{cat trap.sh}
16124 trap 'echo $?' 0
16125 (exit 42); exit 0
16126 $ @kbd{zsh trap.sh}
16128 $ @kbd{bash trap.sh}
16130 @end example
16132 The portable solution is then simple: when you want to @samp{exit 42},
16133 run @samp{(exit 42); exit 42}, the first @command{exit} being used to
16134 set the exit status to 42 for Zsh, and the second to trigger the trap
16135 and pass 42 as exit status for Bash.  In M4sh, this is covered by using
16136 @code{AS_EXIT}.
16138 The shell in Free@acronym{BSD} 4.0 has the following bug: @samp{$?} is
16139 reset to 0 by empty lines if the code is inside @command{trap}.
16141 @example
16142 $ @kbd{trap 'false}
16144 echo $?' 0
16145 $ @kbd{exit}
16147 @end example
16149 @noindent
16150 Fortunately, this bug only affects @command{trap}.
16152 @item @command{true}
16153 @c -----------------
16154 @prindex @command{true}
16155 @c Info cannot handle `:' in index entries.
16156 @c @prindex @command{:}
16157 Don't worry: as far as we know @command{true} is portable.
16158 Nevertheless, it's not always a builtin (e.g., Bash 1.x), and the
16159 portable shell community tends to prefer using @command{:}.  This has a
16160 funny side effect: when asked whether @command{false} is more portable
16161 than @command{true} Alexandre Oliva answered:
16163 @quotation
16164 In a sense, yes, because if it doesn't exist, the shell will produce an
16165 exit status of failure, which is correct for @command{false}, but not
16166 for @command{true}.
16167 @end quotation
16170 @anchor{unset}
16171 @item @command{unset}
16172 @c ------------------
16173 @prindex @command{unset}
16174 In some nonconforming shells (e.g., Bash 2.05a), @code{unset FOO} fails
16175 when @code{FOO} is not set.  You can use
16177 @smallexample
16178 FOO=; unset FOO
16179 @end smallexample
16181 if you are not sure that @code{FOO} is set.
16183 A few ancient shells lack @command{unset} entirely.  For some variables
16184 such as @code{PS1}, you can use a neutralizing value instead:
16186 @smallexample
16187 PS1='$ '
16188 @end smallexample
16190 Usually, shells that do not support @command{unset} need less effort to
16191 make the environment sane, so for example is not a problem if you cannot
16192 unset @command{CDPATH} on those shells.  However, Bash 2.01 mishandles
16193 @code{unset MAIL} in some cases and dumps core.  So, you should do
16194 something like
16196 @smallexample
16197 ( (unset MAIL) || exit 1) >/dev/null 2>&1 && unset MAIL || :
16198 @end smallexample
16200 @noindent
16201 @xref{Special Shell Variables}, for some neutralizing values.  Also, see
16202 @ref{export, , Limitations of Builtins}, for
16203 the case of environment variables.
16205 @item @command{wait}
16206 @c -----------------
16207 @prindex @command{wait}
16208 The exit status of @command{wait} is not always reliable.
16209 @end table
16211 @node Limitations of Usual Tools
16212 @section Limitations of Usual Tools
16213 @cindex Limitations of usual tools
16215 The small set of tools you can expect to find on any machine can still
16216 include some limitations you should be aware of.
16218 @comment Between this list and the list of builtins above, we should
16219 @comment mention all the tools in GNU Coding Standards ``Utilities in
16220 @comment Makefiles''.
16222 @c This table includes things like `@command{expr} (|)', so we can't
16223 @c use @table @command.
16224 @table @asis
16225 @item @command{awk}
16226 @c ----------------
16227 @prindex @command{awk}
16228 Don't leave white space before the opening parenthesis in a user function call.
16229 Posix does not allow this and @acronym{GNU} Awk rejects it:
16231 @example
16232 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
16233         BEGIN @{ die () @}'}
16234 gawk: cmd. line:2:         BEGIN @{ die () @}
16235 gawk: cmd. line:2:                      ^ parse error
16236 $ @kbd{gawk 'function die () @{ print "Aaaaarg!"  @}
16237         BEGIN @{ die() @}'}
16238 Aaaaarg!
16239 @end example
16241 Posix says that if a program contains only @samp{BEGIN} actions, and
16242 contains no instances of @code{getline}, then the program merely
16243 executes the actions without reading input.  However, traditional Awk
16244 implementations (such as Solaris 10 @command{awk}) read and discard
16245 input in this case.  Portable scripts can redirect input from
16246 @file{/dev/null} to work around the problem.  For example:
16248 @example
16249 awk 'BEGIN @{print "hello world"@}' </dev/null
16250 @end example
16252 Posix says that in an @samp{END} action, @samp{$NF} (and presumably,
16253 @samp{$1}) retain their value from the last record read, if no
16254 intervening @samp{getline} occurred.  However, some implementations
16255 (such as Solaris 10 @samp{/usr/bin/awk}, @samp{nawk}, or Darwin
16256 @samp{awk}) reset these variables.  A workaround is to use an
16257 intermediate variable prior to the @samp{END} block.  For example:
16259 @example
16260 $ @kbd{cat end.awk}
16261 @{ tmp = $1 @}
16262 END @{ print "a", $1, $NF, "b", tmp @}
16263 $ @kbd{echo 1 | awk -f end.awk}
16264 a   b 1
16265 $ @kbd{echo 1 | gawk -f end.awk}
16266 a 1 1 b 1
16267 @end example
16269 If you want your program to be deterministic, don't depend on @code{for}
16270 on arrays:
16272 @example
16273 $ @kbd{cat for.awk}
16274 END @{
16275   arr["foo"] = 1
16276   arr["bar"] = 1
16277   for (i in arr)
16278     print i
16280 $ @kbd{gawk -f for.awk </dev/null}
16283 $ @kbd{nawk -f for.awk </dev/null}
16286 @end example
16288 Some Awk implementations, such as @acronym{HP-UX} 11.0's native one,
16289 mishandle anchors:
16291 @example
16292 $ @kbd{echo xfoo | $AWK '/foo|^bar/ @{ print @}'}
16293 $ @kbd{echo bar | $AWK '/foo|^bar/ @{ print @}'}
16295 $ @kbd{echo xfoo | $AWK '/^bar|foo/ @{ print @}'}
16296 xfoo
16297 $ @kbd{echo bar | $AWK '/^bar|foo/ @{ print @}'}
16299 @end example
16301 @noindent
16302 Either do not depend on such patterns (i.e., use @samp{/^(.*foo|bar)/},
16303 or use a simple test to reject such implementations.
16305 On @samp{ia64-hp-hpux11.23}, Awk mishandles @code{printf} conversions
16306 after @code{%u}:
16308 @example
16309 $ @kbd{awk 'BEGIN @{ printf "%u %d\n", 0, -1 @}'}
16310 0 0
16311 @end example
16313 @acronym{AIX} version 5.2 has an arbitrary limit of 399 on the
16314 length of regular expressions and literal strings in an Awk program.
16316 Traditional Awk implementations derived from Unix version 7, such as
16317 Solaris @command{/bin/awk}, have many limitations and do not
16318 conform to Posix.  Nowadays @code{AC_PROG_AWK} (@pxref{Particular
16319 Programs}) finds you an Awk that doesn't have these problems, but if
16320 for some reason you prefer not to use @code{AC_PROG_AWK} you may need to
16321 address them.
16323 Traditional Awk does not support multidimensional arrays or user-defined
16324 functions.
16326 Traditional Awk does not support the @option{-v} option.  You can use
16327 assignments after the program instead, e.g., @code{$AWK '@{print v
16328 $1@}' v=x}; however, don't forget that such assignments are not
16329 evaluated until they are encountered (e.g., after any @code{BEGIN}
16330 action).
16332 Traditional Awk does not support the keywords @code{delete} or @code{do}.
16334 Traditional Awk does not support the expressions
16335 @code{@var{a}?@var{b}:@var{c}}, @code{!@var{a}}, @code{@var{a}^@var{b}},
16336 or @code{@var{a}^=@var{b}}.
16338 Traditional Awk does not support the predefined @code{CONVFMT} variable.
16340 Traditional Awk supports only the predefined functions @code{exp}, @code{index},
16341 @code{int}, @code{length}, @code{log}, @code{split}, @code{sprintf},
16342 @code{sqrt}, and @code{substr}.
16344 Traditional Awk @code{getline} is not at all compatible with Posix;
16345 avoid it.
16347 Traditional Awk has @code{for (i in a) @dots{}} but no other uses of the
16348 @code{in} keyword.  For example, it lacks @code{if (i in a) @dots{}}.
16350 In code portable to both traditional and modern Awk, @code{FS} must be a
16351 string containing just one ordinary character, and similarly for the
16352 field-separator argument to @code{split}.
16354 Traditional Awk has a limit of 99 fields in a record.  Since some Awk
16355 implementations, like Tru64's, split the input even if you don't refer
16356 to any field in the script, to circumvent this problem, set @samp{FS}
16357 to an unusual character and use @code{split}.
16359 Traditional Awk has a limit of at most 99 bytes in a number formatted by
16360 @code{OFMT}; for example, @code{OFMT="%.300e"; print 0.1;} typically
16361 dumps core.
16363 The original version of Awk had a limit of at most 99 bytes per
16364 @code{split} field, 99 bytes per @code{substr} substring, and 99 bytes
16365 per run of non-special characters in a @code{printf} format, but these
16366 bugs have been fixed on all practical hosts that we know of.
16368 @item @command{basename}
16369 @c ---------------------
16370 @prindex @command{basename}
16371 Not all hosts have a working @command{basename}.
16372 You can use @command{expr} instead.
16374 @c AS_BASENAME is to be replaced by a better API.
16375 @ignore
16376 Not all hosts have a working @command{basename}, and you should instead
16377 use @code{AS_BASENAME} (@pxref{Programming in M4sh}), followed by
16378 @command{expr} if you need to strip a suffix.  For example:
16380 @example
16381 a=`basename "$aname"`       # This is not portable.
16382 a=`AS_BASENAME(["$aname"])` # This is more portable.
16384 # This is not portable.
16385 c=`basename "$cname" .c`
16387 # This is more portable.
16388 c=`AS_BASENAME(["$cname"])`
16389 case $c in
16390 ?*.c) c=`expr "X$c" : 'X\(.*\)\.c'`;;
16391 esac
16392 @end example
16393 @end ignore
16396 @item @command{cat}
16397 @c ----------------
16398 @prindex @command{cat}
16399 Don't rely on any option.
16402 @item @command{cc}
16403 @c ---------------
16404 @prindex @command{cc}
16405 The command @samp{cc -c foo.c} traditionally produces an object file
16406 named @file{foo.o}.  Most compilers allow @option{-c} to be combined
16407 with @option{-o} to specify a different object file name, but
16408 Posix does not require this combination and a few compilers
16409 lack support for it.  @xref{C Compiler}, for how @acronym{GNU} Make
16410 tests for this feature with @code{AC_PROG_CC_C_O}.
16412 When a compilation such as @samp{cc -o foo foo.c} fails, some compilers
16413 (such as @sc{cds} on Reliant Unix) leave a @file{foo.o}.
16415 @acronym{HP-UX} @command{cc} doesn't accept @file{.S} files to preprocess and
16416 assemble.  @samp{cc -c foo.S} appears to succeed, but in fact does
16417 nothing.
16419 The default executable, produced by @samp{cc foo.c}, can be
16421 @itemize
16422 @item @file{a.out} --- usual Posix convention.
16423 @item @file{b.out} --- i960 compilers (including @command{gcc}).
16424 @item @file{a.exe} --- @acronym{DJGPP} port of @command{gcc}.
16425 @item @file{a_out.exe} --- GNV @command{cc} wrapper for DEC C on OpenVMS.
16426 @item @file{foo.exe} --- various MS-DOS compilers.
16427 @end itemize
16429 The C compiler's traditional name is @command{cc}, but other names like
16430 @command{gcc} are common.  Posix 1003.1-2001 specifies the
16431 name @command{c99}, but older Posix editions specified
16432 @command{c89} and anyway these standard names are rarely used in
16433 practice.  Typically the C compiler is invoked from makefiles that use
16434 @samp{$(CC)}, so the value of the @samp{CC} make variable selects the
16435 compiler name.
16437 @item @command{chgrp}
16438 @itemx @command{chown}
16439 @c -------------------
16440 @prindex @command{chgrp}
16441 @prindex @command{chown}
16442 It is not portable to change a file's group to a group that the owner
16443 does not belong to.
16445 @item @command{chmod}
16446 @c ------------------
16447 @prindex @command{chmod}
16448 Avoid usages like @samp{chmod -w file}; use @samp{chmod a-w file}
16449 instead, for two reasons.  First, plain @option{-w} does not necessarily
16450 make the file unwritable, since it does not affect mode bits that
16451 correspond to bits in the file mode creation mask.  Second,
16452 Posix says that the @option{-w} might be interpreted as an
16453 implementation-specific option, not as a mode; Posix suggests
16454 using @samp{chmod -- -w file} to avoid this confusion, but unfortunately
16455 @samp{--} does not work on some older hosts.
16458 @item @command{cmp}
16459 @c ----------------
16460 @prindex @command{cmp}
16461 @command{cmp} performs a raw data comparison of two files, while
16462 @command{diff} compares two text files.  Therefore, if you might compare
16463 DOS files, even if only checking whether two files are different, use
16464 @command{diff} to avoid spurious differences due to differences of
16465 newline encoding.
16468 @item @command{cp}
16469 @c ---------------
16470 @prindex @command{cp}
16471 Avoid the @option{-r} option, since Posix 1003.1-2004 marks it as
16472 obsolescent and its behavior on special files is implementation-defined.
16473 Use @option{-R} instead.  On @acronym{GNU} hosts the two options
16474 are equivalent, but on Solaris hosts (for example) @code{cp -r}
16475 reads from pipes instead of replicating them.
16477 Some @command{cp} implementations (e.g., @acronym{BSD/OS} 4.2) do not allow
16478 trailing slashes at the end of nonexistent destination directories.  To
16479 avoid this problem, omit the trailing slashes.  For example, use
16480 @samp{cp -R source /tmp/newdir} rather than @samp{cp -R source
16481 /tmp/newdir/} if @file{/tmp/newdir} does not exist.
16483 @c This is thanks to Ian.
16484 The ancient SunOS 4 @command{cp} does not support @option{-f}, although
16485 its @command{mv} does.
16487 @cindex timestamp resolution
16488 Traditionally, file timestamps had 1-second resolution, and @samp{cp
16489 -p} copied the timestamps exactly.  However, many modern file systems
16490 have timestamps with 1-nanosecond resolution.  Unfortunately, @samp{cp
16491 -p} implementations truncate timestamps when copying files, so this
16492 can result in the destination file appearing to be older than the
16493 source.  The exact amount of truncation depends on the resolution of
16494 the system calls that @command{cp} uses; traditionally this was
16495 @code{utime}, which has 1-second resolution, but some newer
16496 @command{cp} implementations use @code{utimes}, which has
16497 1-microsecond resolution.  These newer implementations include @acronym{GNU}
16498 Core Utilities 5.0.91 or later, and Solaris 8 (sparc) patch 109933-02 or
16499 later.  Unfortunately as of January 2006 there is still no system
16500 call to set timestamps to the full nanosecond resolution.
16502 Bob Proulx notes that @samp{cp -p} always @emph{tries} to copy
16503 ownerships.  But whether it actually does copy ownerships or not is a
16504 system dependent policy decision implemented by the kernel.  If the
16505 kernel allows it then it happens.  If the kernel does not allow it then
16506 it does not happen.  It is not something @command{cp} itself has control
16507 over.
16509 In Unix System V any user can chown files to any other user, and System
16510 V also has a non-sticky @file{/tmp}.  That probably derives from the
16511 heritage of System V in a business environment without hostile users.
16512 @acronym{BSD} changed this
16513 to be a more secure model where only root can @command{chown} files and
16514 a sticky @file{/tmp} is used.  That undoubtedly derives from the heritage
16515 of @acronym{BSD} in a campus environment.
16517 @acronym{GNU}/Linux and Solaris by default follow @acronym{BSD}, but
16518 can be configured to allow a System V style @command{chown}.  On the
16519 other hand, @acronym{HP-UX} follows System V, but can
16520 be configured to use the modern security model and disallow
16521 @command{chown}.  Since it is an administrator-configurable parameter
16522 you can't use the name of the kernel as an indicator of the behavior.
16526 @item @command{date}
16527 @c -----------------
16528 @prindex @command{date}
16529 Some versions of @command{date} do not recognize special @samp{%} directives,
16530 and unfortunately, instead of complaining, they just pass them through,
16531 and exit with success:
16533 @example
16534 $ @kbd{uname -a}
16535 OSF1 medusa.sis.pasteur.fr V5.1 732 alpha
16536 $ @kbd{date "+%s"}
16538 @end example
16541 @item @command{diff}
16542 @c -----------------
16543 @prindex @command{diff}
16544 Option @option{-u} is nonportable.
16546 Some implementations, such as Tru64's, fail when comparing to
16547 @file{/dev/null}.  Use an empty file instead.
16550 @item @command{dirname}
16551 @c --------------------
16552 @prindex @command{dirname}
16553 Not all hosts have a working @command{dirname}, and you should instead
16554 use @code{AS_DIRNAME} (@pxref{Programming in M4sh}).  For example:
16556 @example
16557 dir=`dirname "$file"`       # This is not portable.
16558 dir=`AS_DIRNAME(["$file"])` # This is more portable.
16559 @end example
16562 @item @command{egrep}
16563 @c ------------------
16564 @prindex @command{egrep}
16565 Posix 1003.1-2001 no longer requires @command{egrep},
16566 but many hosts do not yet support the Posix
16567 replacement @code{grep -E}.  Also, some traditional implementations do
16568 not work on long input lines.  To work around these problems, invoke
16569 @code{AC_PROG_EGREP} and then use @code{$EGREP}.
16571 Portable extended regular expressions should use @samp{\} only to escape
16572 characters in the string @samp{$()*+.?[\^@{|}.  For example, @samp{\@}}
16573 is not portable, even though it typically matches @samp{@}}.
16575 The empty alternative is not portable.  Use @samp{?} instead.  For
16576 instance with Digital Unix v5.0:
16578 @example
16579 > printf "foo\n|foo\n" | $EGREP '^(|foo|bar)$'
16580 |foo
16581 > printf "bar\nbar|\n" | $EGREP '^(foo|bar|)$'
16582 bar|
16583 > printf "foo\nfoo|\n|bar\nbar\n" | $EGREP '^(foo||bar)$'
16585 |bar
16586 @end example
16588 @command{$EGREP} also suffers the limitations of @command{grep}
16589 (@pxref{grep, , Limitations of Usual Tools}).
16591 @item @command{expr}
16592 @c -----------------
16593 @prindex @command{expr}
16594 Not all implementations obey the Posix rule that @samp{--} separates
16595 options from arguments; likewise, not all implementations provide the
16596 extension to Posix that the first argument can be treated as part of a
16597 valid expression rather than an invalid option if it begins with
16598 @samp{-}.  When performing arithmetic, use @samp{expr 0 + $var} if
16599 @samp{$var} might be a negative number, to keep @command{expr} from
16600 interpreting it as an option.
16602 No @command{expr} keyword starts with @samp{X}, so use @samp{expr
16603 X"@var{word}" : 'X@var{regex}'} to keep @command{expr} from
16604 misinterpreting @var{word}.
16606 Don't use @code{length}, @code{substr}, @code{match} and @code{index}.
16608 @item @command{expr} (@samp{|})
16609 @prindex @command{expr} (@samp{|})
16610 You can use @samp{|}.  Although Posix does require that @samp{expr
16611 ''} return the empty string, it does not specify the result when you
16612 @samp{|} together the empty string (or zero) with the empty string.  For
16613 example:
16615 @example
16616 expr '' \| ''
16617 @end example
16619 Posix 1003.2-1992 returns the empty string
16620 for this case, but traditional Unix returns @samp{0} (Solaris is
16621 one such example).  In Posix 1003.1-2001, the specification was
16622 changed to match traditional Unix's behavior (which is
16623 bizarre, but it's too late to fix this).  Please note that the same
16624 problem does arise when the empty string results from a computation,
16625 as in:
16627 @example
16628 expr bar : foo \| foo : bar
16629 @end example
16631 @noindent
16632 Avoid this portability problem by avoiding the empty string.
16635 @item @command{expr} (@samp{:})
16636 @c ----------------------------
16637 @prindex @command{expr}
16638 Portable @command{expr} regular expressions should use @samp{\} to
16639 escape only characters in the string @samp{$()*.0123456789[\^n@{@}}.
16640 For example, alternation, @samp{\|}, is common but Posix does not
16641 require its support, so it should be avoided in portable scripts.
16642 Similarly, @samp{\+} and @samp{\?} should be avoided.
16644 Portable @command{expr} regular expressions should not begin with
16645 @samp{^}.  Patterns are automatically anchored so leading @samp{^} is
16646 not needed anyway.
16648 The Posix standard is ambiguous as to whether
16649 @samp{expr 'a' : '\(b\)'} outputs @samp{0} or the empty string.
16650 In practice, it outputs the empty string on most platforms, but portable
16651 scripts should not assume this.  For instance, the @acronym{QNX} 4.25 native
16652 @command{expr} returns @samp{0}.
16654 One might think that a way to get a uniform behavior would be to use
16655 the empty string as a default value:
16657 @example
16658 expr a : '\(b\)' \| ''
16659 @end example
16661 @noindent
16662 Unfortunately this behaves exactly as the original expression; see the
16663 @command{expr} (@samp{|}) entry for more information.
16665 Some ancient @command{expr} implementations (e.g., SunOS 4 @command{expr} and
16666 Solaris 8 @command{/usr/ucb/expr}) have a silly length limit that causes
16667 @command{expr} to fail if the matched substring is longer than 120
16668 bytes.  In this case, you might want to fall back on @samp{echo|sed} if
16669 @command{expr} fails.  Nowadays this is of practical importance only for
16670 the rare installer who mistakenly puts @file{/usr/ucb} before
16671 @file{/usr/bin} in @env{PATH}.
16673 On Mac OS X 10.4, @command{expr} mishandles the pattern @samp{[^-]} in
16674 some cases.  For example, the command
16675 @example
16676 expr Xpowerpc-apple-darwin8.1.0 : 'X[^-]*-[^-]*-\(.*\)'
16677 @end example
16679 @noindent
16680 outputs @samp{apple-darwin8.1.0} rather than the correct @samp{darwin8.1.0}.
16681 This particular case can be worked around by substituting @samp{[^--]}
16682 for @samp{[^-]}.
16684 Don't leave, there is some more!
16686 The @acronym{QNX} 4.25 @command{expr}, in addition of preferring @samp{0} to
16687 the empty string, has a funny behavior in its exit status: it's always 1
16688 when parentheses are used!
16690 @example
16691 $ @kbd{val=`expr 'a' : 'a'`; echo "$?: $val"}
16692 0: 1
16693 $ @kbd{val=`expr 'a' : 'b'`; echo "$?: $val"}
16694 1: 0
16696 $ @kbd{val=`expr 'a' : '\(a\)'`; echo "?: $val"}
16697 1: a
16698 $ @kbd{val=`expr 'a' : '\(b\)'`; echo "?: $val"}
16699 1: 0
16700 @end example
16702 @noindent
16703 In practice this can be a big problem if you are ready to catch failures
16704 of @command{expr} programs with some other method (such as using
16705 @command{sed}), since you may get twice the result.  For instance
16707 @example
16708 $ @kbd{expr 'a' : '\(a\)' || echo 'a' | sed 's/^\(a\)$/\1/'}
16709 @end example
16711 @noindent
16712 outputs @samp{a} on most hosts, but @samp{aa} on @acronym{QNX} 4.25.  A
16713 simple workaround consists of testing @command{expr} and using a variable
16714 set to @command{expr} or to @command{false} according to the result.
16716 Tru64 @command{expr} incorrectly treats the result as a number, if it
16717 can be interpreted that way:
16719 @example
16720 $ @kbd{expr 00001 : '.*\(...\)'}
16722 @end example
16725 @item @command{fgrep}
16726 @c ------------------
16727 @prindex @command{fgrep}
16728 Posix 1003.1-2001 no longer requires @command{fgrep},
16729 but many hosts do not yet support the Posix
16730 replacement @code{grep -F}.  Also, some traditional implementations do
16731 not work on long input lines.  To work around these problems, invoke
16732 @code{AC_PROG_FGREP} and then use @code{$FGREP}.
16735 @item @command{find}
16736 @c -----------------
16737 @prindex @command{find}
16738 The option @option{-maxdepth} seems to be @acronym{GNU} specific.
16739 Tru64 v5.1, Net@acronym{BSD} 1.5 and Solaris @command{find}
16740 commands do not understand it.
16742 The replacement of @samp{@{@}} is guaranteed only if the argument is
16743 exactly @emph{@{@}}, not if it's only a part of an argument.  For
16744 instance on DU, and @acronym{HP-UX} 10.20 and @acronym{HP-UX} 11:
16746 @example
16747 $ @kbd{touch foo}
16748 $ @kbd{find . -name foo -exec echo "@{@}-@{@}" \;}
16749 @{@}-@{@}
16750 @end example
16752 @noindent
16753 while @acronym{GNU} @command{find} reports @samp{./foo-./foo}.
16756 @anchor{grep}
16757 @item @command{grep}
16758 @c -----------------
16759 @prindex @command{grep}
16760 Portable scripts can rely on the @command{grep} options @option{-c},
16761 @option{-l}, @option{-n}, and @option{-v}, but should avoid other
16762 options.  For example, don't use @option{-w}, as Posix does not require
16763 it and Irix 6.5.16m's @command{grep} does not support it.  Also,
16764 portable scripts should not combine @option{-c} with @option{-l},
16765 as Posix does not allow this.
16767 Some of the options required by Posix are not portable in practice.
16768 Don't use @samp{grep -q} to suppress output, because many @command{grep}
16769 implementations (e.g., Solaris) do not support @option{-q}.
16770 Don't use @samp{grep -s} to suppress output either, because Posix
16771 says @option{-s} does not suppress output, only some error messages;
16772 also, the @option{-s} option of traditional @command{grep} behaved
16773 like @option{-q} does in most modern implementations.  Instead,
16774 redirect the standard output and standard error (in case the file
16775 doesn't exist) of @code{grep} to @file{/dev/null}.  Check the exit
16776 status of @code{grep} to determine whether it found a match.
16778 Some traditional @command{grep} implementations do not work on long
16779 input lines.  On AIX the default @code{grep} silently truncates long
16780 lines on the input before matching.
16782 Also, many implementations do not support multiple regexps
16783 with @option{-e}: they either reject @option{-e} entirely (e.g., Solaris)
16784 or honor only the last pattern (e.g., @acronym{IRIX} 6.5 and NeXT).  To
16785 work around these problems, invoke @code{AC_PROG_GREP} and then use
16786 @code{$GREP}.
16788 Another possible workaround for the multiple @option{-e} problem is to
16789 separate the patterns by newlines, for example:
16791 @example
16792 grep 'foo
16793 bar' in.txt
16794 @end example
16796 @noindent
16797 except that this fails with traditional @command{grep}
16798 implementations and with Open@acronym{BSD} 3.8 @command{grep}.
16800 Traditional @command{grep} implementations (e.g., Solaris) do not
16801 support the @option{-E} or @option{-F} options.  To work around these
16802 problems, invoke @code{AC_PROG_EGREP} and then use @code{$EGREP}, and
16803 similarly for @code{AC_PROG_FGREP} and @code{$FGREP}.  Even if you are
16804 willing to require support for Posix @command{grep}, your script should
16805 not use both @option{-E} and @option{-F}, since Posix does not allow
16806 this combination.
16808 Portable @command{grep} regular expressions should use @samp{\} only to
16809 escape characters in the string @samp{$()*.0123456789[\^@{@}}.  For example,
16810 alternation, @samp{\|}, is common but Posix does not require its
16811 support in basic regular expressions, so it should be avoided in
16812 portable scripts.  Solaris and HP-UX @command{grep} do not support it.
16813 Similarly, the following escape sequences should also be avoided:
16814 @samp{\<}, @samp{\>}, @samp{\+}, @samp{\?}, @samp{\`}, @samp{\'},
16815 @samp{\B}, @samp{\b}, @samp{\S}, @samp{\s}, @samp{\W}, and @samp{\w}.
16817 Posix does not specify the behavior of @command{grep} on binary files.
16818 An example where this matters is using @acronym{BSD} @command{grep} to
16819 search text that includes embedded @acronym{ANSI} escape sequences for
16820 colored output to terminals (@samp{\033[m} is the sequence to restore
16821 normal output); the behavior depends on whether input is seekable:
16823 @example
16824 $ @kbd{printf 'esc\033[mape\n' > sample}
16825 $ @kbd{grep . sample}
16826 Binary file sample matches
16827 $ @kbd{cat sample | grep .}
16828 escape
16829 @end example
16832 @item @command{join}
16833 @c -----------------
16834 @prindex @command{join}
16835 Solaris 8 @command{join} has bugs when the second operand is standard
16836 input, and when standard input is a pipe.  For example, the following
16837 shell script causes Solaris 8 @command{join} to loop forever:
16839 @example
16840 cat >file <<'EOF'
16841 1 x
16842 2 y
16844 cat file | join file -
16845 @end example
16847 Use @samp{join - file} instead.
16850 @item @command{ln}
16851 @c ---------------
16852 @prindex @command{ln}
16853 @cindex Symbolic links
16854 Don't rely on @command{ln} having a @option{-f} option.  Symbolic links
16855 are not available on old systems; use @samp{$(LN_S)} as a portable substitute.
16857 For versions of the @acronym{DJGPP} before 2.04,
16858 @command{ln} emulates symbolic links
16859 to executables by generating a stub that in turn calls the real
16860 program.  This feature also works with nonexistent files like in the
16861 Posix spec.  So @samp{ln -s file link} generates @file{link.exe},
16862 which attempts to call @file{file.exe} if run.  But this feature only
16863 works for executables, so @samp{cp -p} is used instead for these
16864 systems.  @acronym{DJGPP} versions 2.04 and later have full support
16865 for symbolic links.
16868 @item @command{ls}
16869 @c ---------------
16870 @prindex @command{ls}
16871 @cindex Listing directories
16872 The portable options are @option{-acdilrtu}.  Current practice is for
16873 @option{-l} to output both owner and group, even though ancient versions
16874 of @command{ls} omitted the group.
16876 On ancient hosts, @samp{ls foo} sent the diagnostic @samp{foo not found}
16877 to standard output if @file{foo} did not exist.  Hence a shell command
16878 like @samp{sources=`ls *.c 2>/dev/null`} did not always work, since it
16879 was equivalent to @samp{sources='*.c not found'} in the absence of
16880 @samp{.c} files.  This is no longer a practical problem, since current
16881 @command{ls} implementations send diagnostics to standard error.
16883 The behavior of @command{ls} on a directory that is being concurrently
16884 modified is not always predictable, because of a data race where cached
16885 information returned by @code{readdir} does not match the current
16886 directory state.  In fact, MacOS 10.5 has an intermittent bug where
16887 @code{readdir}, and thus @command{ls}, sometimes lists a file more than
16888 once if other files were added or removed from the directory immediately
16889 prior to the @command{ls} call.  Since @command{ls} already sorts its
16890 output, the duplicate entries can be avoided by piping the results
16891 through @code{uniq}.
16893 @anchor{mkdir}
16894 @item @command{mkdir}
16895 @c ------------------
16896 @prindex @command{mkdir}
16897 @cindex Making directories
16898 No @command{mkdir} option is portable to older systems.  Instead of
16899 @samp{mkdir -p @var{file-name}}, you should use
16900 @code{AS_MKDIR_P(@var{file-name})} (@pxref{Programming in M4sh})
16901 or @code{AC_PROG_MKDIR_P} (@pxref{Particular Programs}).
16903 Combining the @option{-m} and @option{-p} options, as in @samp{mkdir -m
16904 go-w -p @var{dir}}, often leads to trouble.  Free@acronym{BSD}
16905 @command{mkdir} incorrectly attempts to change the permissions of
16906 @var{dir} even if it already exists.  @acronym{HP-UX} 11.23 and
16907 @acronym{IRIX} 6.5 @command{mkdir} often assign the wrong permissions to
16908 any newly-created parents of @var{dir}.
16910 Posix does not clearly specify whether @samp{mkdir -p foo}
16911 should succeed when @file{foo} is a symbolic link to an already-existing
16912 directory.  The @acronym{GNU} Core Utilities 5.1.0 @command{mkdir}
16913 succeeds, but Solaris @command{mkdir} fails.
16915 Traditional @code{mkdir -p} implementations suffer from race conditions.
16916 For example, if you invoke @code{mkdir -p a/b} and @code{mkdir -p a/c}
16917 at the same time, both processes might detect that @file{a} is missing,
16918 one might create @file{a}, then the other might try to create @file{a}
16919 and fail with a @code{File exists} diagnostic.  The @acronym{GNU} Core
16920 Utilities (@samp{fileutils} version 4.1), Free@acronym{BSD} 5.0,
16921 Net@acronym{BSD} 2.0.2, and Open@acronym{BSD} 2.4 are known to be
16922 race-free when two processes invoke @code{mkdir -p} simultaneously, but
16923 earlier versions are vulnerable.  Solaris @command{mkdir} is still
16924 vulnerable as of Solaris 10, and other traditional Unix systems are
16925 probably vulnerable too.  This possible race is harmful in parallel
16926 builds when several Make rules call @code{mkdir -p} to
16927 construct directories.  You may use
16928 @code{install-sh -d} as a safe replacement, provided this script is
16929 recent enough; the copy shipped with Autoconf 2.60 and Automake 1.10 is
16930 OK, but copies from older versions are vulnerable.
16933 @item @command{mkfifo}
16934 @itemx @command{mknod}
16935 @c -------------------
16936 @prindex @command{mkfifo}
16937 @prindex @command{mknod}
16938 The GNU Coding Standards state that @command{mknod} is safe to use on
16939 platforms where it has been tested to exist; but it is generally portable
16940 only for creating named FIFOs, since device numbers are
16941 platform-specific.  Autotest uses @command{mkfifo} to implement parallel
16942 testsuites.  Posix states that behavior is unspecified when opening a
16943 named FIFO for both reading and writing; on at least Cygwin, this
16944 results in failure on any attempt to read or write to that file
16945 descriptor.
16947 @item @command{mktemp}
16948 @c -------------------
16949 @prindex @command{mktemp}
16950 @cindex Creating temporary files
16951 Shell scripts can use temporary files safely with @command{mktemp}, but
16952 it does not exist on all systems.  A portable way to create a safe
16953 temporary file name is to create a temporary directory with mode 700 and
16954 use a file inside this directory.  Both methods prevent attackers from
16955 gaining control, though @command{mktemp} is far less likely to fail
16956 gratuitously under attack.
16958 Here is sample code to create a new temporary directory safely:
16960 @example
16961 # Create a temporary directory $tmp in $TMPDIR (default /tmp).
16962 # Use mktemp if possible; otherwise fall back on mkdir,
16963 # with $RANDOM to make collisions less likely.
16964 : $@{TMPDIR=/tmp@}
16966   tmp=`
16967     (umask 077 && mktemp -d "$TMPDIR/fooXXXXXX") 2>/dev/null
16968   ` &&
16969   test -n "$tmp" && test -d "$tmp"
16970 @} || @{
16971   tmp=$TMPDIR/foo$$-$RANDOM
16972   (umask 077 && mkdir "$tmp")
16973 @} || exit $?
16974 @end example
16977 @item @command{mv}
16978 @c ---------------
16979 @prindex @command{mv}
16980 @cindex Moving open files
16981 The only portable options are @option{-f} and @option{-i}.
16983 Moving individual files between file systems is portable (it was in Unix
16984 version 6),
16985 but it is not always atomic: when doing @samp{mv new existing}, there's
16986 a critical section where neither the old nor the new version of
16987 @file{existing} actually exists.
16989 On some systems moving files from @file{/tmp} can sometimes cause
16990 undesirable (but perfectly valid) warnings, even if you created these
16991 files.  This is because @file{/tmp} belongs to a group that ordinary
16992 users are not members of, and files created in @file{/tmp} inherit
16993 the group of @file{/tmp}.  When the file is copied, @command{mv} issues
16994 a diagnostic without failing:
16996 @smallexample
16997 $ @kbd{touch /tmp/foo}
16998 $ @kbd{mv /tmp/foo .}
16999 @error{}mv: ./foo: set owner/group (was: 100/0): Operation not permitted
17000 $ @kbd{echo $?}
17002 $ @kbd{ls foo}
17004 @end smallexample
17006 @noindent
17007 This annoying behavior conforms to Posix, unfortunately.
17009 Moving directories across mount points is not portable, use @command{cp}
17010 and @command{rm}.
17012 @acronym{DOS} variants cannot rename or remove open files, and do not
17013 support commands like @samp{mv foo bar >foo}, even though this is
17014 perfectly portable among Posix hosts.
17017 @item @command{od}
17018 @c ---------------
17019 @prindex @command{od}
17021 In Mac OS X 10.3, @command{od} does not support the
17022 standard Posix options @option{-A}, @option{-j}, @option{-N}, or
17023 @option{-t}, or the @acronym{XSI} option @option{-s}.  The only
17024 supported Posix option is @option{-v}, and the only supported
17025 @acronym{XSI} options are those in @option{-bcdox}.  The @acronym{BSD}
17026 @command{hexdump} program can be used instead.
17028 This problem no longer exists in Mac OS X 10.4.3.
17031 @item @command{rm}
17032 @c ---------------
17033 @prindex @command{rm}
17034 The @option{-f} and @option{-r} options are portable.
17036 It is not portable to invoke @command{rm} without operands.  For
17037 example, on many systems @samp{rm -f -r} (with no other arguments)
17038 silently succeeds without doing anything, but it fails with a diagnostic
17039 on Net@acronym{BSD} 2.0.2.
17041 A file might not be removed even if its parent directory is writable
17042 and searchable.  Many Posix hosts cannot remove a mount point, a named
17043 stream, a working directory, or a last link to a file that is being
17044 executed.
17046 @acronym{DOS} variants cannot rename or remove open files, and do not
17047 support commands like @samp{rm foo >foo}, even though this is
17048 perfectly portable among Posix hosts.
17050 @item @command{rmdir}
17051 @c ------------------
17052 @prindex @command{rmdir}
17053 Just as with @command{rm}, some platforms refuse to remove a working
17054 directory.
17056 @anchor{sed}
17057 @item @command{sed}
17058 @c ----------------
17059 @prindex @command{sed}
17060 Patterns should not include the separator (unless escaped), even as part
17061 of a character class.  In conformance with Posix, the Cray
17062 @command{sed} rejects @samp{s/[^/]*$//}: use @samp{s,[^/]*$,,}.
17064 Avoid empty patterns within parentheses (i.e., @samp{\(\)}).  Posix does
17065 not require support for empty patterns, and Unicos 9 @command{sed} rejects
17066 them.
17068 Unicos 9 @command{sed} loops endlessly on patterns like @samp{.*\n.*}.
17070 Sed scripts should not use branch labels longer than 7 characters and
17071 should not contain comments.  @acronym{HP-UX} sed has a limit of 99 commands
17072 (not counting @samp{:} commands) and
17073 48 labels, which can not be circumvented by using more than one script
17074 file.  It can execute up to 19 reads with the @samp{r} command per cycle.
17075 Solaris @command{/usr/ucb/sed} rejects usages that exceed an limit of
17076 about 6000 bytes for the internal representation of commands.
17078 Avoid redundant @samp{;}, as some @command{sed} implementations, such as
17079 Net@acronym{BSD} 1.4.2's, incorrectly try to interpret the second
17080 @samp{;} as a command:
17082 @example
17083 $ @kbd{echo a | sed 's/x/x/;;s/x/x/'}
17084 sed: 1: "s/x/x/;;s/x/x/": invalid command code ;
17085 @end example
17087 Input should not have unreasonably long lines, since some @command{sed}
17088 implementations have an input buffer limited to 4000 bytes.  Likewise,
17089 not all @command{sed} implementations can handle embedded @code{NUL} or
17090 a missing trailing newline.
17092 Portable @command{sed} regular expressions should use @samp{\} only to escape
17093 characters in the string @samp{$()*.0123456789[\^n@{@}}.  For example,
17094 alternation, @samp{\|}, is common but Posix does not require its
17095 support, so it should be avoided in portable scripts.  Solaris
17096 @command{sed} does not support alternation; e.g., @samp{sed '/a\|b/d'}
17097 deletes only lines that contain the literal string @samp{a|b}.
17098 Similarly, @samp{\+} and @samp{\?} should be avoided.
17100 Anchors (@samp{^} and @samp{$}) inside groups are not portable.
17102 Nested parentheses in patterns (e.g., @samp{\(\(a*\)b*)\)}) are
17103 quite portable to current hosts, but was not supported by some ancient
17104 @command{sed} implementations like SVR3.
17106 Some @command{sed} implementations, e.g., Solaris,
17107 restrict the special role of the asterisk to one-character regular expressions.
17108 This may lead to unexpected behavior:
17110 @example
17111 $ @kbd{echo '1*23*4' | /usr/bin/sed 's/\(.\)*/x/g'}
17112 x2x4
17113 $ @kbd{echo '1*23*4' | /usr/xpg4/bin/sed 's/\(.\)*/x/g'}
17115 @end example
17117 The @option{-e} option is mostly portable.
17118 However, its argument
17119 cannot start with @samp{a}, @samp{c}, or @samp{i},
17120 as this runs afoul of a Tru64 5.1 bug.
17121 Also, its argument cannot be empty, as this fails on @acronym{AIX} 5.3.
17122 Some people prefer to use @samp{-e}:
17124 @example
17125 sed -e '@var{command-1}' \
17126     -e '@var{command-2}'
17127 @end example
17129 @noindent
17130 as opposed to the equivalent:
17132 @example
17133 sed '
17134   @var{command-1}
17135   @var{command-2}
17137 @end example
17139 @noindent
17140 The following usage is sometimes equivalent:
17142 @example
17143 sed '@var{command-1};@var{command-2}'
17144 @end example
17146 but Posix says that this use of a semicolon has undefined effect if
17147 @var{command-1}'s verb is @samp{@{}, @samp{a}, @samp{b}, @samp{c},
17148 @samp{i}, @samp{r}, @samp{t}, @samp{w}, @samp{:}, or @samp{#}, so you
17149 should use semicolon only with simple scripts that do not use these
17150 verbs.
17152 Commands inside @{ @} brackets are further restricted.  Posix says that
17153 they cannot be preceded by addresses, @samp{!}, or @samp{;}, and that
17154 each command must be followed immediately by a newline, without any
17155 intervening blanks or semicolons.  The closing bracket must be alone on
17156 a line, other than white space preceding or following it.
17158 Contrary to yet another urban legend, you may portably use @samp{&} in
17159 the replacement part of the @code{s} command to mean ``what was
17160 matched''.  All descendants of Unix version 7 @command{sed}
17161 (at least; we
17162 don't have first hand experience with older @command{sed} implementations) have
17163 supported it.
17165 Posix requires that you must not have any white space between
17166 @samp{!} and the following command.  It is OK to have blanks between
17167 the address and the @samp{!}.  For instance, on Solaris:
17169 @example
17170 $ @kbd{echo "foo" | sed -n '/bar/ ! p'}
17171 @error{}Unrecognized command: /bar/ ! p
17172 $ @kbd{echo "foo" | sed -n '/bar/! p'}
17173 @error{}Unrecognized command: /bar/! p
17174 $ @kbd{echo "foo" | sed -n '/bar/ !p'}
17176 @end example
17178 Posix also says that you should not combine @samp{!} and @samp{;}.  If
17179 you use @samp{!}, it is best to put it on a command that is delimited by
17180 newlines rather than @samp{;}.
17182 Also note that Posix requires that the @samp{b}, @samp{t}, @samp{r}, and
17183 @samp{w} commands be followed by exactly one space before their argument.
17184 On the other hand, no white space is allowed between @samp{:} and the
17185 subsequent label name.
17187 If a sed script is specified on the command line and ends in an
17188 @samp{a}, @samp{c}, or @samp{i} command, the last line of inserted text
17189 should be followed by a newline.  Otherwise some @command{sed}
17190 implementations (e.g., Open@acronym{BSD} 3.9) do not append a newline to the
17191 inserted text.
17193 Many @command{sed} implementations (e.g., MacOS X 10.4,
17194 Open@acronym{BSD} 3.9, Solaris 10
17195 @command{/usr/ucb/sed}) strip leading white space from the text of
17196 @samp{a}, @samp{c}, and @samp{i} commands.  Prepend a backslash to
17197 work around this incompatibility with Posix:
17199 @example
17200 $ @kbd{echo flushleft | sed 'a\}
17201 > @kbd{   indented}
17202 > @kbd{'}
17203 flushleft
17204 indented
17205 $ @kbd{echo foo | sed 'a\}
17206 > @kbd{\   indented}
17207 > @kbd{'}
17208 flushleft
17209    indented
17210 @end example
17212 Posix requires that with an empty regular expression, the last non-empty
17213 regular expression from either an address specification or substitution
17214 command is applied.  However, busybox 1.6.1 complains when using a
17215 substitution command with a replacement containing a back-reference to
17216 an empty regular expression; the workaround is repeating the regular
17217 expression.
17219 @example
17220 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s//\1/'}
17221 sed: No previous regexp.
17222 $ @kbd{echo abc | busybox sed '/a\(b\)c/ s/a\(b\)c/\1/'}
17224 @end example
17227 @item @command{sed} (@samp{t})
17228 @c ---------------------------
17229 @prindex @command{sed} (@samp{t})
17230 Some old systems have @command{sed} that ``forget'' to reset their
17231 @samp{t} flag when starting a new cycle.  For instance on @acronym{MIPS
17232 RISC/OS}, and on @sc{irix} 5.3, if you run the following @command{sed}
17233 script (the line numbers are not actual part of the texts):
17235 @example
17236 s/keep me/kept/g  # a
17237 t end             # b
17238 s/.*/deleted/g    # c
17239 :end              # d
17240 @end example
17242 @noindent
17245 @example
17246 delete me         # 1
17247 delete me         # 2
17248 keep me           # 3
17249 delete me         # 4
17250 @end example
17252 @noindent
17253 you get
17255 @example
17256 deleted
17257 delete me
17258 kept
17259 deleted
17260 @end example
17262 @noindent
17263 instead of
17265 @example
17266 deleted
17267 deleted
17268 kept
17269 deleted
17270 @end example
17272 Why?  When processing line 1, (c) matches, therefore sets the @samp{t}
17273 flag, and the output is produced.  When processing
17274 line 2, the @samp{t} flag is still set (this is the bug).  Command (a)
17275 fails to match, but @command{sed} is not supposed to clear the @samp{t}
17276 flag when a substitution fails.  Command (b) sees that the flag is set,
17277 therefore it clears it, and jumps to (d), hence you get @samp{delete me}
17278 instead of @samp{deleted}.  When processing line (3), @samp{t} is clear,
17279 (a) matches, so the flag is set, hence (b) clears the flags and jumps.
17280 Finally, since the flag is clear, line 4 is processed properly.
17282 There are two things one should remember about @samp{t} in @command{sed}.
17283 Firstly, always remember that @samp{t} jumps if @emph{some} substitution
17284 succeeded, not only the immediately preceding substitution.  Therefore,
17285 always use a fake @samp{t clear} followed by a @samp{:clear} on the next
17286 line, to reset the @samp{t} flag where needed.
17288 Secondly, you cannot rely on @command{sed} to clear the flag at each new
17289 cycle.
17291 One portable implementation of the script above is:
17293 @example
17294 t clear
17295 :clear
17296 s/keep me/kept/g
17297 t end
17298 s/.*/deleted/g
17299 :end
17300 @end example
17302 @item @command{sleep}
17303 @c ------------------
17304 @prindex @command{sleep}
17305 Using @command{sleep} is generally portable.  However, remember that
17306 adding a @command{sleep} to work around timestamp issues, with a minimum
17307 granularity of one second, doesn't scale well for parallel builds on
17308 modern machines with sub-second process completion.
17310 @item @command{sort}
17311 @c -----------------
17312 @prindex @command{sort}
17313 Remember that sort order is influenced by the current locale.  Inside
17314 @file{configure}, the C locale is in effect, but in Makefile snippets,
17315 you may need to specify @code{LC_ALL=C sort}.
17317 @item @command{tar}
17318 @c ----------------
17319 @prindex @command{tar}
17320 There are multiple file formats for @command{tar}; if you use Automake,
17321 the macro @code{AM_INIT_AUTOMAKE} has some options controlling which
17322 level of portability to use.
17324 @anchor{touch}
17325 @item @command{touch}
17326 @c ------------------
17327 @prindex @command{touch}
17328 @cindex timestamp resolution
17329 If you specify the desired timestamp (e.g., with the @option{-r}
17330 option), @command{touch} typically uses the @code{utime} or
17331 @code{utimes} system call, which can result in the same kind of
17332 timestamp truncation problems that @samp{cp -p} has.
17334 On ancient @acronym{BSD} systems, @command{touch} or any command that
17335 results in an empty file does not update the timestamps, so use a
17336 command like @command{echo} as a workaround.
17337 Also,
17338 @acronym{GNU} @command{touch} 3.16r (and presumably all before that)
17339 fails to work on SunOS 4.1.3 when the empty file is on an
17340 @acronym{NFS}-mounted 4.2 volume.
17341 However, these problems are no longer of practical concern.
17343 @item @command{tr}
17344 @c ---------------
17345 @prindex @command{tr}
17346 @cindex carriage return, deleting
17347 @cindex deleting carriage return
17348 Not all versions of @command{tr} handle all backslash character escapes.
17349 For example, Solaris 10 @command{/usr/ucb/tr} falls over, even though
17350 Solaris contains more modern @command{tr} in other locations.
17351 Therefore, it is more portable to use octal escapes, even though this
17352 ties the result to @acronym{ASCII}, when using @command{tr} to delete
17353 newlines or carriage returns.
17355 @example
17356 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\n' ; echo}
17358 light
17359 $ @kbd{@{ echo moon; echo light; @} | /usr/bin/tr -d '\n' ; echo}
17360 moonlight
17361 $ @kbd{@{ echo moon; echo light; @} | /usr/ucb/tr -d '\012' ; echo}
17362 moonlight
17363 @end example
17365 Posix requires @command{tr} to operate on binary files.  But at least
17366 Solaris @command{/usr/ucb/tr} still fails to handle @samp{\0} as the
17367 octal escape for @code{NUL}.  On Solaris, when using @command{tr} to
17368 neutralize a binary file by converting @code{NUL} to a different
17369 character, it is necessary to use @command{/usr/xpg4/bin/tr} instead.
17371 @example
17372 $ @kbd{printf 'a\0b\n' | /usr/ucb/tr '\0' '~' | wc -c}
17374 $ @kbd{printf 'a\0b\n' | /usr/xpg4/bin/tr '\0' '~' | wc -c}
17376 @end example
17378 @end table
17381 @node Portable Make
17382 @chapter Portable Make Programming
17383 @prindex @command{make}
17384 @cindex Limitations of @command{make}
17386 Writing portable makefiles is an art.  Since a makefile's commands are
17387 executed by the shell, you must consider the shell portability issues
17388 already mentioned.  However, other issues are specific to @command{make}
17389 itself.
17391 @menu
17392 * $< in Ordinary Make Rules::   $< in ordinary rules
17393 * Failure in Make Rules::       Failing portably in rules
17394 * Special Chars in Names::      Special Characters in Macro Names
17395 * Backslash-Newline-Newline::   Empty last lines in macro definitions
17396 * Backslash-Newline Comments::  Spanning comments across line boundaries
17397 * Long Lines in Makefiles::     Line length limitations
17398 * Macros and Submakes::         @code{make macro=value} and submakes
17399 * The Make Macro MAKEFLAGS::    @code{$(MAKEFLAGS)} portability issues
17400 * The Make Macro SHELL::        @code{$(SHELL)} portability issues
17401 * Comments in Make Rules::      Other problems with Make comments
17402 * obj/ and Make::               Don't name a subdirectory @file{obj}
17403 * make -k Status::              Exit status of @samp{make -k}
17404 * VPATH and Make::              @code{VPATH} woes
17405 * Single Suffix Rules::         Single suffix rules and separated dependencies
17406 * Timestamps and Make::         Subsecond timestamp resolution
17407 @end menu
17409 @node $< in Ordinary Make Rules
17410 @section @code{$<} in Ordinary Make Rules
17412 Posix says that the @samp{$<} construct in makefiles can be
17413 used only in inference rules and in the @samp{.DEFAULT} rule; its
17414 meaning in ordinary rules is unspecified.  Solaris @command{make}
17415 for instance replaces it with the empty string.  Open@acronym{BSD} (3.0 and
17416 later) @command{make} diagnoses these uses and errors out.
17418 @node Failure in Make Rules
17419 @section Failure in Make Rules
17421 Since 1992 Posix has required that @command{make} must invoke
17422 each command with the equivalent of a @samp{sh -c} subshell.  However,
17423 many @command{make} implementations, including @acronym{BSD} make through 2004,
17424 use @samp{sh -e -c} instead, and the @option{-e} option causes the
17425 subshell to exit immediately if a subsidiary simple-command fails.  For
17426 example, the command @samp{touch T; rm -f U} always attempts to
17427 remove @file{U} with Posix make, but incompatible
17428 @command{make} implementations skip the @command{rm} if the
17429 @command{touch} fails.  One way to work around this is to reword the
17430 affected simple-commands so that they always succeed, e.g., @samp{touch
17431 T || :; rm -f U}.
17432 However, even this approach can run into common bugs in @acronym{BSD}
17433 implementations of the @option{-e} option of @command{sh} and
17434 @command{set} (@pxref{set, , Limitations of Shell Builtins}), so if you
17435 are worried
17436 about porting to buggy @acronym{BSD} shells it may be simpler to migrate
17437 complicated @command{make} actions into separate scripts.
17439 @node Special Chars in Names
17440 @section Special Characters in Make Macro Names
17442 Posix limits macro names to nonempty strings containing only
17443 @acronym{ASCII} letters and digits, @samp{.}, and @samp{_}.  Many
17444 @command{make} implementations allow a wider variety of characters, but
17445 portable makefiles should avoid them.  It is portable to start a name
17446 with a special character, e.g., @samp{$(.FOO)}.
17448 Some ancient @command{make} implementations don't support leading
17449 underscores in macro names.  An example is @acronym{NEWS-OS} 4.2R.
17451 @example
17452 $ @kbd{cat Makefile}
17453 _am_include = #
17454 _am_quote =
17455 all:; @@echo this is test
17456 $ @kbd{make}
17457 Make: Must be a separator on rules line 2.  Stop.
17458 $ @kbd{cat Makefile2}
17459 am_include = #
17460 am_quote =
17461 all:; @@echo this is test
17462 $ @kbd{make -f Makefile2}
17463 this is test
17464 @end example
17466 @noindent
17467 However, this problem is no longer of practical concern.
17469 @node Backslash-Newline-Newline
17470 @section Backslash-Newline-Newline in Make Macro Values
17472 @c  This has been seen on ia64 hpux 11.20, and on one hppa hpux 10.20,
17473 @c  but another hppa hpux 10.20 didn't have it.  Bob Proulx
17474 @c  <bob@proulx.com> thinks it was in hpux 8.0 too.
17475 On some versions of @acronym{HP-UX}, @command{make} reads multiple newlines
17476 following a backslash, continuing to the next non-empty line.  For
17477 example,
17479 @example
17480 FOO = one \
17482 BAR = two
17484 test:
17485         : FOO is "$(FOO)"
17486         : BAR is "$(BAR)"
17487 @end example
17489 @noindent
17490 shows @code{FOO} equal to @code{one BAR = two}.  Other implementations
17491 sensibly let a backslash continue only to the immediately following
17492 line.
17494 @node Backslash-Newline Comments
17495 @section Backslash-Newline in Make Comments
17497 According to Posix, Make comments start with @code{#}
17498 and continue until an unescaped newline is reached.
17500 @example
17501 $ @kbd{cat Makefile}
17502 # A = foo \
17503       bar \
17504       baz
17506 all:
17507         @@echo ok
17508 $ @kbd{make}   # GNU make
17510 @end example
17512 @noindent
17513 However this is not always the case.  Some implementations
17514 discard everything from @code{#} through the end of the line, ignoring any
17515 trailing backslash.
17517 @example
17518 $ @kbd{pmake}  # BSD make
17519 "Makefile", line 3: Need an operator
17520 Fatal errors encountered -- cannot continue
17521 @end example
17523 @noindent
17524 Therefore, if you want to comment out a multi-line definition, prefix each
17525 line with @code{#}, not only the first.
17527 @example
17528 # A = foo \
17529 #     bar \
17530 #     baz
17531 @end example
17533 @node Long Lines in Makefiles
17534 @section Long Lines in Makefiles
17536 Tru64 5.1's @command{make} has been reported to crash when given a
17537 makefile with lines longer than around 20 kB.  Earlier versions are
17538 reported to exit with @code{Line too long} diagnostics.
17540 @node Macros and Submakes
17541 @section @code{make macro=value} and Submakes
17543 A command-line variable definition such as @code{foo=bar} overrides any
17544 definition of @code{foo} in a makefile.  Some @command{make}
17545 implementations (such as @acronym{GNU} @command{make}) propagate this
17546 override to subsidiary invocations of @command{make}.  Some other
17547 implementations do not pass the substitution along to submakes.
17549 @example
17550 $ @kbd{cat Makefile}
17551 foo = foo
17552 one:
17553         @@echo $(foo)
17554         $(MAKE) two
17555 two:
17556         @@echo $(foo)
17557 $ @kbd{make foo=bar}            # GNU make 3.79.1
17559 make two
17560 make[1]: Entering directory `/home/adl'
17562 make[1]: Leaving directory `/home/adl'
17563 $ @kbd{pmake foo=bar}           # BSD make
17565 pmake two
17567 @end example
17569 You have a few possibilities if you do want the @code{foo=bar} override
17570 to propagate to submakes.  One is to use the @option{-e}
17571 option, which causes all environment variables to have precedence over
17572 the makefile macro definitions, and declare foo as an environment
17573 variable:
17575 @example
17576 $ @kbd{env foo=bar make -e}
17577 @end example
17579 The @option{-e} option is propagated to submakes automatically,
17580 and since the environment is inherited between @command{make}
17581 invocations, the @code{foo} macro is overridden in
17582 submakes as expected.
17584 This syntax (@code{foo=bar make -e}) is portable only when used
17585 outside of a makefile, for instance from a script or from the
17586 command line.  When run inside a @command{make} rule, @acronym{GNU}
17587 @command{make} 3.80 and prior versions forget to propagate the
17588 @option{-e} option to submakes.
17590 Moreover, using @option{-e} could have unexpected side effects if your
17591 environment contains some other macros usually defined by the
17592 makefile.  (See also the note about @code{make -e} and @code{SHELL}
17593 below.)
17595 Another way to propagate overrides to submakes is to do it
17596 manually, from your makefile:
17598 @example
17599 foo = foo
17600 one:
17601         @@echo $(foo)
17602         $(MAKE) foo=$(foo) two
17603 two:
17604         @@echo $(foo)
17605 @end example
17607 You need to foresee all macros that a user might want to override if
17608 you do that.
17610 @node The Make Macro MAKEFLAGS
17611 @section The Make Macro MAKEFLAGS
17612 @cindex @code{MAKEFLAGS} and @command{make}
17613 @cindex @command{make} and @code{MAKEFLAGS}
17615 Posix requires @command{make} to use @code{MAKEFLAGS} to affect the
17616 current and recursive invocations of make, but allows implementations
17617 several formats for the variable.  It is tricky to parse
17618 @code{$MAKEFLAGS} to determine whether @option{-s} for silent execution
17619 or @option{-k} for continued execution are in effect.  For example, you
17620 cannot assume that the first space-separated word in @code{$MAKEFLAGS}
17621 contains single-letter options, since in the Cygwin version of
17622 @acronym{GNU} @command{make} it is either @option{--unix} or
17623 @option{--win32} with the second word containing single-letter options.
17625 @example
17626 $ @kbd{cat Makefile}
17627 all:
17628         @@echo MAKEFLAGS = $(MAKEFLAGS)
17629 $ @kbd{make}
17630 MAKEFLAGS = --unix
17631 $ @kbd{make -k}
17632 MAKEFLAGS = --unix -k
17633 @end example
17635 @node The Make Macro SHELL
17636 @section The Make Macro @code{SHELL}
17637 @cindex @code{SHELL} and @command{make}
17638 @cindex @command{make} and @code{SHELL}
17640 Posix-compliant @command{make} internally uses the @code{$(SHELL)}
17641 macro to spawn shell processes and execute Make rules.  This
17642 is a builtin macro supplied by @command{make}, but it can be modified
17643 by a makefile or by a command-line argument.
17645 Not all @command{make} implementations define this @code{SHELL} macro.
17646 Tru64
17647 @command{make} is an example; this implementation always uses
17648 @code{/bin/sh}.  So it's a good idea to always define @code{SHELL} in
17649 your makefiles.  If you use Autoconf, do
17651 @example
17652 SHELL = @@SHELL@@
17653 @end example
17655 @noindent
17656 If you use Automake, this is done for you.
17658 Do not force @code{SHELL = /bin/sh} because that is not correct
17659 everywhere.  Remember, @file{/bin/sh} is not Posix compliant on many
17660 systems, such as FreeBSD 4, NetBSD 3, AIX 3, Solaris 10, or Tru64.
17661 Additionally, @acronym{DJGPP} lacks @code{/bin/sh}, and when its
17662 @acronym{GNU} @command{make} port sees such a setting it enters a
17663 special emulation mode where features like pipes and redirections are
17664 emulated on top of DOS's @command{command.com}.  Unfortunately this
17665 emulation is incomplete; for instance it does not handle command
17666 substitutions.  Using @code{@@SHELL@@} means that your makefile will
17667 benefit from the same improved shell, such as @command{bash} or
17668 @command{ksh}, that was discovered during @command{configure}, so that
17669 you aren't fighting two different sets of shell bugs between the two
17670 contexts.
17672 Posix-compliant @command{make} should never acquire the value of
17673 $(SHELL) from the environment, even when @code{make -e} is used
17674 (otherwise, think about what would happen to your rules if
17675 @code{SHELL=/bin/tcsh}).
17677 However not all @command{make} implementations have this exception.
17678 For instance it's not surprising that Tru64 @command{make} doesn't
17679 protect @code{SHELL}, since it doesn't use it.
17681 @example
17682 $ @kbd{cat Makefile}
17683 SHELL = /bin/sh
17684 FOO = foo
17685 all:
17686         @@echo $(SHELL)
17687         @@echo $(FOO)
17688 $ @kbd{env SHELL=/bin/tcsh FOO=bar make -e}   # Tru64 Make
17689 /bin/tcsh
17691 $ @kbd{env SHELL=/bin/tcsh FOO=bar gmake -e}  # GNU make
17692 /bin/sh
17694 @end example
17696 Conversely, @command{make} is not supposed to export any changes to the
17697 macro @code{SHELL} to child processes.  Again, many implementations
17698 break this rule:
17700 @example
17701 $ @kbd{cat Makefile}
17702 all:
17703         @@echo $(SHELL)
17704         @@printenv SHELL
17705 $ @kbd{env SHELL=sh make -e SHELL=/bin/ksh}   # BSD Make, GNU make 3.80
17706 /bin/ksh
17707 /bin/ksh
17708 $ @kbd{env SHELL=sh gmake -e SHELL=/bin/ksh}  # GNU make 3.81
17709 /bin/ksh
17711 @end example
17713 @node Comments in Make Rules
17714 @section Comments in Make Rules
17715 @cindex Comments in @file{Makefile} rules
17716 @cindex @file{Makefile} rules and comments
17718 Never put comments in a rule.
17720 Some @command{make} treat anything starting with a tab as a command for
17721 the current rule, even if the tab is immediately followed by a @code{#}.
17722 The @command{make} from Tru64 Unix V5.1 is one of them.  The following
17723 makefile runs @code{# foo} through the shell.
17725 @example
17726 all:
17727         # foo
17728 @end example
17730 @node obj/ and Make
17731 @section The @file{obj/} Subdirectory and Make
17732 @cindex @file{obj/}, subdirectory
17733 @cindex @acronym{BSD} @command{make} and @file{obj/}
17735 Never name one of your subdirectories @file{obj/} if you don't like
17736 surprises.
17738 If an @file{obj/} directory exists, @acronym{BSD} @command{make} enters it
17739 before reading the makefile.  Hence the makefile in the
17740 current directory is not read.
17742 @example
17743 $ @kbd{cat Makefile}
17744 all:
17745         echo Hello
17746 $ @kbd{cat obj/Makefile}
17747 all:
17748         echo World
17749 $ @kbd{make}      # GNU make
17750 echo Hello
17751 Hello
17752 $ @kbd{pmake}     # BSD make
17753 echo World
17754 World
17755 @end example
17757 @node make -k Status
17758 @section Exit Status of @code{make -k}
17759 @cindex @code{make -k}
17761 Do not rely on the exit status of @code{make -k}.  Some implementations
17762 reflect whether they encountered an error in their exit status; other
17763 implementations always succeed.
17765 @example
17766 $ @kbd{cat Makefile}
17767 all:
17768         false
17769 $ @kbd{make -k; echo exit status: $?}    # GNU make
17770 false
17771 make: *** [all] Error 1
17772 exit status: 2
17773 $ @kbd{pmake -k; echo exit status: $?}   # BSD make
17774 false
17775 *** Error code 1 (continuing)
17776 exit status: 0
17777 @end example
17779 @node VPATH and Make
17780 @section @code{VPATH} and Make
17781 @cindex @code{VPATH}
17783 Posix does not specify the semantics of @code{VPATH}.  Typically,
17784 @command{make} supports @code{VPATH}, but its implementation is not
17785 consistent.
17787 Autoconf and Automake support makefiles whose usages of @code{VPATH} are
17788 portable to recent-enough popular implementations of @command{make}, but
17789 to keep the resulting makefiles portable, a package's makefile
17790 prototypes must take the following issues into account.  These issues
17791 are complicated and are often poorly understood, and installers who use
17792 @code{VPATH} should expect to find many bugs in this area.  If you use
17793 @code{VPATH}, the simplest way to avoid these portability bugs is to
17794 stick with @acronym{GNU} @command{make}, since it is the most
17795 commonly-used @command{make} among Autoconf users.
17797 Here are some known issues with some @code{VPATH}
17798 implementations.
17800 @menu
17801 * VPATH and Double-colon::      Problems with @samp{::} on ancient hosts
17802 * $< in Explicit Rules::        @code{$<} does not work in ordinary rules
17803 * Automatic Rule Rewriting::    @code{VPATH} goes wild on Solaris
17804 * Tru64 Directory Magic::       @command{mkdir} goes wild on Tru64
17805 * Make Target Lookup::          More details about @code{VPATH} lookup
17806 @end menu
17808 @node VPATH and Double-colon
17809 @subsection @code{VPATH} and Double-colon Rules
17810 @cindex @code{VPATH} and double-colon rules
17811 @cindex double-colon rules and @code{VPATH}
17813 With ancient versions of Sun @command{make},
17814 any assignment to @code{VPATH} causes @command{make} to execute only
17815 the first set of double-colon rules.
17816 However, this problem is no longer of practical concern.
17818 @node $< in Explicit Rules
17819 @subsection @code{$<} Not Supported in Explicit Rules
17820 @cindex explicit rules, @code{$<}, and @code{VPATH}
17821 @cindex @code{$<}, explicit rules, and @code{VPATH}
17822 @cindex @code{VPATH}, explicit rules, and @code{$<}
17824 Using @code{$<} in explicit rules is not portable.
17825 The prerequisite file must be named explicitly in the rule.  If you want
17826 to find the prerequisite via a @code{VPATH} search, you have to code the
17827 whole thing manually.  @xref{Build Directories}.
17829 @node Automatic Rule Rewriting
17830 @subsection Automatic Rule Rewriting
17831 @cindex @code{VPATH} and automatic rule rewriting
17832 @cindex automatic rule rewriting and @code{VPATH}
17834 Some @command{make} implementations, such as Solaris and Tru64,
17835 search for prerequisites in @code{VPATH} and
17836 then rewrite each occurrence as a plain word in the rule.
17837 For instance:
17839 @example
17840 # This isn't portable to GNU make.
17841 VPATH = ../pkg/src
17842 f.c: if.c
17843         cp if.c f.c
17844 @end example
17846 @noindent
17847 executes @code{cp ../pkg/src/if.c f.c} if @file{if.c} is
17848 found in @file{../pkg/src}.
17850 However, this rule leads to real problems in practice.  For example, if
17851 the source directory contains an ordinary file named @file{test} that is
17852 used in a dependency, Solaris @command{make} rewrites commands like
17853 @samp{if test -r foo; @dots{}} to @samp{if ../pkg/src/test -r foo;
17854 @dots{}}, which is typically undesirable.  To avoid this problem,
17855 portable makefiles should never mention a source file whose name is that
17856 of a shell keyword like @file{until} or a shell command like
17857 @command{cat} or @command{gcc} or @command{test}.
17859 Because of these problems @acronym{GNU} @command{make} and many other
17860 @command{make} implementations do not rewrite commands, so portable
17861 makefiles should
17862 search @code{VPATH} manually.  It is tempting to write this:
17864 @smallexample
17865 # This isn't portable to Solaris make.
17866 VPATH = ../pkg/src
17867 f.c: if.c
17868         cp `test -f if.c || echo $(VPATH)/`if.c f.c
17869 @end smallexample
17871 @noindent
17872 However, the ``prerequisite rewriting'' still applies here.  So if
17873 @file{if.c} is in @file{../pkg/src}, Solaris and Tru64 @command{make}
17874 execute
17876 @smallexample
17877 cp `test -f ../pkg/src/if.c || echo ../pkg/src/`if.c f.c
17878 @end smallexample
17880 @noindent
17881 which reduces to
17883 @example
17884 cp if.c f.c
17885 @end example
17887 @noindent
17888 and thus fails.  Oops.
17890 A simple workaround, and good practice anyway, is to use @samp{$?} and
17891 @samp{$@@} when possible:
17893 @smallexample
17894 VPATH = ../pkg/src
17895 f.c: if.c
17896         cp $? $@@
17897 @end smallexample
17899 @noindent
17900 but this does not generalize well to commands with multiple
17901 prerequisites.  A more general workaround is to rewrite the rule so that
17902 the prerequisite @file{if.c} never appears as a plain word.  For
17903 example, these three rules would be safe, assuming @file{if.c} is in
17904 @file{../pkg/src} and the other files are in the working directory:
17906 @smallexample
17907 VPATH = ../pkg/src
17908 f.c: if.c f1.c
17909         cat `test -f ./if.c || echo $(VPATH)/`if.c f1.c >$@@
17910 g.c: if.c g1.c
17911         cat `test -f 'if.c' || echo $(VPATH)/`if.c g1.c >$@@
17912 h.c: if.c h1.c
17913         cat `test -f "if.c" || echo $(VPATH)/`if.c h1.c >$@@
17914 @end smallexample
17916 Things get worse when your prerequisites are in a macro.
17918 @example
17919 VPATH = ../pkg/src
17920 HEADERS = f.h g.h h.h
17921 install-HEADERS: $(HEADERS)
17922         for i in $(HEADERS); do \
17923           $(INSTALL) -m 644 \
17924             `test -f $$i || echo $(VPATH)/`$$i \
17925             $(DESTDIR)$(includedir)/$$i; \
17926         done
17927 @end example
17929 The above @code{install-HEADERS} rule is not Solaris-proof because @code{for
17930 i in $(HEADERS);} is expanded to @code{for i in f.h g.h h.h;}
17931 where @code{f.h} and @code{g.h} are plain words and are hence
17932 subject to @code{VPATH} adjustments.
17934 If the three files are in @file{../pkg/src}, the rule is run as:
17936 @example
17937 for i in ../pkg/src/f.h ../pkg/src/g.h h.h; do \
17938   install -m 644 \
17939      `test -f $i || echo ../pkg/src/`$i \
17940      /usr/local/include/$i; \
17941 done
17942 @end example
17944 where the two first @command{install} calls fail.  For instance,
17945 consider the @code{f.h} installation:
17947 @example
17948 install -m 644 \
17949   `test -f ../pkg/src/f.h || \
17950     echo ../pkg/src/ \
17951   `../pkg/src/f.h \
17952   /usr/local/include/../pkg/src/f.h;
17953 @end example
17955 @noindent
17956 It reduces to:
17958 @example
17959 install -m 644 \
17960   ../pkg/src/f.h \
17961   /usr/local/include/../pkg/src/f.h;
17962 @end example
17964 Note that the manual @code{VPATH} search did not cause any problems here;
17965 however this command installs @file{f.h} in an incorrect directory.
17967 Trying to quote @code{$(HEADERS)} in some way, as we did for
17968 @code{foo.c} a few makefiles ago, does not help:
17970 @example
17971 install-HEADERS: $(HEADERS)
17972         headers='$(HEADERS)'; \
17973         for i in $$headers; do \
17974           $(INSTALL) -m 644 \
17975             `test -f $$i || echo $(VPATH)/`$$i \
17976             $(DESTDIR)$(includedir)/$$i; \
17977         done
17978 @end example
17980 Now, @code{headers='$(HEADERS)'} macro-expands to:
17982 @example
17983 headers='f.h g.h h.h'
17984 @end example
17986 @noindent
17987 but @code{g.h} is still a plain word.  (As an aside, the idiom
17988 @code{headers='$(HEADERS)'; for i in $$headers;} is a good
17989 idea if @code{$(HEADERS)} can be empty, because some shells diagnose a
17990 syntax error on @code{for i in;}.)
17992 One workaround is to strip this unwanted @file{../pkg/src/} prefix manually:
17994 @example
17995 VPATH = ../pkg/src
17996 HEADERS = f.h g.h h.h
17997 install-HEADERS: $(HEADERS)
17998         headers='$(HEADERS)'; \
17999         for i in $$headers; do \
18000           i=`expr "$$i" : '$(VPATH)/\(.*\)'`;
18001           $(INSTALL) -m 644 \
18002             `test -f $$i || echo $(VPATH)/`$$i \
18003             $(DESTDIR)$(includedir)/$$i; \
18004         done
18005 @end example
18007 Automake does something similar.  However the above hack works only if
18008 the files listed in @code{HEADERS} are in the current directory or a
18009 subdirectory; they should not be in an enclosing directory.  If we had
18010 @code{HEADERS = ../f.h}, the above fragment would fail in a VPATH
18011 build with Tru64 @command{make}.  The reason is that not only does
18012 Tru64 @command{make} rewrite dependencies, but it also simplifies
18013 them.  Hence @code{../f.h} becomes @code{../pkg/f.h} instead of
18014 @code{../pkg/src/../f.h}.  This obviously defeats any attempt to strip
18015 a leading @file{../pkg/src/} component.
18017 The following example makes the behavior of Tru64 @command{make}
18018 more apparent.
18020 @example
18021 $ @kbd{cat Makefile}
18022 VPATH = sub
18023 all: ../foo
18024         echo ../foo
18025 $ @kbd{ls}
18026 Makefile foo
18027 $ @kbd{make}
18028 echo foo
18030 @end example
18032 @noindent
18033 Dependency @file{../foo} was found in @file{sub/../foo}, but Tru64
18034 @command{make} simplified it as @file{foo}.  (Note that the @file{sub/}
18035 directory does not even exist, this just means that the simplification
18036 occurred before the file was checked for.)
18038 For the record here is how SunOS 4 @command{make} behaves on this
18039 example.
18041 @smallexample
18042 $ @kbd{make}
18043 make: Fatal error: Don't know how to make target `../foo'
18044 $ @kbd{mkdir sub}
18045 $ @kbd{make}
18046 echo sub/../foo
18047 sub/../foo
18048 @end smallexample
18051 @node Tru64 Directory Magic
18052 @subsection Tru64 @command{make} Creates Prerequisite Directories Magically
18053 @cindex @code{VPATH} and prerequisite directories
18054 @cindex prerequisite directories and @code{VPATH}
18056 When a prerequisite is a subdirectory of @code{VPATH}, Tru64
18057 @command{make} creates it in the current directory.
18059 @example
18060 $ @kbd{mkdir -p foo/bar build}
18061 $ @kbd{cd build}
18062 $ @kbd{cat >Makefile <<END
18063 VPATH = ..
18064 all: foo/bar
18065 END}
18066 $ @kbd{make}
18067 mkdir foo
18068 mkdir foo/bar
18069 @end example
18071 This can yield unexpected results if a rule uses a manual @code{VPATH}
18072 search as presented before.
18074 @example
18075 VPATH = ..
18076 all : foo/bar
18077         command `test -d foo/bar || echo ../`foo/bar
18078 @end example
18080 The above @command{command} is run on the empty @file{foo/bar}
18081 directory that was created in the current directory.
18083 @node Make Target Lookup
18084 @subsection Make Target Lookup
18085 @cindex @code{VPATH}, resolving target pathnames
18087 @acronym{GNU} @command{make} uses a complex algorithm to decide when it
18088 should use files found via a @code{VPATH} search.  @xref{Search
18089 Algorithm, , How Directory Searches are Performed, make, The @acronym{GNU} Make
18090 Manual}.
18092 If a target needs to be rebuilt, @acronym{GNU} @command{make} discards the
18093 file name found during the @code{VPATH} search for this target, and
18094 builds the file locally using the file name given in the makefile.
18095 If a target does not need to be rebuilt, @acronym{GNU} @command{make} uses the
18096 file name found during the @code{VPATH} search.
18098 Other @command{make} implementations, like Net@acronym{BSD} @command{make}, are
18099 easier to describe: the file name found during the @code{VPATH} search
18100 is used whether the target needs to be rebuilt or not.  Therefore
18101 new files are created locally, but existing files are updated at their
18102 @code{VPATH} location.
18104 Open@acronym{BSD} and Free@acronym{BSD} @command{make}, however,
18105 never perform a
18106 @code{VPATH} search for a dependency that has an explicit rule.
18107 This is extremely annoying.
18109 When attempting a @code{VPATH} build for an autoconfiscated package
18110 (e.g., @code{mkdir build && cd build && ../configure}), this means
18111 @acronym{GNU}
18112 @command{make} builds everything locally in the @file{build}
18113 directory, while @acronym{BSD} @command{make} builds new files locally and
18114 updates existing files in the source directory.
18116 @example
18117 $ @kbd{cat Makefile}
18118 VPATH = ..
18119 all: foo.x bar.x
18120 foo.x bar.x: newer.x
18121         @@echo Building $@@
18122 $ @kbd{touch ../bar.x}
18123 $ @kbd{touch ../newer.x}
18124 $ @kbd{make}        # GNU make
18125 Building foo.x
18126 Building bar.x
18127 $ @kbd{pmake}       # NetBSD make
18128 Building foo.x
18129 Building ../bar.x
18130 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18131 Building foo.x
18132 Building bar.x
18133 $ @kbd{tmake}       # Tru64 make
18134 Building foo.x
18135 Building bar.x
18136 $ @kbd{touch ../bar.x}
18137 $ @kbd{make}        # GNU make
18138 Building foo.x
18139 $ @kbd{pmake}       # NetBSD make
18140 Building foo.x
18141 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18142 Building foo.x
18143 Building bar.x
18144 $ @kbd{tmake}       # Tru64 make
18145 Building foo.x
18146 Building bar.x
18147 @end example
18149 Note how Net@acronym{BSD} @command{make} updates @file{../bar.x} in its
18150 VPATH location, and how Free@acronym{BSD}, Open@acronym{BSD}, and Tru64
18151 @command{make} always
18152 update @file{bar.x}, even when @file{../bar.x} is up to date.
18154 Another point worth mentioning is that once @acronym{GNU} @command{make} has
18155 decided to ignore a @code{VPATH} file name (e.g., it ignored
18156 @file{../bar.x} in the above example) it continues to ignore it when
18157 the target occurs as a prerequisite of another rule.
18159 The following example shows that @acronym{GNU} @command{make} does not look up
18160 @file{bar.x} in @code{VPATH} before performing the @code{.x.y} rule,
18161 because it ignored the @code{VPATH} result of @file{bar.x} while running
18162 the @code{bar.x: newer.x} rule.
18164 @example
18165 $ @kbd{cat Makefile}
18166 VPATH = ..
18167 all: bar.y
18168 bar.x: newer.x
18169         @@echo Building $@@
18170 .SUFFIXES: .x .y
18171 .x.y:
18172         cp $< $@@
18173 $ @kbd{touch ../bar.x}
18174 $ @kbd{touch ../newer.x}
18175 $ @kbd{make}        # GNU make
18176 Building bar.x
18177 cp bar.x bar.y
18178 cp: cannot stat `bar.x': No such file or directory
18179 make: *** [bar.y] Error 1
18180 $ @kbd{pmake}       # NetBSD make
18181 Building ../bar.x
18182 cp ../bar.x bar.y
18183 $ @kbd{rm bar.y}
18184 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18185 echo Building bar.x
18186 cp bar.x bar.y
18187 cp: cannot stat `bar.x': No such file or directory
18188 *** Error code 1
18189 $ @kbd{tmake}       # Tru64 make
18190 Building bar.x
18191 cp: bar.x: No such file or directory
18192 *** Exit 1
18193 @end example
18195 Note that if you drop away the command from the @code{bar.x: newer.x}
18196 rule, @acronym{GNU} @command{make} magically starts to work: it
18197 knows that @code{bar.x} hasn't been updated, therefore it doesn't
18198 discard the result from @code{VPATH} (@file{../bar.x}) in succeeding
18199 uses.  Tru64 also works, but Free@acronym{BSD} and Open@acronym{BSD}
18200 still don't.
18202 @example
18203 $ @kbd{cat Makefile}
18204 VPATH = ..
18205 all: bar.y
18206 bar.x: newer.x
18207 .SUFFIXES: .x .y
18208 .x.y:
18209         cp $< $@@
18210 $ @kbd{touch ../bar.x}
18211 $ @kbd{touch ../newer.x}
18212 $ @kbd{make}        # GNU make
18213 cp ../bar.x bar.y
18214 $ @kbd{rm bar.y}
18215 $ @kbd{pmake}       # NetBSD make
18216 cp ../bar.x bar.y
18217 $ @kbd{rm bar.y}
18218 $ @kbd{fmake}       # FreeBSD make, OpenBSD make
18219 cp bar.x bar.y
18220 cp: cannot stat `bar.x': No such file or directory
18221 *** Error code 1
18222 $ @kbd{tmake}       # Tru64 make
18223 cp ../bar.x bar.y
18224 @end example
18226 It seems the sole solution that would please every @command{make}
18227 implementation is to never rely on @code{VPATH} searches for targets.
18228 In other words, @code{VPATH} should be reserved to unbuilt sources.
18231 @node Single Suffix Rules
18232 @section Single Suffix Rules and Separated Dependencies
18233 @cindex Single Suffix Inference Rule
18234 @cindex Rule, Single Suffix Inference
18235 A @dfn{Single Suffix Rule} is basically a usual suffix (inference) rule
18236 (@samp{.from.to:}), but which @emph{destination} suffix is empty
18237 (@samp{.from:}).
18239 @cindex Separated Dependencies
18240 @dfn{Separated dependencies} simply refers to listing the prerequisite
18241 of a target, without defining a rule.  Usually one can list on the one
18242 hand side, the rules, and on the other hand side, the dependencies.
18244 Solaris @command{make} does not support separated dependencies for
18245 targets defined by single suffix rules:
18247 @example
18248 $ @kbd{cat Makefile}
18249 .SUFFIXES: .in
18250 foo: foo.in
18251 .in:
18252         cp $< $@@
18253 $ @kbd{touch foo.in}
18254 $ @kbd{make}
18255 $ @kbd{ls}
18256 Makefile  foo.in
18257 @end example
18259 @noindent
18260 while @acronym{GNU} Make does:
18262 @example
18263 $ @kbd{gmake}
18264 cp foo.in foo
18265 $ @kbd{ls}
18266 Makefile  foo       foo.in
18267 @end example
18269 Note it works without the @samp{foo: foo.in} dependency.
18271 @example
18272 $ @kbd{cat Makefile}
18273 .SUFFIXES: .in
18274 .in:
18275         cp $< $@@
18276 $ @kbd{make foo}
18277 cp foo.in foo
18278 @end example
18280 @noindent
18281 and it works with double suffix inference rules:
18283 @example
18284 $ @kbd{cat Makefile}
18285 foo.out: foo.in
18286 .SUFFIXES: .in .out
18287 .in.out:
18288         cp $< $@@
18289 $ @kbd{make}
18290 cp foo.in foo.out
18291 @end example
18293 As a result, in such a case, you have to write target rules.
18295 @node Timestamps and Make
18296 @section Timestamp Resolution and Make
18297 @cindex timestamp resolution
18298 Traditionally, file timestamps had 1-second resolution, and
18299 @command{make} used those timestamps to determine whether one file was
18300 newer than the other.  However, many modern file systems have
18301 timestamps with 1-nanosecond resolution.  Some @command{make}
18302 implementations look at the entire timestamp; others ignore the
18303 fractional part, which can lead to incorrect results.  Normally this
18304 is not a problem, but in some extreme cases you may need to use tricks
18305 like @samp{sleep 1} to work around timestamp truncation bugs.
18307 Commands like @samp{cp -p} and @samp{touch -r} typically do not copy
18308 file timestamps to their full resolutions (@pxref{touch, , Limitations of Usual
18309 Tools}).  Hence you should be wary of rules like this:
18311 @example
18312 dest: src
18313         cp -p src dest
18314 @end example
18316 as @file{dest} often appears to be older than @file{src} after the
18317 timestamp is truncated, and this can cause @command{make} to do
18318 needless rework the next time it is invoked.  To work around this
18319 problem, you can use a timestamp file, e.g.:
18321 @example
18322 dest-stamp: src
18323         cp -p src dest
18324         date >dest-stamp
18325 @end example
18330 @c ======================================== Portable C and C++ Programming
18332 @node Portable C and C++
18333 @chapter Portable C and C++ Programming
18334 @cindex Portable C and C++ programming
18336 C and C++ programs often use low-level features of the underlying
18337 system, and therefore are often more difficult to make portable to other
18338 platforms.
18340 Several standards have been developed to help make your programs more
18341 portable.  If you write programs with these standards in mind, you can
18342 have greater confidence that your programs work on a wide variety
18343 of systems.  @xref{Standards, , Language Standards Supported by
18344 @acronym{GCC}, gcc, Using the @acronym{GNU} Compiler Collection
18345 (@acronym{GCC})}, for a list of C-related
18346 standards.  Many programs also assume the
18347 @uref{http://@/www.opengroup.org/@/susv3, Posix standard}.
18349 Some old code is written to be portable to K&R C, which predates any C
18350 standard.  K&R C compilers are no longer of practical interest, though,
18351 and the rest of section assumes at least C89, the first C standard.
18353 Program portability is a huge topic, and this section can only briefly
18354 introduce common pitfalls.  @xref{System Portability, , Portability
18355 between System Types, standards, @acronym{GNU} Coding Standards}, for
18356 more information.
18358 @menu
18359 * Varieties of Unportability::  How to make your programs unportable
18360 * Integer Overflow::            When integers get too large
18361 * Preprocessor Arithmetic::     @code{#if} expression problems
18362 * Null Pointers::               Properties of null pointers
18363 * Buffer Overruns::             Subscript errors and the like
18364 * Volatile Objects::            @code{volatile} and signals
18365 * Floating Point Portability::  Portable floating-point arithmetic
18366 * Exiting Portably::            Exiting and the exit status
18367 @end menu
18369 @node Varieties of Unportability
18370 @section Varieties of Unportability
18371 @cindex portability
18373 Autoconf tests and ordinary programs often need to test what is allowed
18374 on a system, and therefore they may need to deliberately exceed the
18375 boundaries of what the standards allow, if only to see whether an
18376 optional feature is present.  When you write such a program, you should
18377 keep in mind the difference between constraints, unspecified behavior,
18378 and undefined behavior.
18380 In C, a @dfn{constraint} is a rule that the compiler must enforce.  An
18381 example constraint is that C programs must not declare a bit-field with
18382 negative width.  Tests can therefore reliably assume that programs with
18383 negative-width bit-fields are rejected by a compiler that conforms
18384 to the standard.
18386 @dfn{Unspecified behavior} is valid behavior, where the standard allows
18387 multiple possibilities.  For example, the order of evaluation of
18388 function arguments is unspecified.  Some unspecified behavior is
18389 @dfn{implementation-defined}, i.e., documented by the implementation,
18390 but since Autoconf tests cannot read the documentation they cannot
18391 distinguish between implementation-defined and other unspecified
18392 behavior.  It is common for Autoconf tests to probe implementations to
18393 determine otherwise-unspecified behavior.
18395 @dfn{Undefined behavior} is invalid behavior, where the standard allows
18396 the implementation to do anything it pleases.  For example,
18397 dereferencing a null pointer leads to undefined behavior.  If possible,
18398 test programs should avoid undefined behavior, since a program with
18399 undefined behavior might succeed on a test that should fail.
18401 The above rules apply to programs that are intended to conform to the
18402 standard.  However, strictly-conforming programs are quite rare, since
18403 the standards are so limiting.  A major goal of Autoconf is to support
18404 programs that use implementation features not described by the standard,
18405 and it is fairly common for test programs to violate the above rules, if
18406 the programs work well enough in practice.
18408 @node Integer Overflow
18409 @section Integer Overflow
18410 @cindex integer overflow
18411 @cindex overflow, signed integer
18412 @cindex signed integer overflow
18413 @cindex wraparound arithmetic
18415 In practice many portable C programs assume that signed integer overflow wraps
18416 around reliably using two's complement arithmetic.  Yet the C standard
18417 says that program behavior is undefined on overflow, and in a few cases
18418 C programs do not work on some modern implementations because their
18419 overflows do not wrap around as their authors expected.  Conversely, in
18420 signed integer remainder, the C standard requires overflow
18421 behavior that is commonly not implemented.
18423 @menu
18424 * Integer Overflow Basics::      Why integer overflow is a problem
18425 * Signed Overflow Examples::     Examples of code assuming wraparound
18426 * Optimization and Wraparound::  Optimizations that break uses of wraparound
18427 * Signed Overflow Advice::       Practical advice for signed overflow issues
18428 * Signed Integer Division::      @code{INT_MIN / -1} and @code{INT_MIN % -1}
18429 @end menu
18431 @node Integer Overflow Basics
18432 @subsection Basics of Integer Overflow
18433 @cindex integer overflow
18434 @cindex overflow, signed integer
18435 @cindex signed integer overflow
18436 @cindex wraparound arithmetic
18438 In languages like C, unsigned integer overflow reliably wraps around;
18439 e.g., @code{UINT_MAX + 1} yields zero.
18440 This is guaranteed by the C standard and is
18441 portable in practice, unless you specify aggressive,
18442 nonstandard optimization options
18443 suitable only for special applications.
18445 In contrast, the C standard says that signed integer overflow leads to
18446 undefined behavior where a program can do anything, including dumping
18447 core or overrunning a buffer.  The misbehavior can even precede the
18448 overflow.  Such an overflow can occur during addition, subtraction,
18449 multiplication, division, and left shift.
18451 Despite this requirement of the standard, many C programs and Autoconf
18452 tests assume that signed integer overflow silently wraps around modulo a
18453 power of two, using two's complement arithmetic, so long as you cast the
18454 resulting value to a signed integer type or store it into a signed
18455 integer variable.  If you use conservative optimization flags, such
18456 programs are generally portable to the vast majority of modern
18457 platforms, with a few exceptions discussed later.
18459 For historical reasons the C standard also allows implementations with
18460 ones' complement or signed magnitude arithmetic, but it is safe to
18461 assume two's complement nowadays.
18463 Also, overflow can occur when converting an out-of-range value to a
18464 signed integer type.  Here a standard implementation must define what
18465 happens, but this might include raising an exception.  In practice all
18466 known implementations support silent wraparound in this case, so you need
18467 not worry about other possibilities.
18469 @node Signed Overflow Examples
18470 @subsection Examples of Code Assuming Wraparound Overflow
18471 @cindex integer overflow
18472 @cindex overflow, signed integer
18473 @cindex signed integer overflow
18474 @cindex wraparound arithmetic
18476 There has long been a tension between what the C standard requires for
18477 signed integer overflow, and what C programs commonly assume.  The
18478 standard allows aggressive optimizations based on assumptions that
18479 overflow never occurs, but many practical C programs rely on overflow
18480 wrapping around.  These programs do not conform to the standard, but
18481 they commonly work in practice because compiler writers are
18482 understandably reluctant to implement optimizations that would break
18483 many programs, unless perhaps a user specifies aggressive optimization.
18485 The C Standard says that if a program has signed integer overflow its
18486 behavior is undefined, and the undefined behavior can even precede the
18487 overflow.  To take an extreme example:
18489 @c Inspired by Robert Dewar's example in
18490 @c <http://gcc.gnu.org/ml/gcc/2007-01/msg00038.html> (2007-01-01).
18491 @example
18492 if (password == expected_password)
18493   allow_superuser_privileges ();
18494 else if (counter++ == INT_MAX)
18495   abort ();
18496 else
18497   printf ("%d password mismatches\n", counter);
18498 @end example
18500 @noindent
18501 If the @code{int} variable @code{counter} equals @code{INT_MAX},
18502 @code{counter++} must overflow and the behavior is undefined, so the C
18503 standard allows the compiler to optimize away the test against
18504 @code{INT_MAX} and the @code{abort} call.
18505 Worse, if an earlier bug in the program lets the compiler deduce that
18506 @code{counter == INT_MAX} or that @code{counter} previously overflowed,
18507 the C standard allows the compiler to optimize away the password test
18508 and generate code that allows superuser privileges unconditionally.
18510 Despite this requirement by the standard, it has long been common for C
18511 code to assume wraparound arithmetic after signed overflow, and all
18512 known practical C implementations support some C idioms that assume
18513 wraparound signed arithmetic, even if the idioms do not conform
18514 strictly to the standard.  If your code looks like the following
18515 examples it will almost surely work with real-world compilers.
18517 Here is an example derived from the 7th Edition Unix implementation of
18518 @code{atoi} (1979-01-10):
18520 @example
18521 char *p;
18522 int f, n;
18523 @dots{}
18524 while (*p >= '0' && *p <= '9')
18525   n = n * 10 + *p++ - '0';
18526 return (f ? -n : n);
18527 @end example
18529 @noindent
18530 Even if the input string is in range, on most modern machines this has
18531 signed overflow when computing the most negative integer (the @code{-n}
18532 overflows) or a value near an extreme integer (the first @code{+}
18533 overflows).
18535 Here is another example, derived from the 7th Edition implementation of
18536 @code{rand} (1979-01-10).  Here the programmer expects both
18537 multiplication and addition to wrap on overflow:
18539 @example
18540 static long int randx = 1;
18541 @dots{}
18542 randx = randx * 1103515245 + 12345;
18543 return (randx >> 16) & 077777;
18544 @end example
18546 In the following example, derived from the @acronym{GNU} C Library 2.5
18547 implementation of @code{mktime} (2006-09-09), the code assumes
18548 wraparound arithmetic in @code{+} to detect signed overflow:
18550 @example
18551 time_t t, t1, t2;
18552 int sec_requested, sec_adjustment;
18553 @dots{}
18554 t1 = t + sec_requested;
18555 t2 = t1 + sec_adjustment;
18556 if (((t1 < t) != (sec_requested < 0))
18557     | ((t2 < t1) != (sec_adjustment < 0)))
18558   return -1;
18559 @end example
18561 If your code looks like these examples, it is probably safe even though
18562 it does not strictly conform to the C standard.  This might lead one to
18563 believe that one can generally assume wraparound on overflow, but that
18564 is not always true, as can be seen in the next section.
18566 @node Optimization and Wraparound
18567 @subsection Optimizations That Break Wraparound Arithmetic
18568 @cindex loop induction
18570 Compilers sometimes generate code that is incompatible with wraparound
18571 integer arithmetic.  A simple example is an algebraic simplification: a
18572 compiler might translate @code{(i * 2000) / 1000} to @code{i * 2}
18573 because it assumes that @code{i * 2000} does not overflow.  The
18574 translation is not equivalent to the original when overflow occurs:
18575 e.g., in the typical case of 32-bit signed two's complement wraparound
18576 @code{int}, if @code{i} has type @code{int} and value @code{1073742},
18577 the original expression returns @minus{}2147483 but the optimized
18578 version returns the mathematically correct value 2147484.
18580 More subtly, loop induction optimizations often exploit the undefined
18581 behavior of signed overflow.  Consider the following contrived function
18582 @code{sumc}:
18584 @example
18586 sumc (int lo, int hi)
18588   int sum = 0;
18589   int i;
18590   for (i = lo; i <= hi; i++)
18591     sum ^= i * 53;
18592   return sum;
18594 @end example
18596 @noindent
18597 To avoid multiplying by 53 each time through the loop, an optimizing
18598 compiler might internally transform @code{sumc} to the equivalent of the
18599 following:
18601 @example
18603 transformed_sumc (int lo, int hi)
18605   int sum = 0;
18606   int hic = hi * 53;
18607   int ic;
18608   for (ic = lo * 53; ic <= hic; ic += 53)
18609     sum ^= ic;
18610   return sum;
18612 @end example
18614 @noindent
18615 This transformation is allowed by the C standard, but it is invalid for
18616 wraparound arithmetic when @code{INT_MAX / 53 < hi}, because then the
18617 overflow in computing expressions like @code{hi * 53} can cause the
18618 expression @code{i <= hi} to yield a different value from the
18619 transformed expression @code{ic <= hic}.
18621 For this reason, compilers that use loop induction and similar
18622 techniques often do not support reliable wraparound arithmetic when a
18623 loop induction variable like @code{ic} is involved.  Since loop
18624 induction variables are generated by the compiler, and are not visible
18625 in the source code, it is not always trivial to say whether the problem
18626 affects your code.
18628 Hardly any code actually depends on wraparound arithmetic in cases like
18629 these, so in practice these loop induction optimizations are almost
18630 always useful.  However, edge cases in this area can cause problems.
18631 For example:
18633 @example
18634 int j;
18635 for (j = 1; 0 < j; j *= 2)
18636   test (j);
18637 @end example
18639 @noindent
18640 Here, the loop attempts to iterate through all powers of 2 that
18641 @code{int} can represent, but the C standard allows a compiler to
18642 optimize away the comparison and generate an infinite loop,
18643 under the argument that behavior is undefined on overflow.  As of this
18644 writing this optimization is not done by any production version of
18645 @acronym{GCC} with @option{-O2}, but it might be performed by other
18646 compilers, or by more aggressive @acronym{GCC} optimization options,
18647 and the @acronym{GCC} developers have not decided whether it will
18648 continue to work with @acronym{GCC} and @option{-O2}.
18650 @node Signed Overflow Advice
18651 @subsection Practical Advice for Signed Overflow Issues
18652 @cindex integer overflow
18653 @cindex overflow, signed integer
18654 @cindex signed integer overflow
18655 @cindex wraparound arithmetic
18657 Ideally the safest approach is to avoid signed integer overflow
18658 entirely.  For example, instead of multiplying two signed integers, you
18659 can convert them to unsigned integers, multiply the unsigned values,
18660 then test whether the result is in signed range.
18662 Rewriting code in this way will be inconvenient, though, particularly if
18663 the signed values might be negative.  Also, it may hurt
18664 performance.  Using unsigned arithmetic to check for overflow is
18665 particularly painful to do portably and efficiently when dealing with an
18666 integer type like @code{uid_t} whose width and signedness vary from
18667 platform to platform.
18669 Furthermore, many C applications pervasively assume wraparound behavior
18670 and typically it is not easy to find and remove all these assumptions.
18671 Hence it is often useful to maintain nonstandard code that assumes
18672 wraparound on overflow, instead of rewriting the code.  The rest of this
18673 section attempts to give practical advice for this situation.
18675 If your code wants to detect signed integer overflow in @code{sum = a +
18676 b}, it is generally safe to use an expression like @code{(sum < a) != (b
18677 < 0)}.
18679 If your code uses a signed loop index, make sure that the index cannot
18680 overflow, along with all signed expressions derived from the index.
18681 Here is a contrived example of problematic code with two instances of
18682 overflow.
18684 @example
18685 for (i = INT_MAX - 10; i <= INT_MAX; i++)
18686   if (i + 1 < 0)
18687     @{
18688       report_overflow ();
18689       break;
18690     @}
18691 @end example
18693 @noindent
18694 Because of the two overflows, a compiler might optimize away or
18695 transform the two comparisons in a way that is incompatible with the
18696 wraparound assumption.
18698 If your code uses an expression like @code{(i * 2000) / 1000} and you
18699 actually want the multiplication to wrap around on overflow, use
18700 unsigned arithmetic
18701 to do it, e.g., @code{((int) (i * 2000u)) / 1000}.
18703 If your code assumes wraparound behavior and you want to insulate it
18704 against any @acronym{GCC} optimizations that would fail to support that
18705 behavior, you should use @acronym{GCC}'s @option{-fwrapv} option, which
18706 causes signed overflow to wrap around reliably (except for division and
18707 remainder, as discussed in the next section).
18709 If you need to port to platforms where signed integer overflow does not
18710 reliably wrap around (e.g., due to hardware overflow checking, or to
18711 highly aggressive optimizations), you should consider debugging with
18712 @acronym{GCC}'s @option{-ftrapv} option, which causes signed overflow to
18713 raise an exception.
18715 @node Signed Integer Division
18716 @subsection Signed Integer Division and Integer Overflow
18717 @cindex division, integer
18719 Overflow in signed
18720 integer division is not always harmless: for example, on CPUs of the
18721 i386 family, dividing @code{INT_MIN} by @code{-1} yields a SIGFPE signal
18722 which by default terminates the program.  Worse, taking the remainder
18723 of these two values typically yields the same signal on these CPUs,
18724 even though the C standard requires @code{INT_MIN % -1} to yield zero
18725 because the expression does not overflow.
18727 @node Preprocessor Arithmetic
18728 @section Preprocessor Arithmetic
18729 @cindex preprocessor arithmetic
18731 In C99, preprocessor arithmetic, used for @code{#if} expressions, must
18732 be evaluated as if all signed values are of type @code{intmax_t} and all
18733 unsigned values of type @code{uintmax_t}.  Many compilers are buggy in
18734 this area, though.  For example, as of 2007, Sun C mishandles @code{#if
18735 LLONG_MIN < 0} on a platform with 32-bit @code{long int} and 64-bit
18736 @code{long long int}.  Also, some older preprocessors mishandle
18737 constants ending in @code{LL}.  To work around these problems, you can
18738 compute the value of expressions like @code{LONG_MAX < LLONG_MAX} at
18739 @code{configure}-time rather than at @code{#if}-time.
18741 @node Null Pointers
18742 @section Properties of Null Pointers
18743 @cindex null pointers
18745 Most modern hosts reliably fail when you attempt to dereference a null
18746 pointer.
18748 On almost all modern hosts, null pointers use an all-bits-zero internal
18749 representation, so you can reliably use @code{memset} with 0 to set all
18750 the pointers in an array to null values.
18752 If @code{p} is a null pointer to an object type, the C expression
18753 @code{p + 0} always evaluates to @code{p} on modern hosts, even though
18754 the standard says that it has undefined behavior.
18756 @node Buffer Overruns
18757 @section Buffer Overruns and Subscript Errors
18758 @cindex buffer overruns
18760 Buffer overruns and subscript errors are the most common dangerous
18761 errors in C programs.  They result in undefined behavior because storing
18762 outside an array typically modifies storage that is used by some other
18763 object, and most modern systems lack runtime checks to catch these
18764 errors.  Programs should not rely on buffer overruns being caught.
18766 There is one exception to the usual rule that a portable program cannot
18767 address outside an array.  In C, it is valid to compute the address just
18768 past an object, e.g., @code{&a[N]} where @code{a} has @code{N} elements,
18769 so long as you do not dereference the resulting pointer.  But it is not
18770 valid to compute the address just before an object, e.g., @code{&a[-1]};
18771 nor is it valid to compute two past the end, e.g., @code{&a[N+1]}.  On
18772 most platforms @code{&a[-1] < &a[0] && &a[N] < &a[N+1]}, but this is not
18773 reliable in general, and it is usually easy enough to avoid the
18774 potential portability problem, e.g., by allocating an extra unused array
18775 element at the start or end.
18777 @uref{http://@/valgrind.org/, Valgrind} can catch many overruns.
18778 @acronym{GCC}
18779 users might also consider using the @option{-fmudflap} option to catch
18780 overruns.
18782 Buffer overruns are usually caused by off-by-one errors, but there are
18783 more subtle ways to get them.
18785 Using @code{int} values to index into an array or compute array sizes
18786 causes problems on typical 64-bit hosts where an array index might
18787 be @math{2^31} or larger.  Index values of type @code{size_t} avoid this
18788 problem, but cannot be negative.  Index values of type @code{ptrdiff_t}
18789 are signed, and are wide enough in practice.
18791 If you add or multiply two numbers to calculate an array size, e.g.,
18792 @code{malloc (x * sizeof y + z)}, havoc ensues if the addition or
18793 multiplication overflows.
18795 Many implementations of the @code{alloca} function silently misbehave
18796 and can generate buffer overflows if given sizes that are too large.
18797 The size limits are implementation dependent, but are at least 4000
18798 bytes on all platforms that we know about.
18800 The standard functions @code{asctime}, @code{asctime_r}, @code{ctime},
18801 @code{ctime_r}, and @code{gets} are prone to buffer overflows, and
18802 portable code should not use them unless the inputs are known to be
18803 within certain limits.  The time-related functions can overflow their
18804 buffers if given timestamps out of range (e.g., a year less than -999
18805 or greater than 9999).  Time-related buffer overflows cannot happen with
18806 recent-enough versions of the @acronym{GNU} C library, but are possible
18807 with other
18808 implementations.  The @code{gets} function is the worst, since it almost
18809 invariably overflows its buffer when presented with an input line larger
18810 than the buffer.
18812 @node Volatile Objects
18813 @section Volatile Objects
18814 @cindex volatile objects
18816 The keyword @code{volatile} is often misunderstood in portable code.
18817 Its use inhibits some memory-access optimizations, but programmers often
18818 wish that it had a different meaning than it actually does.
18820 @code{volatile} was designed for code that accesses special objects like
18821 memory-mapped device registers whose contents spontaneously change.
18822 Such code is inherently low-level, and it is difficult to specify
18823 portably what @code{volatile} means in these cases.  The C standard
18824 says, ``What constitutes an access to an object that has
18825 volatile-qualified type is implementation-defined,'' so in theory each
18826 implementation is supposed to fill in the gap by documenting what
18827 @code{volatile} means for that implementation.  In practice, though,
18828 this documentation is usually absent or incomplete.
18830 One area of confusion is the distinction between objects defined with
18831 volatile types, and volatile lvalues.  From the C standard's point of
18832 view, an object defined with a volatile type has externally visible
18833 behavior.  You can think of such objects as having little oscilloscope
18834 probes attached to them, so that the user can observe some properties of
18835 accesses to them, just as the user can observe data written to output
18836 files.  However, the standard does not make it clear whether users can
18837 observe accesses by volatile lvalues to ordinary objects.  For example:
18839 @example
18840 /* Declare and access a volatile object.
18841    Accesses to X are "visible" to users.  */
18842 static int volatile x;
18843 x = 1;
18845 /* Access two ordinary objects via a volatile lvalue.
18846    It's not clear whether accesses to *P are "visible".  */
18847 int y;
18848 int *z = malloc (sizeof (int));
18849 int volatile *p;
18850 p = &y;
18851 *p = 1;
18852 p = z;
18853 *p = 1;
18854 @end example
18856 Programmers often wish that @code{volatile} meant ``Perform the memory
18857 access here and now, without merging several memory accesses, without
18858 changing the memory word size, and without reordering.''  But the C
18859 standard does not require this.  For objects defined with a volatile
18860 type, accesses must be done before the next sequence point; but
18861 otherwise merging, reordering, and word-size change is allowed.  Worse,
18862 it is not clear from the standard whether volatile lvalues provide more
18863 guarantees in general than nonvolatile lvalues, if the underlying
18864 objects are ordinary.
18866 Even when accessing objects defined with a volatile type,
18867 the C standard allows only
18868 extremely limited signal handlers: the behavior is undefined if a signal
18869 handler reads any nonlocal object, or writes to any nonlocal object
18870 whose type is not @code{sig_atomic_t volatile}, or calls any standard
18871 library function other than @code{abort}, @code{signal}, and (if C99)
18872 @code{_Exit}.  Hence C compilers need not worry about a signal handler
18873 disturbing ordinary computation, unless the computation accesses a
18874 @code{sig_atomic_t volatile} lvalue that is not a local variable.
18875 (There is an obscure exception for accesses via a pointer to a volatile
18876 character, since it may point into part of a @code{sig_atomic_t
18877 volatile} object.)  Posix
18878 adds to the list of library functions callable from a portable signal
18879 handler, but otherwise is like the C standard in this area.
18881 Some C implementations allow memory-access optimizations within each
18882 translation unit, such that actual behavior agrees with the behavior
18883 required by the standard only when calling a function in some other
18884 translation unit, and a signal handler acts like it was called from a
18885 different translation unit.  The C standard hints that in these
18886 implementations, objects referred to by signal handlers ``would require
18887 explicit specification of @code{volatile} storage, as well as other
18888 implementation-defined restrictions.''  But unfortunately even for this
18889 special case these other restrictions are often not documented well.
18890 @xref{Volatiles, , When is a Volatile Object Accessed?, gcc, Using the
18891 @acronym{GNU} Compiler Collection (@acronym{GCC})}, for some
18892 restrictions imposed by @acronym{GCC}.  @xref{Defining Handlers, ,
18893 Defining Signal Handlers, libc, The @acronym{GNU} C Library}, for some
18894 restrictions imposed by the @acronym{GNU} C library.  Restrictions
18895 differ on other platforms.
18897 If possible, it is best to use a signal handler that fits within the
18898 limits imposed by the C and Posix standards.
18900 If this is not practical, you can try the following rules of thumb.  A
18901 signal handler should access only volatile lvalues, preferably lvalues
18902 that refer to objects defined with a volatile type, and should not
18903 assume that the accessed objects have an internally consistent state
18904 if they are larger than a machine word.  Furthermore, installers
18905 should employ compilers and compiler options that are commonly used
18906 for building operating system kernels, because kernels often need more
18907 from @code{volatile} than the C Standard requires, and installers who
18908 compile an application in a similar environment can sometimes benefit
18909 from the extra constraints imposed by kernels on compilers.
18910 Admittedly we are handwaving somewhat here, as there are few
18911 guarantees in this area; the rules of thumb may help to fix some bugs
18912 but there is a good chance that they will not fix them all.
18914 For @code{volatile}, C++ has the same problems that C does.
18915 Multithreaded applications have even more problems with @code{volatile},
18916 but they are beyond the scope of this section.
18918 The bottom line is that using @code{volatile} typically hurts
18919 performance but should not hurt correctness.  In some cases its use
18920 does help correctness, but these cases are often so poorly understood
18921 that all too often adding @code{volatile} to a data structure merely
18922 alleviates some symptoms of a bug while not fixing the bug in general.
18924 @node Floating Point Portability
18925 @section Floating Point Portability
18926 @cindex floating point
18928 Almost all modern systems use IEEE-754 floating point, and it is safe to
18929 assume IEEE-754 in most portable code these days.  For more information,
18930 please see David Goldberg's classic paper
18931 @uref{http://@/www.validlab.com/@/goldberg/@/paper.pdf, What Every Computer
18932 Scientist Should Know About Floating-Point Arithmetic}.
18934 @node Exiting Portably
18935 @section Exiting Portably
18936 @cindex exiting portably
18938 A C or C++ program can exit with status @var{N} by returning
18939 @var{N} from the @code{main} function.  Portable programs are supposed
18940 to exit either with status 0 or @code{EXIT_SUCCESS} to succeed, or with
18941 status @code{EXIT_FAILURE} to fail, but in practice it is portable to
18942 fail by exiting with status 1, and test programs that assume Posix can
18943 fail by exiting with status values from 1 through 255.  Programs on
18944 SunOS 2.0 (1985) through 3.5.2 (1988) incorrectly exited with zero
18945 status when @code{main} returned nonzero, but ancient systems like these
18946 are no longer of practical concern.
18948 A program can also exit with status @var{N} by passing @var{N} to the
18949 @code{exit} function, and a program can fail by calling the @code{abort}
18950 function.  If a program is specialized to just some platforms, it can fail
18951 by calling functions specific to those platforms, e.g., @code{_exit}
18952 (Posix) and @code{_Exit} (C99).  However, like other functions, an exit
18953 function should be declared, typically by including a header.  For
18954 example, if a C program calls @code{exit}, it should include @file{stdlib.h}
18955 either directly or via the default includes (@pxref{Default Includes}).
18957 A program can fail due to undefined behavior such as dereferencing a null
18958 pointer, but this is not recommended as undefined behavior allows an
18959 implementation to do whatever it pleases and this includes exiting
18960 successfully.
18963 @c ================================================== Manual Configuration
18965 @node Manual Configuration
18966 @chapter Manual Configuration
18968 A few kinds of features can't be guessed automatically by running test
18969 programs.  For example, the details of the object-file format, or
18970 special options that need to be passed to the compiler or linker.  You
18971 can check for such features using ad-hoc means, such as having
18972 @command{configure} check the output of the @code{uname} program, or
18973 looking for libraries that are unique to particular systems.  However,
18974 Autoconf provides a uniform method for handling unguessable features.
18976 @menu
18977 * Specifying Names::            Specifying the system type
18978 * Canonicalizing::              Getting the canonical system type
18979 * Using System Type::           What to do with the system type
18980 @end menu
18982 @node Specifying Names
18983 @section Specifying the System Type
18984 @cindex System type
18986 Autoconf-generated
18987 @command{configure} scripts can make decisions based on a canonical name
18988 for the system type, which has the form:
18989 @samp{@var{cpu}-@var{vendor}-@var{os}}, where @var{os} can be
18990 @samp{@var{system}} or @samp{@var{kernel}-@var{system}}
18992 @command{configure} can usually guess the canonical name for the type of
18993 system it's running on.  To do so it runs a script called
18994 @command{config.guess}, which infers the name using the @code{uname}
18995 command or symbols predefined by the C preprocessor.
18997 Alternately, the user can specify the system type with command line
18998 arguments to @command{configure}.  Doing so is necessary when
18999 cross-compiling.  In the most complex case of cross-compiling, three
19000 system types are involved.  The options to specify them are:
19002 @table @option
19003 @item --build=@var{build-type}
19004 the type of system on which the package is being configured and
19005 compiled.  It defaults to the result of running @command{config.guess}.
19007 @item --host=@var{host-type}
19008 the type of system on which the package runs.  By default it is the
19009 same as the build machine.  Specifying it enables the cross-compilation
19010 mode.
19012 @item --target=@var{target-type}
19013 the type of system for which any compiler tools in the package
19014 produce code (rarely needed).  By default, it is the same as host.
19015 @end table
19017 If you mean to override the result of @command{config.guess}, use
19018 @option{--build}, not @option{--host}, since the latter enables
19019 cross-compilation.  For historical reasons,
19020 whenever you specify @option{--host},
19021 be sure to specify @option{--build} too; this will be fixed in the
19022 future.  So, to enter cross-compilation mode, use a command like this
19024 @example
19025 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
19026 @end example
19028 @noindent
19029 Note that if you do not specify @option{--host}, @command{configure}
19030 fails if it can't run the code generated by the specified compiler.  For
19031 example, configuring as follows fails:
19033 @example
19034 ./configure CC=m68k-coff-gcc
19035 @end example
19037 When cross-compiling, @command{configure} will warn about any tools
19038 (compilers, linkers, assemblers) whose name is not prefixed with the
19039 host type.  This is an aid to users performing cross-compilation.
19040 Continuing the example above, if a cross-compiler named @command{cc} is
19041 used with a native @command{pkg-config}, then libraries found by
19042 @command{pkg-config} will likely cause subtle build failures; but using
19043 the names @command{m68k-coff-cc} and @command{m68k-coff-pkg-config}
19044 avoids any confusion.  Avoiding the warning is as simple as creating the
19045 correct symlinks naming the cross tools.
19047 @cindex @command{config.sub}
19048 @command{configure} recognizes short aliases for many system types; for
19049 example, @samp{decstation} can be used instead of
19050 @samp{mips-dec-ultrix4.2}.  @command{configure} runs a script called
19051 @command{config.sub} to canonicalize system type aliases.
19053 This section deliberately omits the description of the obsolete
19054 interface; see @ref{Hosts and Cross-Compilation}.
19057 @node Canonicalizing
19058 @section Getting the Canonical System Type
19059 @cindex System type
19060 @cindex Canonical system type
19062 The following macros make the system type available to @command{configure}
19063 scripts.
19065 @ovindex build_alias
19066 @ovindex host_alias
19067 @ovindex target_alias
19069 The variables @samp{build_alias}, @samp{host_alias}, and
19070 @samp{target_alias} are always exactly the arguments of @option{--build},
19071 @option{--host}, and @option{--target}; in particular, they are left empty
19072 if the user did not use them, even if the corresponding
19073 @code{AC_CANONICAL} macro was run.  Any configure script may use these
19074 variables anywhere.  These are the variables that should be used when in
19075 interaction with the user.
19077 If you need to recognize some special environments based on their system
19078 type, run the following macros to get canonical system names.  These
19079 variables are not set before the macro call.
19081 If you use these macros, you must distribute @command{config.guess} and
19082 @command{config.sub} along with your source code.  @xref{Output}, for
19083 information about the @code{AC_CONFIG_AUX_DIR} macro which you can use
19084 to control in which directory @command{configure} looks for those scripts.
19087 @defmac AC_CANONICAL_BUILD
19088 @acindex{CANONICAL_BUILD}
19089 @ovindex build
19090 @ovindex build_cpu
19091 @ovindex build_vendor
19092 @ovindex build_os
19093 Compute the canonical build-system type variable, @code{build}, and its
19094 three individual parts @code{build_cpu}, @code{build_vendor}, and
19095 @code{build_os}.
19097 If @option{--build} was specified, then @code{build} is the
19098 canonicalization of @code{build_alias} by @command{config.sub},
19099 otherwise it is determined by the shell script @command{config.guess}.
19100 @end defmac
19102 @defmac AC_CANONICAL_HOST
19103 @acindex{CANONICAL_HOST}
19104 @ovindex host
19105 @ovindex host_cpu
19106 @ovindex host_vendor
19107 @ovindex host_os
19108 Compute the canonical host-system type variable, @code{host}, and its
19109 three individual parts @code{host_cpu}, @code{host_vendor}, and
19110 @code{host_os}.
19112 If @option{--host} was specified, then @code{host} is the
19113 canonicalization of @code{host_alias} by @command{config.sub},
19114 otherwise it defaults to @code{build}.
19115 @end defmac
19117 @defmac AC_CANONICAL_TARGET
19118 @acindex{CANONICAL_TARGET}
19119 @ovindex target
19120 @ovindex target_cpu
19121 @ovindex target_vendor
19122 @ovindex target_os
19123 Compute the canonical target-system type variable, @code{target}, and its
19124 three individual parts @code{target_cpu}, @code{target_vendor}, and
19125 @code{target_os}.
19127 If @option{--target} was specified, then @code{target} is the
19128 canonicalization of @code{target_alias} by @command{config.sub},
19129 otherwise it defaults to @code{host}.
19130 @end defmac
19132 Note that there can be artifacts due to the backward compatibility
19133 code.  See @xref{Hosts and Cross-Compilation}, for more.
19135 @node Using System Type
19136 @section Using the System Type
19138 In @file{configure.ac} the system type is generally used by one or more
19139 @code{case} statements to select system-specifics.  Shell wildcards can
19140 be used to match a group of system types.
19142 For example, an extra assembler code object file could be chosen, giving
19143 access to a CPU cycle counter register.  @code{$(CYCLE_OBJ)} in the
19144 following would be used in a makefile to add the object to a
19145 program or library.
19147 @example
19148 AS_CASE([$host],
19149   [alpha*-*-*], [CYCLE_OBJ=rpcc.o],
19150   [i?86-*-*],   [CYCLE_OBJ=rdtsc.o],
19151   [CYCLE_OBJ=""]
19153 AC_SUBST([CYCLE_OBJ])
19154 @end example
19156 @code{AC_CONFIG_LINKS} (@pxref{Configuration Links}) is another good way
19157 to select variant source files, for example optimized code for some
19158 CPUs.  The configured CPU type doesn't always indicate exact CPU types,
19159 so some runtime capability checks may be necessary too.
19161 @example
19162 case $host in
19163   alpha*-*-*)   AC_CONFIG_LINKS([dither.c:alpha/dither.c]) ;;
19164   powerpc*-*-*) AC_CONFIG_LINKS([dither.c:powerpc/dither.c]) ;;
19165   *-*-*)        AC_CONFIG_LINKS([dither.c:generic/dither.c]) ;;
19166 esac
19167 @end example
19169 The host system type can also be used to find cross-compilation tools
19170 with @code{AC_CHECK_TOOL} (@pxref{Generic Programs}).
19172 The above examples all show @samp{$host}, since this is where the code
19173 is going to run.  Only rarely is it necessary to test @samp{$build}
19174 (which is where the build is being done).
19176 Whenever you're tempted to use @samp{$host} it's worth considering
19177 whether some sort of probe would be better.  New system types come along
19178 periodically or previously missing features are added.  Well-written
19179 probes can adapt themselves to such things, but hard-coded lists of
19180 names can't.  Here are some guidelines,
19182 @itemize @bullet
19183 @item
19184 Availability of libraries and library functions should always be checked
19185 by probing.
19186 @item
19187 Variant behavior of system calls is best identified with runtime tests
19188 if possible, but bug workarounds or obscure difficulties might have to
19189 be driven from @samp{$host}.
19190 @item
19191 Assembler code is inevitably highly CPU-specific and is best selected
19192 according to @samp{$host_cpu}.
19193 @item
19194 Assembler variations like underscore prefix on globals or ELF versus
19195 COFF type directives are however best determined by probing, perhaps
19196 even examining the compiler output.
19197 @end itemize
19199 @samp{$target} is for use by a package creating a compiler or similar.
19200 For ordinary packages it's meaningless and should not be used.  It
19201 indicates what the created compiler should generate code for, if it can
19202 cross-compile.  @samp{$target} generally selects various hard-coded CPU
19203 and system conventions, since usually the compiler or tools under
19204 construction themselves determine how the target works.
19207 @c ===================================================== Site Configuration.
19209 @node Site Configuration
19210 @chapter Site Configuration
19212 @command{configure} scripts support several kinds of local configuration
19213 decisions.  There are ways for users to specify where external software
19214 packages are, include or exclude optional features, install programs
19215 under modified names, and set default values for @command{configure}
19216 options.
19218 @menu
19219 * Help Formatting::             Customizing @samp{configure --help}
19220 * External Software::           Working with other optional software
19221 * Package Options::             Selecting optional features
19222 * Pretty Help Strings::         Formatting help string
19223 * Option Checking::             Controlling checking of @command{configure} options
19224 * Site Details::                Configuring site details
19225 * Transforming Names::          Changing program names when installing
19226 * Site Defaults::               Giving @command{configure} local defaults
19227 @end menu
19229 @node Help Formatting
19230 @section Controlling Help Output
19232 Users consult @samp{configure --help} to learn of configuration
19233 decisions specific to your package.  By default, @command{configure}
19234 breaks this output into sections for each type of option; within each
19235 section, help strings appear in the order @file{configure.ac} defines
19236 them:
19238 @example
19239 Optional Features:
19240   @dots{}
19241   --enable-bar            include bar
19243 Optional Packages:
19244   @dots{}
19245   --with-foo              use foo
19246 @end example
19248 @defmac AC_PRESERVE_HELP_ORDER
19249 @acindex{PRESERVE_HELP_ORDER}
19251 Request an alternate @option{--help} format, in which options of all
19252 types appear together, in the order defined.  Call this macro before any
19253 @code{AC_ARG_ENABLE} or @code{AC_ARG_WITH}.
19255 @example
19256 Optional Features and Packages:
19257   @dots{}
19258   --enable-bar            include bar
19259   --with-foo              use foo
19260 @end example
19262 @end defmac
19264 @node External Software
19265 @section Working With External Software
19266 @cindex External software
19268 Some packages require, or can optionally use, other software packages
19269 that are already installed.  The user can give @command{configure}
19270 command line options to specify which such external software to use.
19271 The options have one of these forms:
19273 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
19274 @c awful.
19275 @example
19276 --with-@var{package}[=@var{arg}]
19277 --without-@var{package}
19278 @end example
19280 For example, @option{--with-gnu-ld} means work with the @acronym{GNU} linker
19281 instead of some other linker.  @option{--with-x} means work with The X
19282 Window System.
19284 The user can give an argument by following the package name with
19285 @samp{=} and the argument.  Giving an argument of @samp{no} is for
19286 packages that are used by default; it says to @emph{not} use the
19287 package.  An argument that is neither @samp{yes} nor @samp{no} could
19288 include a name or number of a version of the other package, to specify
19289 more precisely which other package this program is supposed to work
19290 with.  If no argument is given, it defaults to @samp{yes}.
19291 @option{--without-@var{package}} is equivalent to
19292 @option{--with-@var{package}=no}.
19294 Normally @command{configure} scripts complain about
19295 @option{--with-@var{package}} options that they do not support.
19296 @xref{Option Checking}, for details, and for how to override the
19297 defaults.
19299 For each external software package that may be used, @file{configure.ac}
19300 should call @code{AC_ARG_WITH} to detect whether the @command{configure}
19301 user asked to use it.  Whether each package is used or not by default,
19302 and which arguments are valid, is up to you.
19304 @anchor{AC_ARG_WITH}
19305 @defmac AC_ARG_WITH (@var{package}, @var{help-string}, @
19306   @ovar{action-if-given}, @ovar{action-if-not-given})
19307 @acindex{ARG_WITH}
19308 If the user gave @command{configure} the option @option{--with-@var{package}}
19309 or @option{--without-@var{package}}, run shell commands
19310 @var{action-if-given}.  If neither option was given, run shell commands
19311 @var{action-if-not-given}.  The name @var{package} indicates another
19312 software package that this program should work with.  It should consist
19313 only of alphanumeric characters, dashes, and dots.
19315 The option's argument is available to the shell commands
19316 @var{action-if-given} in the shell variable @code{withval}, which is
19317 actually just the value of the shell variable named
19318 @code{with_@var{package}}, with any non-alphanumeric characters in
19319 @var{package} changed into @samp{_}.  You may use that variable instead,
19320 if you wish.
19322 The argument @var{help-string} is a description of the option that
19323 looks like this:
19324 @example
19325   --with-readline         support fancy command line editing
19326 @end example
19328 @noindent
19329 @var{help-string} may be more than one line long, if more detail is
19330 needed.  Just make sure the columns line up in @samp{configure
19331 --help}.  Avoid tabs in the help string.  You'll need to enclose the
19332 help string in @samp{[} and @samp{]} in order to produce the leading
19333 blanks.
19335 You should format your @var{help-string} with the macro
19336 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
19338 The following example shows how to use the @code{AC_ARG_WITH} macro in
19339 a common situation.  You want to let the user decide whether to enable
19340 support for an external library (e.g., the readline library); if the user
19341 specified neither @option{--with-readline} nor @option{--without-readline},
19342 you want to enable support for readline only if the library is available
19343 on the system.
19345 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19346 @example
19347 AC_ARG_WITH([readline],
19348   [AS_HELP_STRING([--with-readline],
19349     [support fancy command line editing @@<:@@default=check@@:>@@])],
19350   [],
19351   [with_readline=check])
19353 LIBREADLINE=
19354 AS_IF([test "x$with_readline" != xno],
19355   [AC_CHECK_LIB([readline], [main],
19356     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19357      AC_DEFINE([HAVE_LIBREADLINE], [1],
19358                [Define if you have libreadline])
19359     ],
19360     [if test "x$with_readline" != xcheck; then
19361        AC_MSG_FAILURE(
19362          [--with-readline was given, but test for readline failed])
19363      fi
19364     ], -lncurses)])
19365 @end example
19367 The next example shows how to use @code{AC_ARG_WITH} to give the user the
19368 possibility to enable support for the readline library, in case it is still
19369 experimental and not well tested, and is therefore disabled by default.
19371 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19372 @example
19373 AC_ARG_WITH([readline],
19374   [AS_HELP_STRING([--with-readline],
19375     [enable experimental support for readline])],
19376   [],
19377   [with_readline=no])
19379 LIBREADLINE=
19380 AS_IF([test "x$with_readline" != xno],
19381   [AC_CHECK_LIB([readline], [main],
19382     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19383      AC_DEFINE([HAVE_LIBREADLINE], [1],
19384                [Define if you have libreadline])
19385     ],
19386     [AC_MSG_FAILURE(
19387        [--with-readline was given, but test for readline failed])],
19388     [-lncurses])])
19389 @end example
19391 The last example shows how to use @code{AC_ARG_WITH} to give the user the
19392 possibility to disable support for the readline library, given that it is
19393 an important feature and that it should be enabled by default.
19395 @c FIXME: Remove AS_IF when the problem of AC_REQUIRE within `if' is solved.
19396 @example
19397 AC_ARG_WITH([readline],
19398   [AS_HELP_STRING([--without-readline],
19399     [disable support for readline])],
19400   [],
19401   [with_readline=yes])
19403 LIBREADLINE=
19404 AS_IF([test "x$with_readline" != xno],
19405   [AC_CHECK_LIB([readline], [main],
19406     [AC_SUBST([LIBREADLINE], ["-lreadline -lncurses"])
19407      AC_DEFINE([HAVE_LIBREADLINE], [1],
19408                [Define if you have libreadline])
19409     ],
19410     [AC_MSG_FAILURE(
19411        [readline test failed (--without-readline to disable)])],
19412     [-lncurses])])
19413 @end example
19415 These three examples can be easily adapted to the case where
19416 @code{AC_ARG_ENABLE} should be preferred to @code{AC_ARG_WITH} (see
19417 @ref{Package Options}).
19418 @end defmac
19420 @node Package Options
19421 @section Choosing Package Options
19422 @cindex Package options
19423 @cindex Options, package
19425 If a software package has optional compile-time features, the user can
19426 give @command{configure} command line options to specify whether to
19427 compile them.  The options have one of these forms:
19429 @c FIXME: Can't use @ovar here, Texinfo 4.0 goes lunatic and emits something
19430 @c awful.
19431 @example
19432 --enable-@var{feature}[=@var{arg}]
19433 --disable-@var{feature}
19434 @end example
19436 These options allow users to choose which optional features to build and
19437 install.  @option{--enable-@var{feature}} options should never make a
19438 feature behave differently or cause one feature to replace another.
19439 They should only cause parts of the program to be built rather than left
19440 out.
19442 The user can give an argument by following the feature name with
19443 @samp{=} and the argument.  Giving an argument of @samp{no} requests
19444 that the feature @emph{not} be made available.  A feature with an
19445 argument looks like @option{--enable-debug=stabs}.  If no argument is
19446 given, it defaults to @samp{yes}.  @option{--disable-@var{feature}} is
19447 equivalent to @option{--enable-@var{feature}=no}.
19449 Normally @command{configure} scripts complain about
19450 @option{--enable-@var{package}} options that they do not support.
19451 @xref{Option Checking}, for details, and for how to override the
19452 defaults.
19454 For each optional feature, @file{configure.ac} should call
19455 @code{AC_ARG_ENABLE} to detect whether the @command{configure} user asked
19456 to include it.  Whether each feature is included or not by default, and
19457 which arguments are valid, is up to you.
19459 @anchor{AC_ARG_ENABLE}
19460 @defmac AC_ARG_ENABLE (@var{feature}, @var{help-string}, @
19461   @ovar{action-if-given}, @ovar{action-if-not-given})
19462 @acindex{ARG_ENABLE}
19463 If the user gave @command{configure} the option
19464 @option{--enable-@var{feature}} or @option{--disable-@var{feature}}, run
19465 shell commands @var{action-if-given}.  If neither option was given, run
19466 shell commands @var{action-if-not-given}.  The name @var{feature}
19467 indicates an optional user-level facility.  It should consist only of
19468 alphanumeric characters, dashes, and dots.
19470 The option's argument is available to the shell commands
19471 @var{action-if-given} in the shell variable @code{enableval}, which is
19472 actually just the value of the shell variable named
19473 @code{enable_@var{feature}}, with any non-alphanumeric characters in
19474 @var{feature} changed into @samp{_}.  You may use that variable instead,
19475 if you wish.  The @var{help-string} argument is like that of
19476 @code{AC_ARG_WITH} (@pxref{External Software}).
19478 You should format your @var{help-string} with the macro
19479 @code{AS_HELP_STRING} (@pxref{Pretty Help Strings}).
19481 See the examples suggested with the definition of @code{AC_ARG_WITH}
19482 (@pxref{External Software}) to get an idea of possible applications of
19483 @code{AC_ARG_ENABLE}.
19484 @end defmac
19486 @node Pretty Help Strings
19487 @section Making Your Help Strings Look Pretty
19488 @cindex Help strings
19490 Properly formatting the @samp{help strings} which are used in
19491 @code{AC_ARG_WITH} (@pxref{External Software}) and @code{AC_ARG_ENABLE}
19492 (@pxref{Package Options}) can be challenging.  Specifically, you want
19493 your own @samp{help strings} to line up in the appropriate columns of
19494 @samp{configure --help} just like the standard Autoconf @samp{help
19495 strings} do.  This is the purpose of the @code{AS_HELP_STRING} macro.
19497 @anchor{AS_HELP_STRING}
19498 @defmac AS_HELP_STRING (@var{left-hand-side}, @var{right-hand-side} @
19499   @dvar{indent-column, 26}, @dvar{wrap-column, 79})
19500 @asindex{HELP_STRING}
19502 Expands into an help string that looks pretty when the user executes
19503 @samp{configure --help}.  It is typically used in @code{AC_ARG_WITH}
19504 (@pxref{External Software}) or @code{AC_ARG_ENABLE} (@pxref{Package
19505 Options}).  The following example makes this clearer.
19507 @example
19508 AC_ARG_WITH([foo],
19509   [AS_HELP_STRING([--with-foo],
19510      [use foo (default is no)])],
19511   [use_foo=$withval],
19512   [use_foo=no])
19513 @end example
19515 Then the last few lines of @samp{configure --help} appear like
19516 this:
19518 @example
19519 --enable and --with options recognized:
19520   --with-foo              use foo (default is no)
19521 @end example
19523 Macro expansion is performed on the first argument.  However, the second
19524 argument of @code{AS_HELP_STRING} is treated as a whitespace separated
19525 list of text to be reformatted, and is not subject to macro expansion.
19526 Since it is not expanded, it should not be double quoted.
19527 @xref{Autoconf Language}, for a more detailed explanation.
19529 The @code{AS_HELP_STRING} macro is particularly helpful when the
19530 @var{left-hand-side} and/or @var{right-hand-side} are composed of macro
19531 arguments, as shown in the following example.  Be aware that
19532 @var{left-hand-side} may not expand to unbalanced quotes,
19533 although quadrigraphs can be used.
19535 @example
19536 AC_DEFUN([MY_ARG_WITH],
19537   [AC_ARG_WITH(m4_translit([[$1]], [_], [-]),
19538      [AS_HELP_STRING([--with-m4_translit([$1], [_], [-])],
19539                      [use $1 (default is $2)])],
19540      [use_[]$1=$withval],
19541      [use_[]$1=$2])])
19542 MY_ARG_WITH([a_b], [no])
19543 @end example
19544 @noindent
19545 Here, the last few lines of @samp{configure --help} will include:
19547 @example
19548 --enable and --with options recognized:
19549   --with-a-b              use a_b (default is no)
19550 @end example
19552 The parameters @var{indent-column} and @var{wrap-column} were introduced
19553 in Autoconf 2.62.  Generally, they should not be specified; they exist
19554 for fine-tuning of the wrapping.
19555 @example
19556 AS_HELP_STRING([--option], [description of option])
19557 @result{}  --option                description of option
19558 AS_HELP_STRING([--option], [description of option], [15], [30])
19559 @result{}  --option     description of
19560 @result{}               option
19561 @end example
19562 @end defmac
19565 @node Option Checking
19566 @section Controlling Checking of @command{configure} Options
19567 @cindex Options, Package
19569 The @command{configure} script checks its command-line options against a
19570 list of known options, like @option{--help} or @option{--config-cache}.
19571 An unknown option ordinarily indicates a mistake by the user and
19572 @command{configure} halts with an error.  However, by default unknown
19573 @option{--with-@var{package}} and @option{--enable-@var{feature}}
19574 options elicit only a warning, to support configuring entire source
19575 trees.
19577 Source trees often contain multiple packages with a top-level
19578 @command{configure} script that uses the @code{AC_CONFIG_SUBDIRS} macro
19579 (@pxref{Subdirectories}).  Because the packages generally support
19580 different @option{--with-@var{package}} and
19581 @option{--enable-@var{feature}} options, the @acronym{GNU} Coding
19582 Standards say they must accept unrecognized options without halting.
19583 Even a warning message is undesirable here, so @code{AC_CONFIG_SUBDIRS}
19584 automatically disables the warnings.
19586 This default behavior may be modified in two ways.  First, the installer
19587 can invoke @code{configure --disable-option-checking} to disable
19588 these warnings, or invoke @code{configure --enable-option-checking=fatal}
19589 options to turn them into fatal errors, respectively.  Second, the
19590 maintainer can use @code{AC_DISABLE_OPTION_CHECKING}.
19592 @defmac AC_DISABLE_OPTION_CHECKING
19593 @acindex{DISABLE_OPTION_CHECKING}
19595 By default, disable warnings related to any unrecognized
19596 @option{--with-@var{package}} or @option{--enable-@var{feature}}
19597 options.  This is implied by @code{AC_CONFIG_SUBDIRS}.
19599 The installer can override this behavior by passing
19600 @option{--enable-option-checking} (enable warnings) or
19601 @option{--enable-option-checking=fatal} (enable errors) to
19602 @command{configure}.
19603 @end defmac
19606 @node Site Details
19607 @section Configuring Site Details
19608 @cindex Site details
19610 Some software packages require complex site-specific information.  Some
19611 examples are host names to use for certain services, company names, and
19612 email addresses to contact.  Since some configuration scripts generated
19613 by Metaconfig ask for such information interactively, people sometimes
19614 wonder how to get that information in Autoconf-generated configuration
19615 scripts, which aren't interactive.
19617 Such site configuration information should be put in a file that is
19618 edited @emph{only by users}, not by programs.  The location of the file
19619 can either be based on the @code{prefix} variable, or be a standard
19620 location such as the user's home directory.  It could even be specified
19621 by an environment variable.  The programs should examine that file at
19622 runtime, rather than at compile time.  Runtime configuration is more
19623 convenient for users and makes the configuration process simpler than
19624 getting the information while configuring.  @xref{Directory Variables, ,
19625 Variables for Installation Directories, standards, @acronym{GNU} Coding
19626 Standards}, for more information on where to put data files.
19628 @node Transforming Names
19629 @section Transforming Program Names When Installing
19630 @cindex Transforming program names
19631 @cindex Program names, transforming
19633 Autoconf supports changing the names of programs when installing them.
19634 In order to use these transformations, @file{configure.ac} must call the
19635 macro @code{AC_ARG_PROGRAM}.
19637 @defmac AC_ARG_PROGRAM
19638 @acindex{ARG_PROGRAM}
19639 @ovindex program_transform_name
19640 Place in output variable @code{program_transform_name} a sequence of
19641 @code{sed} commands for changing the names of installed programs.
19643 If any of the options described below are given to @command{configure},
19644 program names are transformed accordingly.  Otherwise, if
19645 @code{AC_CANONICAL_TARGET} has been called and a @option{--target} value
19646 is given, the target type followed by a dash is used as a prefix.
19647 Otherwise, no program name transformation is done.
19648 @end defmac
19650 @menu
19651 * Transformation Options::      @command{configure} options to transform names
19652 * Transformation Examples::     Sample uses of transforming names
19653 * Transformation Rules::        Makefile uses of transforming names
19654 @end menu
19656 @node Transformation Options
19657 @subsection Transformation Options
19659 You can specify name transformations by giving @command{configure} these
19660 command line options:
19662 @table @option
19663 @item --program-prefix=@var{prefix}
19664 prepend @var{prefix} to the names;
19666 @item --program-suffix=@var{suffix}
19667 append @var{suffix} to the names;
19669 @item --program-transform-name=@var{expression}
19670 perform @code{sed} substitution @var{expression} on the names.
19671 @end table
19673 @node Transformation Examples
19674 @subsection Transformation Examples
19676 These transformations are useful with programs that can be part of a
19677 cross-compilation development environment.  For example, a
19678 cross-assembler running on a Sun 4 configured with
19679 @option{--target=i960-vxworks} is normally installed as
19680 @file{i960-vxworks-as}, rather than @file{as}, which could be confused
19681 with a native Sun 4 assembler.
19683 You can force a program name to begin with @file{g}, if you don't want
19684 @acronym{GNU} programs installed on your system to shadow other programs with
19685 the same name.  For example, if you configure @acronym{GNU} @code{diff} with
19686 @option{--program-prefix=g}, then when you run @samp{make install} it is
19687 installed as @file{/usr/local/bin/gdiff}.
19689 As a more sophisticated example, you could use
19691 @example
19692 --program-transform-name='s/^/g/; s/^gg/g/; s/^gless/less/'
19693 @end example
19694 @noindent
19696 to prepend @samp{g} to most of the program names in a source tree,
19697 excepting those like @code{gdb} that already have one and those like
19698 @code{less} and @code{lesskey} that aren't @acronym{GNU} programs.  (That is
19699 assuming that you have a source tree containing those programs that is
19700 set up to use this feature.)
19702 One way to install multiple versions of some programs simultaneously is
19703 to append a version number to the name of one or both.  For example, if
19704 you want to keep Autoconf version 1 around for awhile, you can configure
19705 Autoconf version 2 using @option{--program-suffix=2} to install the
19706 programs as @file{/usr/local/bin/autoconf2},
19707 @file{/usr/local/bin/autoheader2}, etc.  Nevertheless, pay attention
19708 that only the binaries are renamed, therefore you'd have problems with
19709 the library files which might overlap.
19711 @node Transformation Rules
19712 @subsection Transformation Rules
19714 Here is how to use the variable @code{program_transform_name} in a
19715 @file{Makefile.in}:
19717 @example
19718 PROGRAMS = cp ls rm
19719 transform = @@program_transform_name@@
19720 install:
19721         for p in $(PROGRAMS); do \
19722           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/`echo $$p | \
19723                                               sed '$(transform)'`; \
19724         done
19726 uninstall:
19727         for p in $(PROGRAMS); do \
19728           rm -f $(DESTDIR)$(bindir)/`echo $$p | sed '$(transform)'`; \
19729         done
19730 @end example
19732 It is guaranteed that @code{program_transform_name} is never empty, and
19733 that there are no useless separators.  Therefore you may safely embed
19734 @code{program_transform_name} within a sed program using @samp{;}:
19736 @example
19737 transform = @@program_transform_name@@
19738 transform_exe = s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/
19739 @end example
19741 Whether to do the transformations on documentation files (Texinfo or
19742 @code{man}) is a tricky question; there seems to be no perfect answer,
19743 due to the several reasons for name transforming.  Documentation is not
19744 usually particular to a specific architecture, and Texinfo files do not
19745 conflict with system documentation.  But they might conflict with
19746 earlier versions of the same files, and @code{man} pages sometimes do
19747 conflict with system documentation.  As a compromise, it is probably
19748 best to do name transformations on @code{man} pages but not on Texinfo
19749 manuals.
19751 @node Site Defaults
19752 @section Setting Site Defaults
19753 @cindex Site defaults
19754 @cindex config.site
19756 Autoconf-generated @command{configure} scripts allow your site to provide
19757 default values for some configuration values.  You do this by creating
19758 site- and system-wide initialization files.
19760 @evindex CONFIG_SITE
19761 If the environment variable @code{CONFIG_SITE} is set, @command{configure}
19762 uses its value as the name of a shell script to read.  Otherwise, it
19763 reads the shell script @file{@var{prefix}/share/config.site} if it exists,
19764 then @file{@var{prefix}/etc/config.site} if it exists.  Thus,
19765 settings in machine-specific files override those in machine-independent
19766 ones in case of conflict.
19768 Site files can be arbitrary shell scripts, but only certain kinds of
19769 code are really appropriate to be in them.  Because @command{configure}
19770 reads any cache file after it has read any site files, a site file can
19771 define a default cache file to be shared between all Autoconf-generated
19772 @command{configure} scripts run on that system (@pxref{Cache Files}).  If
19773 you set a default cache file in a site file, it is a good idea to also
19774 set the output variable @code{CC} in that site file, because the cache
19775 file is only valid for a particular compiler, but many systems have
19776 several available.
19778 You can examine or override the value set by a command line option to
19779 @command{configure} in a site file; options set shell variables that have
19780 the same names as the options, with any dashes turned into underscores.
19781 The exceptions are that @option{--without-} and @option{--disable-} options
19782 are like giving the corresponding @option{--with-} or @option{--enable-}
19783 option and the value @samp{no}.  Thus, @option{--cache-file=localcache}
19784 sets the variable @code{cache_file} to the value @samp{localcache};
19785 @option{--enable-warnings=no} or @option{--disable-warnings} sets the variable
19786 @code{enable_warnings} to the value @samp{no}; @option{--prefix=/usr} sets the
19787 variable @code{prefix} to the value @samp{/usr}; etc.
19789 Site files are also good places to set default values for other output
19790 variables, such as @code{CFLAGS}, if you need to give them non-default
19791 values: anything you would normally do, repetitively, on the command
19792 line.  If you use non-default values for @var{prefix} or
19793 @var{exec_prefix} (wherever you locate the site file), you can set them
19794 in the site file if you specify it with the @code{CONFIG_SITE}
19795 environment variable.
19797 You can set some cache values in the site file itself.  Doing this is
19798 useful if you are cross-compiling, where it is impossible to check features
19799 that require running a test program.  You could ``prime the cache'' by
19800 setting those values correctly for that system in
19801 @file{@var{prefix}/etc/config.site}.  To find out the names of the cache
19802 variables you need to set, look for shell variables with @samp{_cv_} in
19803 their names in the affected @command{configure} scripts, or in the Autoconf
19804 M4 source code for those macros.
19806 The cache file is careful to not override any variables set in the site
19807 files.  Similarly, you should not override command-line options in the
19808 site files.  Your code should check that variables such as @code{prefix}
19809 and @code{cache_file} have their default values (as set near the top of
19810 @command{configure}) before changing them.
19812 Here is a sample file @file{/usr/share/local/@/gnu/share/@/config.site}.  The
19813 command @samp{configure --prefix=/usr/share/local/gnu} would read this
19814 file (if @code{CONFIG_SITE} is not set to a different file).
19816 @example
19817 # /usr/share/local/gnu/share/config.site for configure
19819 # Change some defaults.
19820 test "$prefix" = NONE && prefix=/usr/share/local/gnu
19821 test "$exec_prefix" = NONE && exec_prefix=/usr/local/gnu
19822 test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
19823 test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
19825 # Give Autoconf 2.x generated configure scripts a shared default
19826 # cache file for feature test results, architecture-specific.
19827 if test "$cache_file" = /dev/null; then
19828   cache_file="$prefix/var/config.cache"
19829   # A cache file is only valid for one C compiler.
19830   CC=gcc
19832 @end example
19834 @cindex Filesystem Hierarchy Standard
19835 @cindex FHS
19837 Another use of @file{config.site} is for priming the directory variables
19838 in a manner consistent with the Filesystem Hierarchy Standard
19839 (@acronym{FHS}).  Once the following file is installed at
19840 @file{/usr/share/config.site}, a user can execute simply
19841 @code{./configure --prefix=/usr} to get all the directories chosen in
19842 the locations recommended by @acronym{FHS}.
19844 @example
19845 # /usr/share/config.site for FHS defaults when installing below /usr,
19846 # and the respective settings were not changed on the command line.
19847 if test "$prefix" = /usr; then
19848   test "$sysconfdir" = '$@{prefix@}/etc' && sysconfdir=/etc
19849   test "$sharedstatedir" = '$@{prefix@}/com' && sharedstatedir=/var
19850   test "$localstatedir" = '$@{prefix@}/var' && localstatedir=/var
19852 @end example
19854 @cindex lib64
19855 @cindex 64-bit libraries
19856 Likewise, on platforms where 64-bit libraries are built by default, then
19857 installed in @file{/usr/local/@/lib64} instead of @file{/usr/local/@/lib},
19858 it is appropriate to install @file{/usr/local/@/share/config.site}:
19860 @example
19861 # /usr/local/share/config.site for platforms that prefer
19862 # the directory /usr/local/lib64 over /usr/local/lib.
19863 test "$libdir" = '$@{exec_prefix@}/lib' && libdir='$@{exec_prefix@}/lib64'
19864 @end example
19867 @c ============================================== Running configure Scripts.
19869 @node Running configure Scripts
19870 @chapter Running @command{configure} Scripts
19871 @cindex @command{configure}
19873 Below are instructions on how to configure a package that uses a
19874 @command{configure} script, suitable for inclusion as an @file{INSTALL}
19875 file in the package.  A plain-text version of @file{INSTALL} which you
19876 may use comes with Autoconf.
19878 @menu
19879 * Basic Installation::          Instructions for typical cases
19880 * Compilers and Options::       Selecting compilers and optimization
19881 * Multiple Architectures::      Compiling for multiple architectures at once
19882 * Installation Names::          Installing in different directories
19883 * Optional Features::           Selecting optional features
19884 * Particular Systems::          Particular systems
19885 * System Type::                 Specifying the system type
19886 * Sharing Defaults::            Setting site-wide defaults for @command{configure}
19887 * Defining Variables::          Specifying the compiler etc.
19888 * configure Invocation::        Changing how @command{configure} runs
19889 @end menu
19891 @set autoconf
19892 @include install.texi
19895 @c ============================================== config.status Invocation
19897 @node config.status Invocation
19898 @chapter config.status Invocation
19899 @cindex @command{config.status}
19901 The @command{configure} script creates a file named @file{config.status},
19902 which actually configures, @dfn{instantiates}, the template files.  It
19903 also records the configuration options that were specified when the
19904 package was last configured in case reconfiguring is needed.
19906 Synopsis:
19907 @example
19908 ./config.status @var{option}@dots{} [@var{file}@dots{}]
19909 @end example
19911 It configures the @var{files}; if none are specified, all the templates
19912 are instantiated.  The files must be specified without their
19913 dependencies, as in
19915 @example
19916 ./config.status foobar
19917 @end example
19919 @noindent
19922 @example
19923 ./config.status foobar:foo.in:bar.in
19924 @end example
19926 The supported options are:
19928 @table @option
19929 @item --help
19930 @itemx -h
19931 Print a summary of the command line options, the list of the template
19932 files, and exit.
19934 @item --version
19935 @itemx -V
19936 Print the version number of Autoconf and the configuration settings,
19937 and exit.
19939 @item --silent
19940 @itemx --quiet
19941 @itemx -q
19942 Do not print progress messages.
19944 @item --debug
19945 @itemx -d
19946 Don't remove the temporary files.
19948 @item --file=@var{file}[:@var{template}]
19949 Require that @var{file} be instantiated as if
19950 @samp{AC_CONFIG_FILES(@var{file}:@var{template})} was used.  Both
19951 @var{file} and @var{template} may be @samp{-} in which case the standard
19952 output and/or standard input, respectively, is used.  If a
19953 @var{template} file name is relative, it is first looked for in the build
19954 tree, and then in the source tree.  @xref{Configuration Actions}, for
19955 more details.
19957 This option and the following ones provide one way for separately
19958 distributed packages to share the values computed by @command{configure}.
19959 Doing so can be useful if some of the packages need a superset of the
19960 features that one of them, perhaps a common library, does.  These
19961 options allow a @file{config.status} file to create files other than the
19962 ones that its @file{configure.ac} specifies, so it can be used for a
19963 different package, or for extracting a subset of values.  For example,
19965 @example
19966 echo '@@CC@@' | ./config.status --file=-
19967 @end example
19969 @noindent
19970 provides the value of @code{@@CC@@} on standard output.
19972 @item --header=@var{file}[:@var{template}]
19973 Same as @option{--file} above, but with @samp{AC_CONFIG_HEADERS}.
19975 @item --recheck
19976 Ask @file{config.status} to update itself and exit (no instantiation).
19977 This option is useful if you change @command{configure}, so that the
19978 results of some tests might be different from the previous run.  The
19979 @option{--recheck} option reruns @command{configure} with the same arguments
19980 you used before, plus the @option{--no-create} option, which prevents
19981 @command{configure} from running @file{config.status} and creating
19982 @file{Makefile} and other files, and the @option{--no-recursion} option,
19983 which prevents @command{configure} from running other @command{configure}
19984 scripts in subdirectories.  (This is so other Make rules can
19985 run @file{config.status} when it changes; @pxref{Automatic Remaking},
19986 for an example).
19987 @end table
19989 @file{config.status} checks several optional environment variables that
19990 can alter its behavior:
19992 @anchor{CONFIG_SHELL}
19993 @defvar CONFIG_SHELL
19994 @evindex CONFIG_SHELL
19995 The shell with which to run @command{configure} for the @option{--recheck}
19996 option.  It must be Bourne-compatible.  The default is a shell that
19997 supports @code{LINENO} if available, and @file{/bin/sh} otherwise.
19998 Invoking @command{configure} by hand bypasses this setting, so you may
19999 need to use a command like @samp{CONFIG_SHELL=/bin/bash /bin/bash ./configure}
20000 to insure that the same shell is used everywhere.  The absolute name of the
20001 shell should be passed.
20002 @end defvar
20004 @defvar CONFIG_STATUS
20005 @evindex CONFIG_STATUS
20006 The file name to use for the shell script that records the
20007 configuration.  The default is @file{./config.status}.  This variable is
20008 useful when one package uses parts of another and the @command{configure}
20009 scripts shouldn't be merged because they are maintained separately.
20010 @end defvar
20012 You can use @file{./config.status} in your makefiles.  For example, in
20013 the dependencies given above (@pxref{Automatic Remaking}),
20014 @file{config.status} is run twice when @file{configure.ac} has changed.
20015 If that bothers you, you can make each run only regenerate the files for
20016 that rule:
20017 @example
20018 @group
20019 config.h: stamp-h
20020 stamp-h: config.h.in config.status
20021         ./config.status config.h
20022         echo > stamp-h
20024 Makefile: Makefile.in config.status
20025         ./config.status Makefile
20026 @end group
20027 @end example
20029 The calling convention of @file{config.status} has changed; see
20030 @ref{Obsolete config.status Use}, for details.
20033 @c =================================================== Obsolete Constructs
20035 @node Obsolete Constructs
20036 @chapter Obsolete Constructs
20037 @cindex Obsolete constructs
20039 Autoconf changes, and throughout the years some constructs have been
20040 obsoleted.  Most of the changes involve the macros, but in some cases
20041 the tools themselves, or even some concepts, are now considered
20042 obsolete.
20044 You may completely skip this chapter if you are new to Autoconf.  Its
20045 intention is mainly to help maintainers updating their packages by
20046 understanding how to move to more modern constructs.
20048 @menu
20049 * Obsolete config.status Use::  Obsolete convention for @command{config.status}
20050 * acconfig Header::             Additional entries in @file{config.h.in}
20051 * autoupdate Invocation::       Automatic update of @file{configure.ac}
20052 * Obsolete Macros::             Backward compatibility macros
20053 * Autoconf 1::                  Tips for upgrading your files
20054 * Autoconf 2.13::               Some fresher tips
20055 @end menu
20057 @node Obsolete config.status Use
20058 @section Obsolete @file{config.status} Invocation
20060 @file{config.status} now supports arguments to specify the files to
20061 instantiate; see @ref{config.status Invocation}, for more details.
20062 Before, environment variables had to be used.
20064 @defvar CONFIG_COMMANDS
20065 @evindex CONFIG_COMMANDS
20066 The tags of the commands to execute.  The default is the arguments given
20067 to @code{AC_OUTPUT} and @code{AC_CONFIG_COMMANDS} in
20068 @file{configure.ac}.
20069 @end defvar
20071 @defvar CONFIG_FILES
20072 @evindex CONFIG_FILES
20073 The files in which to perform @samp{@@@var{variable}@@} substitutions.
20074 The default is the arguments given to @code{AC_OUTPUT} and
20075 @code{AC_CONFIG_FILES} in @file{configure.ac}.
20076 @end defvar
20078 @defvar CONFIG_HEADERS
20079 @evindex CONFIG_HEADERS
20080 The files in which to substitute C @code{#define} statements.  The
20081 default is the arguments given to @code{AC_CONFIG_HEADERS}; if that
20082 macro was not called, @file{config.status} ignores this variable.
20083 @end defvar
20085 @defvar CONFIG_LINKS
20086 @evindex CONFIG_LINKS
20087 The symbolic links to establish.  The default is the arguments given to
20088 @code{AC_CONFIG_LINKS}; if that macro was not called,
20089 @file{config.status} ignores this variable.
20090 @end defvar
20092 In @ref{config.status Invocation}, using this old interface, the example
20093 would be:
20095 @example
20096 @group
20097 config.h: stamp-h
20098 stamp-h: config.h.in config.status
20099         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_FILES= \
20100           CONFIG_HEADERS=config.h ./config.status
20101         echo > stamp-h
20103 Makefile: Makefile.in config.status
20104         CONFIG_COMMANDS= CONFIG_LINKS= CONFIG_HEADERS= \
20105           CONFIG_FILES=Makefile ./config.status
20106 @end group
20107 @end example
20109 @noindent
20110 (If @file{configure.ac} does not call @code{AC_CONFIG_HEADERS}, there is
20111 no need to set @code{CONFIG_HEADERS} in the @command{make} rules.  Equally
20112 for @code{CONFIG_COMMANDS}, etc.)
20115 @node acconfig Header
20116 @section @file{acconfig.h}
20118 @cindex @file{acconfig.h}
20119 @cindex @file{config.h.top}
20120 @cindex @file{config.h.bot}
20122 In order to produce @file{config.h.in}, @command{autoheader} needs to
20123 build or to find templates for each symbol.  Modern releases of Autoconf
20124 use @code{AH_VERBATIM} and @code{AH_TEMPLATE} (@pxref{Autoheader
20125 Macros}), but in older releases a file, @file{acconfig.h}, contained the
20126 list of needed templates.  @command{autoheader} copied comments and
20127 @code{#define} and @code{#undef} statements from @file{acconfig.h} in
20128 the current directory, if present.  This file used to be mandatory if
20129 you @code{AC_DEFINE} any additional symbols.
20131 Modern releases of Autoconf also provide @code{AH_TOP} and
20132 @code{AH_BOTTOM} if you need to prepend/append some information to
20133 @file{config.h.in}.  Ancient versions of Autoconf had a similar feature:
20134 if @file{./acconfig.h} contains the string @samp{@@TOP@@},
20135 @command{autoheader} copies the lines before the line containing
20136 @samp{@@TOP@@} into the top of the file that it generates.  Similarly,
20137 if @file{./acconfig.h} contains the string @samp{@@BOTTOM@@},
20138 @command{autoheader} copies the lines after that line to the end of the
20139 file it generates.  Either or both of those strings may be omitted.  An
20140 even older alternate way to produce the same effect in ancient versions
20141 of Autoconf is to create the files @file{@var{file}.top} (typically
20142 @file{config.h.top}) and/or @file{@var{file}.bot} in the current
20143 directory.  If they exist, @command{autoheader} copies them to the
20144 beginning and end, respectively, of its output.
20146 In former versions of Autoconf, the files used in preparing a software
20147 package for distribution were:
20148 @example
20149 @group
20150 configure.ac --.   .------> autoconf* -----> configure
20151                +---+
20152 [aclocal.m4] --+   `---.
20153 [acsite.m4] ---'       |
20154                        +--> [autoheader*] -> [config.h.in]
20155 [acconfig.h] ----.     |
20156                  +-----'
20157 [config.h.top] --+
20158 [config.h.bot] --'
20159 @end group
20160 @end example
20162 Using only the @code{AH_} macros, @file{configure.ac} should be
20163 self-contained, and should not depend upon @file{acconfig.h} etc.
20166 @node autoupdate Invocation
20167 @section Using @command{autoupdate} to Modernize @file{configure.ac}
20168 @cindex @command{autoupdate}
20170 The @command{autoupdate} program updates a @file{configure.ac} file that
20171 calls Autoconf macros by their old names to use the current macro names.
20172 In version 2 of Autoconf, most of the macros were renamed to use a more
20173 uniform and descriptive naming scheme.  @xref{Macro Names}, for a
20174 description of the new scheme.  Although the old names still work
20175 (@pxref{Obsolete Macros}, for a list of the old macros and the corresponding
20176 new names), you can make your @file{configure.ac} files more readable
20177 and make it easier to use the current Autoconf documentation if you
20178 update them to use the new macro names.
20180 @evindex SIMPLE_BACKUP_SUFFIX
20181 If given no arguments, @command{autoupdate} updates @file{configure.ac},
20182 backing up the original version with the suffix @file{~} (or the value
20183 of the environment variable @code{SIMPLE_BACKUP_SUFFIX}, if that is
20184 set).  If you give @command{autoupdate} an argument, it reads that file
20185 instead of @file{configure.ac} and writes the updated file to the
20186 standard output.
20188 @noindent
20189 @command{autoupdate} accepts the following options:
20191 @table @option
20192 @item --help
20193 @itemx -h
20194 Print a summary of the command line options and exit.
20196 @item --version
20197 @itemx -V
20198 Print the version number of Autoconf and exit.
20200 @item --verbose
20201 @itemx -v
20202 Report processing steps.
20204 @item --debug
20205 @itemx -d
20206 Don't remove the temporary files.
20208 @item --force
20209 @itemx -f
20210 Force the update even if the file has not changed.  Disregard the cache.
20212 @item --include=@var{dir}
20213 @itemx -I @var{dir}
20214 Also look for input files in @var{dir}.  Multiple invocations accumulate.
20215 Directories are browsed from last to first.
20217 @item --prepend-include=@var{dir}
20218 @itemx -B @var{dir}
20219 Prepend directory @var{dir} to the search path.  This is used to include
20220 the language-specific files before any third-party macros.
20221 @end table
20223 @node Obsolete Macros
20224 @section Obsolete Macros
20226 Several macros are obsoleted in Autoconf, for various reasons (typically
20227 they failed to quote properly, couldn't be extended for more recent
20228 issues, etc.).  They are still supported, but deprecated: their use
20229 should be avoided.
20231 During the jump from Autoconf version 1 to version 2, most of the
20232 macros were renamed to use a more uniform and descriptive naming scheme,
20233 but their signature did not change.  @xref{Macro Names}, for a
20234 description of the new naming scheme.  Below, if there is just the mapping
20235 from old names to new names for these macros, the reader is invited to
20236 refer to the definition of the new macro for the signature and the
20237 description.
20239 @defmac AC_AIX
20240 @acindex{AIX}
20241 @cvindex _ALL_SOURCE
20242 This macro is a platform-specific subset of
20243 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
20244 @end defmac
20246 @defmac AC_ALLOCA
20247 @acindex{ALLOCA}
20248 Replaced by @code{AC_FUNC_ALLOCA} (@pxref{AC_FUNC_ALLOCA}).
20249 @end defmac
20251 @defmac AC_ARG_ARRAY
20252 @acindex{ARG_ARRAY}
20253 Removed because of limited usefulness.
20254 @end defmac
20256 @defmac AC_C_CROSS
20257 @acindex{C_CROSS}
20258 This macro is obsolete; it does nothing.
20259 @end defmac
20261 @defmac AC_C_LONG_DOUBLE
20262 @acindex{C_LONG_DOUBLE}
20263 @cvindex HAVE_LONG_DOUBLE
20264 If the C compiler supports a working @code{long double} type with more
20265 range or precision than the @code{double} type, define
20266 @code{HAVE_LONG_DOUBLE}.
20268 You should use @code{AC_TYPE_LONG_DOUBLE} or
20269 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
20270 @end defmac
20272 @defmac AC_CANONICAL_SYSTEM
20273 @acindex{CANONICAL_SYSTEM}
20274 Determine the system type and set output variables to the names of the
20275 canonical system types.  @xref{Canonicalizing}, for details about the
20276 variables this macro sets.
20278 The user is encouraged to use either @code{AC_CANONICAL_BUILD}, or
20279 @code{AC_CANONICAL_HOST}, or @code{AC_CANONICAL_TARGET}, depending on
20280 the needs.  Using @code{AC_CANONICAL_TARGET} is enough to run the two
20281 other macros (@pxref{Canonicalizing}).
20282 @end defmac
20284 @defmac AC_CHAR_UNSIGNED
20285 @acindex{CHAR_UNSIGNED}
20286 Replaced by @code{AC_C_CHAR_UNSIGNED} (@pxref{AC_C_CHAR_UNSIGNED}).
20287 @end defmac
20289 @defmac AC_CHECK_TYPE (@var{type}, @var{default})
20290 @acindex{CHECK_TYPE}
20291 Autoconf, up to 2.13, used to provide this version of
20292 @code{AC_CHECK_TYPE}, deprecated because of its flaws.  First, although
20293 it is a member of the @code{CHECK} clan, it does
20294 more than just checking.  Secondly, missing types are defined
20295 using @code{#define}, not @code{typedef}, and this can lead to
20296 problems in the case of pointer types.
20298 This use of @code{AC_CHECK_TYPE} is obsolete and discouraged; see
20299 @ref{Generic Types}, for the description of the current macro.
20301 If the type @var{type} is not defined, define it to be the C (or C++)
20302 builtin type @var{default}, e.g., @samp{short int} or @samp{unsigned int}.
20304 This macro is equivalent to:
20306 @example
20307 AC_CHECK_TYPE([@var{type}], [],
20308   [AC_DEFINE_UNQUOTED([@var{type}], [@var{default}],
20309      [Define to `@var{default}'
20310       if <sys/types.h> does not define.])])
20311 @end example
20313 In order to keep backward compatibility, the two versions of
20314 @code{AC_CHECK_TYPE} are implemented, selected using these heuristics:
20316 @enumerate
20317 @item
20318 If there are three or four arguments, the modern version is used.
20320 @item
20321 If the second argument appears to be a C or C++ type, then the
20322 obsolete version is used.  This happens if the argument is a C or C++
20323 @emph{builtin} type or a C identifier ending in @samp{_t}, optionally
20324 followed by one of @samp{[(* } and then by a string of zero or more
20325 characters taken from the set @samp{[]()* _a-zA-Z0-9}.
20327 @item
20328 If the second argument is spelled with the alphabet of valid C and C++
20329 types, the user is warned and the modern version is used.
20331 @item
20332 Otherwise, the modern version is used.
20333 @end enumerate
20335 @noindent
20336 You are encouraged either to use a valid builtin type, or to use the
20337 equivalent modern code (see above), or better yet, to use
20338 @code{AC_CHECK_TYPES} together with
20340 @example
20341 #ifndef HAVE_LOFF_T
20342 typedef loff_t off_t;
20343 #endif
20344 @end example
20345 @end defmac
20346 @c end of AC_CHECK_TYPE
20348 @defmac AC_CHECKING (@var{feature-description})
20349 @acindex{CHECKING}
20350 Same as
20352 @example
20353 AC_MSG_NOTICE([checking @var{feature-description}@dots{}]
20354 @end example
20356 @noindent
20357 @xref{AC_MSG_NOTICE}.
20358 @end defmac
20360 @defmac AC_COMPILE_CHECK (@var{echo-text}, @var{includes}, @
20361   @var{function-body}, @var{action-if-true}, @ovar{action-if-false})
20362 @acindex{COMPILE_CHECK}
20363 This is an obsolete version of @code{AC_TRY_COMPILE} itself replaced by
20364 @code{AC_COMPILE_IFELSE} (@pxref{Running the Compiler}), with the
20365 addition that it prints @samp{checking for @var{echo-text}} to the
20366 standard output first, if @var{echo-text} is non-empty.  Use
20367 @code{AC_MSG_CHECKING} and @code{AC_MSG_RESULT} instead to print
20368 messages (@pxref{Printing Messages}).
20369 @end defmac
20371 @defmac AC_CONST
20372 @acindex{CONST}
20373 Replaced by @code{AC_C_CONST} (@pxref{AC_C_CONST}).
20374 @end defmac
20376 @defmac AC_CROSS_CHECK
20377 @acindex{CROSS_CHECK}
20378 Same as @code{AC_C_CROSS}, which is obsolete too, and does nothing
20379 @code{:-)}.
20380 @end defmac
20382 @defmac AC_CYGWIN
20383 @acindex{CYGWIN}
20384 @evindex CYGWIN
20385 Check for the Cygwin environment in which case the shell variable
20386 @code{CYGWIN} is set to @samp{yes}.  Don't use this macro, the dignified
20387 means to check the nature of the host is using @code{AC_CANONICAL_HOST}
20388 (@pxref{Canonicalizing}).  As a matter of fact this macro is defined as:
20390 @example
20391 AC_REQUIRE([AC_CANONICAL_HOST])[]dnl
20392 case $host_os in
20393   *cygwin* ) CYGWIN=yes;;
20394          * ) CYGWIN=no;;
20395 esac
20396 @end example
20398 Beware that the variable @env{CYGWIN} has a special meaning when
20399 running Cygwin, and should not be changed.  That's yet another reason
20400 not to use this macro.
20401 @end defmac
20403 @defmac AC_DECL_SYS_SIGLIST
20404 @acindex{DECL_SYS_SIGLIST}
20405 @cvindex SYS_SIGLIST_DECLARED
20406 Same as:
20408 @example
20409 AC_CHECK_DECLS([sys_siglist], [], [],
20410 [#include <signal.h>
20411 /* NetBSD declares sys_siglist in unistd.h.  */
20412 #ifdef HAVE_UNISTD_H
20413 # include <unistd.h>
20414 #endif
20416 @end example
20418 @noindent
20419 @xref{AC_CHECK_DECLS}.
20420 @end defmac
20422 @defmac AC_DECL_YYTEXT
20423 @acindex{DECL_YYTEXT}
20424 Does nothing, now integrated in @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
20425 @end defmac
20427 @defmac AC_DIR_HEADER
20428 @acindex{DIR_HEADER}
20429 @cvindex DIRENT
20430 @cvindex SYSNDIR
20431 @cvindex SYSDIR
20432 @cvindex NDIR
20433 Like calling @code{AC_FUNC_CLOSEDIR_VOID}
20434 (@pxref{AC_FUNC_CLOSEDIR_VOID}) and @code{AC_HEADER_DIRENT}
20435 (@pxref{AC_HEADER_DIRENT}),
20436 but defines a different set of C preprocessor macros to indicate which
20437 header file is found:
20439 @multitable {@file{sys/ndir.h}} {Old Symbol} {@code{HAVE_SYS_NDIR_H}}
20440 @item Header            @tab Old Symbol     @tab New Symbol
20441 @item @file{dirent.h}   @tab @code{DIRENT}  @tab @code{HAVE_DIRENT_H}
20442 @item @file{sys/ndir.h} @tab @code{SYSNDIR} @tab @code{HAVE_SYS_NDIR_H}
20443 @item @file{sys/dir.h}  @tab @code{SYSDIR}  @tab @code{HAVE_SYS_DIR_H}
20444 @item @file{ndir.h}     @tab @code{NDIR}    @tab @code{HAVE_NDIR_H}
20445 @end multitable
20446 @end defmac
20448 @defmac AC_DYNIX_SEQ
20449 @acindex{DYNIX_SEQ}
20450 If on DYNIX/ptx, add @option{-lseq} to output variable
20451 @code{LIBS}.  This macro used to be defined as
20453 @example
20454 AC_CHECK_LIB([seq], [getmntent], [LIBS="-lseq $LIBS"])
20455 @end example
20457 @noindent
20458 now it is just @code{AC_FUNC_GETMNTENT} (@pxref{AC_FUNC_GETMNTENT}).
20459 @end defmac
20461 @defmac AC_EXEEXT
20462 @acindex{EXEEXT}
20463 @ovindex EXEEXT
20464 Defined the output variable @code{EXEEXT} based on the output of the
20465 compiler, which is now done automatically.  Typically set to empty
20466 string if Posix and @samp{.exe} if a @acronym{DOS} variant.
20467 @end defmac
20469 @defmac AC_EMXOS2
20470 @acindex{EMXOS2}
20471 Similar to @code{AC_CYGWIN} but checks for the EMX environment on OS/2
20472 and sets @code{EMXOS2}.  Don't use this macro, the dignified means to
20473 check the nature of the host is using @code{AC_CANONICAL_HOST}
20474 (@pxref{Canonicalizing}).
20475 @end defmac
20477 @defmac AC_ENABLE (@var{feature}, @var{action-if-given}, @
20478   @ovar{action-if-not-given})
20479 @acindex{ENABLE}
20480 This is an obsolete version of @code{AC_ARG_ENABLE} that does not
20481 support providing a help string (@pxref{AC_ARG_ENABLE}).
20482 @end defmac
20484 @defmac AC_ERROR
20485 @acindex{ERROR}
20486 Replaced by @code{AC_MSG_ERROR} (@pxref{AC_MSG_ERROR}).
20487 @end defmac
20489 @defmac AC_FIND_X
20490 @acindex{FIND_X}
20491 Replaced by @code{AC_PATH_X} (@pxref{AC_PATH_X}).
20492 @end defmac
20494 @defmac AC_FIND_XTRA
20495 @acindex{FIND_XTRA}
20496 Replaced by @code{AC_PATH_XTRA} (@pxref{AC_PATH_XTRA}).
20497 @end defmac
20499 @defmac AC_FOREACH
20500 @acindex{FOREACH}
20501 Replaced by @code{m4_foreach_w} (@pxref{m4_foreach_w}).
20502 @end defmac
20504 @defmac AC_FUNC_CHECK
20505 @acindex{FUNC_CHECK}
20506 Replaced by @code{AC_CHECK_FUNC} (@pxref{AC_CHECK_FUNC}).
20507 @end defmac
20509 @anchor{AC_FUNC_SETVBUF_REVERSED}
20510 @defmac AC_FUNC_SETVBUF_REVERSED
20511 @acindex{FUNC_SETVBUF_REVERSED}
20512 @cvindex SETVBUF_REVERSED
20513 @c @fuindex setvbuf
20514 @prindex @code{setvbuf}
20515 Do nothing.  Formerly, this macro checked whether @code{setvbuf} takes
20516 the buffering type as its second argument and the buffer pointer as the
20517 third, instead of the other way around, and defined
20518 @code{SETVBUF_REVERSED}.  However, the last systems to have the problem
20519 were those based on SVR2, which became obsolete in 1987, and the macro
20520 is no longer needed.
20521 @end defmac
20523 @defmac AC_FUNC_WAIT3
20524 @acindex{FUNC_WAIT3}
20525 @cvindex HAVE_WAIT3
20526 @c @fuindex wait3
20527 @prindex @code{wait3}
20528 If @code{wait3} is found and fills in the contents of its third argument
20529 (a @samp{struct rusage *}), which @acronym{HP-UX} does not do, define
20530 @code{HAVE_WAIT3}.
20532 These days portable programs should use @code{waitpid}, not
20533 @code{wait3}, as @code{wait3} has been removed from Posix.
20534 @end defmac
20536 @defmac AC_GCC_TRADITIONAL
20537 @acindex{GCC_TRADITIONAL}
20538 Replaced by @code{AC_PROG_GCC_TRADITIONAL} (@pxref{AC_PROG_GCC_TRADITIONAL}).
20539 @end defmac
20541 @defmac AC_GETGROUPS_T
20542 @acindex{GETGROUPS_T}
20543 Replaced by @code{AC_TYPE_GETGROUPS} (@pxref{AC_TYPE_GETGROUPS}).
20544 @end defmac
20546 @defmac AC_GETLOADAVG
20547 @acindex{GETLOADAVG}
20548 Replaced by @code{AC_FUNC_GETLOADAVG} (@pxref{AC_FUNC_GETLOADAVG}).
20549 @end defmac
20551 @defmac AC_GNU_SOURCE
20552 @acindex{GNU_SOURCE}
20553 @cvindex _GNU_SOURCE
20554 This macro is a platform-specific subset of
20555 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
20556 @end defmac
20558 @defmac AC_HAVE_FUNCS
20559 @acindex{HAVE_FUNCS}
20560 Replaced by @code{AC_CHECK_FUNCS} (@pxref{AC_CHECK_FUNCS}).
20561 @end defmac
20563 @defmac AC_HAVE_HEADERS
20564 @acindex{HAVE_HEADERS}
20565 Replaced by @code{AC_CHECK_HEADERS} (@pxref{AC_CHECK_HEADERS}).
20566 @end defmac
20568 @defmac AC_HAVE_LIBRARY (@var{library}, @ovar{action-if-found}, @
20569   @ovar{action-if-not-found}, @ovar{other-libraries})
20570 @acindex{HAVE_LIBRARY}
20571 This macro is equivalent to calling @code{AC_CHECK_LIB} with a
20572 @var{function} argument of @code{main}.  In addition, @var{library} can
20573 be written as any of @samp{foo}, @option{-lfoo}, or @samp{libfoo.a}.  In
20574 all of those cases, the compiler is passed @option{-lfoo}.  However,
20575 @var{library} cannot be a shell variable; it must be a literal name.
20576 @xref{AC_CHECK_LIB}.
20577 @end defmac
20579 @defmac AC_HAVE_POUNDBANG
20580 @acindex{HAVE_POUNDBANG}
20581 Replaced by @code{AC_SYS_INTERPRETER} (@pxref{AC_SYS_INTERPRETER}).
20582 @end defmac
20584 @defmac AC_HEADER_CHECK
20585 @acindex{HEADER_CHECK}
20586 Replaced by @code{AC_CHECK_HEADER} (@pxref{AC_CHECK_HEADER}).
20587 @end defmac
20589 @defmac AC_HEADER_EGREP
20590 @acindex{HEADER_EGREP}
20591 Replaced by @code{AC_EGREP_HEADER} (@pxref{AC_EGREP_HEADER}).
20592 @end defmac
20594 @defmac AC_HELP_STRING
20595 @acindex{HELP_STRING}
20596 Replaced by @code{AS_HELP_STRING} (@pxref{AS_HELP_STRING}).
20597 @end defmac
20599 @defmac AC_INIT (@var{unique-file-in-source-dir})
20600 @acindex{INIT}
20601 Formerly @code{AC_INIT} used to have a single argument, and was
20602 equivalent to:
20604 @example
20605 AC_INIT
20606 AC_CONFIG_SRCDIR(@var{unique-file-in-source-dir})
20607 @end example
20608 See @ref{AC_INIT} and @ref{AC_CONFIG_SRCDIR}.
20609 @end defmac
20611 @defmac AC_INLINE
20612 @acindex{INLINE}
20613 Replaced by @code{AC_C_INLINE} (@pxref{AC_C_INLINE}).
20614 @end defmac
20616 @defmac AC_INT_16_BITS
20617 @acindex{INT_16_BITS}
20618 @cvindex INT_16_BITS
20619 If the C type @code{int} is 16 bits wide, define @code{INT_16_BITS}.
20620 Use @samp{AC_CHECK_SIZEOF(int)} instead (@pxref{AC_CHECK_SIZEOF}).
20621 @end defmac
20623 @defmac AC_IRIX_SUN
20624 @acindex{IRIX_SUN}
20625 If on @sc{irix} (Silicon Graphics Unix), add @option{-lsun} to output
20626 @code{LIBS}.  If you were using it to get @code{getmntent}, use
20627 @code{AC_FUNC_GETMNTENT} instead.  If you used it for the NIS versions
20628 of the password and group functions, use @samp{AC_CHECK_LIB(sun,
20629 getpwnam)}.  Up to Autoconf 2.13, it used to be
20631 @example
20632 AC_CHECK_LIB([sun], [getmntent], [LIBS="-lsun $LIBS"])
20633 @end example
20635 @noindent
20636 now it is defined as
20638 @example
20639 AC_FUNC_GETMNTENT
20640 AC_CHECK_LIB([sun], [getpwnam])
20641 @end example
20643 @noindent
20644 See @ref{AC_FUNC_GETMNTENT} and @ref{AC_CHECK_LIB}.
20645 @end defmac
20647 @defmac AC_ISC_POSIX
20648 @acindex{ISC_POSIX}
20649 @ovindex LIBS
20650 This macro adds @option{-lcposix} to output variable @code{LIBS} if
20651 necessary for Posix facilities.  Sun dropped support for the obsolete
20652 @sc{interactive} Systems Corporation Unix on 2006-07-23.  New programs
20653 need not use this macro.  It is implemented as
20654 @code{AC_SEARCH_LIBS([strerror], [cposix])} (@pxref{AC_SEARCH_LIBS}).
20655 @end defmac
20657 @defmac AC_LANG_C
20658 @acindex{LANG_C}
20659 Same as @samp{AC_LANG([C])} (@pxref{AC_LANG}).
20660 @end defmac
20662 @defmac AC_LANG_CPLUSPLUS
20663 @acindex{LANG_CPLUSPLUS}
20664 Same as @samp{AC_LANG([C++])} (@pxref{AC_LANG}).
20665 @end defmac
20667 @defmac AC_LANG_FORTRAN77
20668 @acindex{LANG_FORTRAN77}
20669 Same as @samp{AC_LANG([Fortran 77])} (@pxref{AC_LANG}).
20670 @end defmac
20672 @defmac AC_LANG_RESTORE
20673 @acindex{LANG_RESTORE}
20674 Select the @var{language} that is saved on the top of the stack, as set
20675 by @code{AC_LANG_SAVE}, remove it from the stack, and call
20676 @code{AC_LANG(@var{language})}.  @xref{Language Choice}, for the
20677 preferred way to change languages.
20678 @end defmac
20680 @defmac AC_LANG_SAVE
20681 @acindex{LANG_SAVE}
20682 Remember the current language (as set by @code{AC_LANG}) on a stack.
20683 The current language does not change.  @code{AC_LANG_PUSH} is preferred
20684 (@pxref{AC_LANG_PUSH}).
20685 @end defmac
20687 @defmac AC_LINK_FILES (@var{source}@dots{}, @var{dest}@dots{})
20688 @acindex{LINK_FILES}
20689 This is an obsolete version of @code{AC_CONFIG_LINKS}
20690 (@pxref{AC_CONFIG_LINKS}.  An updated version of:
20692 @example
20693 AC_LINK_FILES(config/$machine.h config/$obj_format.h,
20694               host.h            object.h)
20695 @end example
20697 @noindent
20700 @example
20701 AC_CONFIG_LINKS([host.h:config/$machine.h
20702                 object.h:config/$obj_format.h])
20703 @end example
20704 @end defmac
20706 @defmac AC_LN_S
20707 @acindex{LN_S}
20708 Replaced by @code{AC_PROG_LN_S} (@pxref{AC_PROG_LN_S}).
20709 @end defmac
20711 @defmac AC_LONG_64_BITS
20712 @acindex{LONG_64_BITS}
20713 @cvindex LONG_64_BITS
20714 Define @code{LONG_64_BITS} if the C type @code{long int} is 64 bits wide.
20715 Use the generic macro @samp{AC_CHECK_SIZEOF([long int])} instead
20716 (@pxref{AC_CHECK_SIZEOF}).
20717 @end defmac
20719 @defmac AC_LONG_DOUBLE
20720 @acindex{LONG_DOUBLE}
20721 If the C compiler supports a working @code{long double} type with more
20722 range or precision than the @code{double} type, define
20723 @code{HAVE_LONG_DOUBLE}.
20725 You should use @code{AC_TYPE_LONG_DOUBLE} or
20726 @code{AC_TYPE_LONG_DOUBLE_WIDER} instead.  @xref{Particular Types}.
20727 @end defmac
20729 @defmac AC_LONG_FILE_NAMES
20730 @acindex{LONG_FILE_NAMES}
20731 Replaced by
20732 @example
20733 AC_SYS_LONG_FILE_NAMES
20734 @end example
20735 @noindent
20736 @xref{AC_SYS_LONG_FILE_NAMES}.
20737 @end defmac
20739 @defmac AC_MAJOR_HEADER
20740 @acindex{MAJOR_HEADER}
20741 Replaced by @code{AC_HEADER_MAJOR} (@pxref{AC_HEADER_MAJOR}).
20742 @end defmac
20744 @defmac AC_MEMORY_H
20745 @acindex{MEMORY_H}
20746 @cvindex NEED_MEMORY_H
20747 Used to define @code{NEED_MEMORY_H} if the @code{mem} functions were
20748 defined in @file{memory.h}.  Today it is equivalent to
20749 @samp{AC_CHECK_HEADERS([memory.h])} (@pxref{AC_CHECK_HEADERS}).  Adjust
20750 your code to depend upon
20751 @code{HAVE_MEMORY_H}, not @code{NEED_MEMORY_H}; see @ref{Standard
20752 Symbols}.
20753 @end defmac
20755 @defmac AC_MINGW32
20756 @acindex{MINGW32}
20757 Similar to @code{AC_CYGWIN} but checks for the MinGW compiler
20758 environment and sets @code{MINGW32}.  Don't use this macro, the
20759 dignified means to check the nature of the host is using
20760 @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
20761 @end defmac
20763 @defmac AC_MINIX
20764 @acindex{MINIX}
20765 @cvindex _MINIX
20766 @cvindex _POSIX_SOURCE
20767 @cvindex _POSIX_1_SOURCE
20768 This macro is a platform-specific subset of
20769 @code{AC_USE_SYSTEM_EXTENSIONS} (@pxref{AC_USE_SYSTEM_EXTENSIONS}).
20770 @end defmac
20772 @defmac AC_MINUS_C_MINUS_O
20773 @acindex{MINUS_C_MINUS_O}
20774 Replaced by @code{AC_PROG_CC_C_O} (@pxref{AC_PROG_CC_C_O}).
20775 @end defmac
20777 @defmac AC_MMAP
20778 @acindex{MMAP}
20779 Replaced by @code{AC_FUNC_MMAP} (@pxref{AC_FUNC_MMAP}).
20780 @end defmac
20782 @defmac AC_MODE_T
20783 @acindex{MODE_T}
20784 Replaced by @code{AC_TYPE_MODE_T} (@pxref{AC_TYPE_MODE_T}).
20785 @end defmac
20787 @defmac AC_OBJEXT
20788 @acindex{OBJEXT}
20789 @ovindex OBJEXT
20790 Defined the output variable @code{OBJEXT} based on the output of the
20791 compiler, after .c files have been excluded.  Typically set to @samp{o}
20792 if Posix, @samp{obj} if a @acronym{DOS} variant.
20793 Now the compiler checking macros handle
20794 this automatically.
20795 @end defmac
20797 @defmac AC_OBSOLETE (@var{this-macro-name}, @ovar{suggestion})
20798 @acindex{OBSOLETE}
20799 Make M4 print a message to the standard error output warning that
20800 @var{this-macro-name} is obsolete, and giving the file and line number
20801 where it was called.  @var{this-macro-name} should be the name of the
20802 macro that is calling @code{AC_OBSOLETE}.  If @var{suggestion} is given,
20803 it is printed at the end of the warning message; for example, it can be
20804 a suggestion for what to use instead of @var{this-macro-name}.
20806 For instance
20808 @example
20809 AC_OBSOLETE([$0], [; use AC_CHECK_HEADERS(unistd.h) instead])dnl
20810 @end example
20812 @noindent
20813 You are encouraged to use @code{AU_DEFUN} instead, since it gives better
20814 services to the user (@pxref{AU_DEFUN}).
20815 @end defmac
20817 @defmac AC_OFF_T
20818 @acindex{OFF_T}
20819 Replaced by @code{AC_TYPE_OFF_T} (@pxref{AC_TYPE_OFF_T}).
20820 @end defmac
20822 @defmac AC_OUTPUT (@ovar{file}@dots{}, @ovar{extra-cmds}, @ovar{init-cmds})
20823 @acindex{OUTPUT}
20824 The use of @code{AC_OUTPUT} with arguments is deprecated.  This obsoleted
20825 interface is equivalent to:
20827 @example
20828 @group
20829 AC_CONFIG_FILES(@var{file}@dots{})
20830 AC_CONFIG_COMMANDS([default],
20831                    @var{extra-cmds}, @var{init-cmds})
20832 AC_OUTPUT
20833 @end group
20834 @end example
20836 @noindent
20837 See @ref{AC_CONFIG_FILES}, @ref{AC_CONFIG_COMMANDS}, and @ref{AC_OUTPUT}.
20838 @end defmac
20840 @defmac AC_OUTPUT_COMMANDS (@var{extra-cmds}, @ovar{init-cmds})
20841 @acindex{OUTPUT_COMMANDS}
20842 Specify additional shell commands to run at the end of
20843 @file{config.status}, and shell commands to initialize any variables
20844 from @command{configure}.  This macro may be called multiple times.  It is
20845 obsolete, replaced by @code{AC_CONFIG_COMMANDS} (@pxref{AC_CONFIG_COMMANDS}).
20847 Here is an unrealistic example:
20849 @example
20850 fubar=27
20851 AC_OUTPUT_COMMANDS([echo this is extra $fubar, and so on.],
20852                    [fubar=$fubar])
20853 AC_OUTPUT_COMMANDS([echo this is another, extra, bit],
20854                    [echo init bit])
20855 @end example
20857 Aside from the fact that @code{AC_CONFIG_COMMANDS} requires an
20858 additional key, an important difference is that
20859 @code{AC_OUTPUT_COMMANDS} is quoting its arguments twice, unlike
20860 @code{AC_CONFIG_COMMANDS}.  This means that @code{AC_CONFIG_COMMANDS}
20861 can safely be given macro calls as arguments:
20863 @example
20864 AC_CONFIG_COMMANDS(foo, [my_FOO()])
20865 @end example
20867 @noindent
20868 Conversely, where one level of quoting was enough for literal strings
20869 with @code{AC_OUTPUT_COMMANDS}, you need two with
20870 @code{AC_CONFIG_COMMANDS}.  The following lines are equivalent:
20872 @example
20873 @group
20874 AC_OUTPUT_COMMANDS([echo "Square brackets: []"])
20875 AC_CONFIG_COMMANDS([default], [[echo "Square brackets: []"]])
20876 @end group
20877 @end example
20878 @end defmac
20880 @defmac AC_PID_T
20881 @acindex{PID_T}
20882 Replaced by @code{AC_TYPE_PID_T} (@pxref{AC_TYPE_PID_T}).
20883 @end defmac
20885 @defmac AC_PREFIX
20886 @acindex{PREFIX}
20887 Replaced by @code{AC_PREFIX_PROGRAM} (@pxref{AC_PREFIX_PROGRAM}).
20888 @end defmac
20890 @defmac AC_PROGRAMS_CHECK
20891 @acindex{PROGRAMS_CHECK}
20892 Replaced by @code{AC_CHECK_PROGS} (@pxref{AC_CHECK_PROGS}).
20893 @end defmac
20895 @defmac AC_PROGRAMS_PATH
20896 @acindex{PROGRAMS_PATH}
20897 Replaced by @code{AC_PATH_PROGS} (@pxref{AC_PATH_PROGS}).
20898 @end defmac
20900 @defmac AC_PROGRAM_CHECK
20901 @acindex{PROGRAM_CHECK}
20902 Replaced by @code{AC_CHECK_PROG} (@pxref{AC_CHECK_PROG}).
20903 @end defmac
20905 @defmac AC_PROGRAM_EGREP
20906 @acindex{PROGRAM_EGREP}
20907 Replaced by @code{AC_EGREP_CPP} (@pxref{AC_EGREP_CPP}).
20908 @end defmac
20910 @defmac AC_PROGRAM_PATH
20911 @acindex{PROGRAM_PATH}
20912 Replaced by @code{AC_PATH_PROG} (@pxref{AC_PATH_PROG}).
20913 @end defmac
20915 @defmac AC_REMOTE_TAPE
20916 @acindex{REMOTE_TAPE}
20917 Removed because of limited usefulness.
20918 @end defmac
20920 @defmac AC_RESTARTABLE_SYSCALLS
20921 @acindex{RESTARTABLE_SYSCALLS}
20922 This macro was renamed @code{AC_SYS_RESTARTABLE_SYSCALLS}.  However,
20923 these days portable programs should use @code{sigaction} with
20924 @code{SA_RESTART} if they want restartable system calls.  They should
20925 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
20926 system call is restartable is a dynamic issue, not a configuration-time
20927 issue.
20928 @end defmac
20930 @defmac AC_RETSIGTYPE
20931 @acindex{RETSIGTYPE}
20932 Replaced by @code{AC_TYPE_SIGNAL} (@pxref{AC_TYPE_SIGNAL}), which itself
20933 is obsolete when assuming C89 or better.
20934 @end defmac
20936 @defmac AC_RSH
20937 @acindex{RSH}
20938 Removed because of limited usefulness.
20939 @end defmac
20941 @defmac AC_SCO_INTL
20942 @acindex{SCO_INTL}
20943 @ovindex LIBS
20944 If on SCO Unix, add @option{-lintl} to output variable @code{LIBS}.  This
20945 macro used to do this:
20947 @example
20948 AC_CHECK_LIB([intl], [strftime], [LIBS="-lintl $LIBS"])
20949 @end example
20951 @noindent
20952 Now it just calls @code{AC_FUNC_STRFTIME} instead (@pxref{AC_FUNC_STRFTIME}).
20953 @end defmac
20955 @defmac AC_SETVBUF_REVERSED
20956 @acindex{SETVBUF_REVERSED}
20957 Replaced by
20958 @example
20959 AC_FUNC_SETVBUF_REVERSED
20960 @end example
20961 @noindent
20962 @xref{AC_FUNC_SETVBUF_REVERSED}.
20963 @end defmac
20965 @defmac AC_SET_MAKE
20966 @acindex{SET_MAKE}
20967 Replaced by @code{AC_PROG_MAKE_SET} (@pxref{AC_PROG_MAKE_SET}).
20968 @end defmac
20970 @defmac AC_SIZEOF_TYPE
20971 @acindex{SIZEOF_TYPE}
20972 Replaced by @code{AC_CHECK_SIZEOF} (@pxref{AC_CHECK_SIZEOF}).
20973 @end defmac
20975 @defmac AC_SIZE_T
20976 @acindex{SIZE_T}
20977 Replaced by @code{AC_TYPE_SIZE_T} (@pxref{AC_TYPE_SIZE_T}).
20978 @end defmac
20980 @defmac AC_STAT_MACROS_BROKEN
20981 @acindex{STAT_MACROS_BROKEN}
20982 Replaced by @code{AC_HEADER_STAT} (@pxref{AC_HEADER_STAT}).
20983 @end defmac
20985 @defmac AC_STDC_HEADERS
20986 @acindex{STDC_HEADERS}
20987 Replaced by @code{AC_HEADER_STDC} (@pxref{AC_HEADER_STDC}).
20988 @end defmac
20990 @defmac AC_STRCOLL
20991 @acindex{STRCOLL}
20992 Replaced by @code{AC_FUNC_STRCOLL} (@pxref{AC_FUNC_STRCOLL}).
20993 @end defmac
20995 @defmac AC_STRUCT_ST_BLKSIZE
20996 @acindex{STRUCT_ST_BLKSIZE}
20997 @cvindex HAVE_STRUCT_STAT_ST_BLKSIZE
20998 @cvindex HAVE_ST_BLKSIZE
20999 If @code{struct stat} contains an @code{st_blksize} member, define
21000 @code{HAVE_STRUCT_STAT_ST_BLKSIZE}.  The former name,
21001 @code{HAVE_ST_BLKSIZE} is to be avoided, as its support will cease in
21002 the future.  This macro is obsoleted, and should be replaced by
21004 @example
21005 AC_CHECK_MEMBERS([struct stat.st_blksize])
21006 @end example
21007 @noindent
21008 @xref{AC_CHECK_MEMBERS}.
21009 @end defmac
21011 @defmac AC_STRUCT_ST_RDEV
21012 @acindex{STRUCT_ST_RDEV}
21013 @cvindex HAVE_ST_RDEV
21014 @cvindex HAVE_STRUCT_STAT_ST_RDEV
21015 If @code{struct stat} contains an @code{st_rdev} member, define
21016 @code{HAVE_STRUCT_STAT_ST_RDEV}.  The former name for this macro,
21017 @code{HAVE_ST_RDEV}, is to be avoided as it will cease to be supported
21018 in the future.  Actually, even the new macro is obsolete and should be
21019 replaced by:
21020 @example
21021 AC_CHECK_MEMBERS([struct stat.st_rdev])
21022 @end example
21023 @noindent
21024 @xref{AC_CHECK_MEMBERS}.
21025 @end defmac
21027 @defmac AC_ST_BLKSIZE
21028 @acindex{ST_BLKSIZE}
21029 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
21030 @end defmac
21032 @defmac AC_ST_BLOCKS
21033 @acindex{ST_BLOCKS}
21034 Replaced by @code{AC_STRUCT_ST_BLOCKS} (@pxref{AC_STRUCT_ST_BLOCKS}).
21035 @end defmac
21037 @defmac AC_ST_RDEV
21038 @acindex{ST_RDEV}
21039 Replaced by @code{AC_CHECK_MEMBERS} (@pxref{AC_CHECK_MEMBERS}).
21040 @end defmac
21042 @defmac AC_SYS_RESTARTABLE_SYSCALLS
21043 @acindex{SYS_RESTARTABLE_SYSCALLS}
21044 @cvindex HAVE_RESTARTABLE_SYSCALLS
21045 If the system automatically restarts a system call that is interrupted
21046 by a signal, define @code{HAVE_RESTARTABLE_SYSCALLS}.  This macro does
21047 not check whether system calls are restarted in general---it checks whether a
21048 signal handler installed with @code{signal} (but not @code{sigaction})
21049 causes system calls to be restarted.  It does not check whether system calls
21050 can be restarted when interrupted by signals that have no handler.
21052 These days portable programs should use @code{sigaction} with
21053 @code{SA_RESTART} if they want restartable system calls.  They should
21054 not rely on @code{HAVE_RESTARTABLE_SYSCALLS}, since nowadays whether a
21055 system call is restartable is a dynamic issue, not a configuration-time
21056 issue.
21057 @end defmac
21059 @defmac AC_SYS_SIGLIST_DECLARED
21060 @acindex{SYS_SIGLIST_DECLARED}
21061 This macro was renamed @code{AC_DECL_SYS_SIGLIST}.  However, even that
21062 name is obsolete, as the same functionality is now acheived via
21063 @code{AC_CHECK_DECLS} (@pxref{AC_CHECK_DECLS}).
21064 @end defmac
21066 @defmac AC_TEST_CPP
21067 @acindex{TEST_CPP}
21068 This macro was renamed @code{AC_TRY_CPP}, which in turn was replaced by
21069 @code{AC_PREPROC_IFELSE} (@pxref{AC_PREPROC_IFELSE}).
21070 @end defmac
21072 @defmac AC_TEST_PROGRAM
21073 @acindex{TEST_PROGRAM}
21074 This macro was renamed @code{AC_TRY_RUN}, which in turn was replaced by
21075 @code{AC_RUN_IFELSE} (@pxref{AC_RUN_IFELSE}).
21076 @end defmac
21078 @defmac AC_TIMEZONE
21079 @acindex{TIMEZONE}
21080 Replaced by @code{AC_STRUCT_TIMEZONE} (@pxref{AC_STRUCT_TIMEZONE}).
21081 @end defmac
21083 @defmac AC_TIME_WITH_SYS_TIME
21084 @acindex{TIME_WITH_SYS_TIME}
21085 Replaced by @code{AC_HEADER_TIME} (@pxref{AC_HEADER_TIME}).
21086 @end defmac
21088 @defmac AC_TRY_COMPILE (@var{includes}, @var{function-body}, @
21089   @ovar{action-if-true}, @ovar{action-if-false})
21090 @acindex{TRY_COMPILE}
21091 Same as:
21093 @example
21094 AC_COMPILE_IFELSE(
21095   [AC_LANG_PROGRAM([[@var{includes}]],
21096      [[@var{function-body}]])],
21097   [@var{action-if-true}],
21098   [@var{action-if-false}])
21099 @end example
21101 @noindent
21102 @xref{Running the Compiler}.
21104 This macro double quotes both @var{includes} and @var{function-body}.
21106 For C and C++, @var{includes} is any @code{#include} statements needed
21107 by the code in @var{function-body} (@var{includes} is ignored if
21108 the currently selected language is Fortran or Fortran 77).  The compiler
21109 and compilation flags are determined by the current language
21110 (@pxref{Language Choice}).
21111 @end defmac
21113 @defmac AC_TRY_CPP (@var{input}, @ovar{action-if-true}, @ovar{action-if-false})
21114 @acindex{TRY_CPP}
21115 Same as:
21117 @example
21118 AC_PREPROC_IFELSE(
21119   [AC_LANG_SOURCE([[@var{input}]])],
21120   [@var{action-if-true}],
21121   [@var{action-if-false}])
21122 @end example
21124 @noindent
21125 @xref{Running the Preprocessor}.
21127 This macro double quotes the @var{input}.
21128 @end defmac
21130 @defmac AC_TRY_LINK (@var{includes}, @var{function-body}, @
21131   @ovar{action-if-true}, @ovar{action-if-false})
21132 @acindex{TRY_LINK}
21133 Same as:
21135 @example
21136 AC_LINK_IFELSE(
21137   [AC_LANG_PROGRAM([[@var{includes}]],
21138      [[@var{function-body}]])],
21139   [@var{action-if-true}],
21140   [@var{action-if-false}])
21141 @end example
21143 @noindent
21144 @xref{Running the Compiler}.
21146 This macro double quotes both @var{includes} and @var{function-body}.
21148 Depending on the current language (@pxref{Language Choice}), create a
21149 test program to see whether a function whose body consists of
21150 @var{function-body} can be compiled and linked.  If the file compiles
21151 and links successfully, run shell commands @var{action-if-found},
21152 otherwise run @var{action-if-not-found}.
21154 This macro double quotes both @var{includes} and @var{function-body}.
21156 For C and C++, @var{includes} is any @code{#include} statements needed
21157 by the code in @var{function-body} (@var{includes} is ignored if
21158 the currently selected language is Fortran or Fortran 77).  The compiler
21159 and compilation flags are determined by the current language
21160 (@pxref{Language Choice}), and in addition @code{LDFLAGS} and
21161 @code{LIBS} are used for linking.
21162 @end defmac
21164 @defmac AC_TRY_LINK_FUNC (@var{function}, @ovar{action-if-found}, @
21165   @ovar{action-if-not-found})
21166 @acindex{TRY_LINK_FUNC}
21167 This macro is equivalent to
21168 @example
21169 AC_LINK_IFELSE([AC_LANG_CALL([], [@var{function}])],
21170   [@var{action-if-found}], [@var{action-if-not-found}])
21171 @end example
21172 @noindent
21173 @xref{AC_LINK_IFELSE}.
21174 @end defmac
21176 @defmac AC_TRY_RUN (@var{program}, @ovar{action-if-true}, @
21177   @ovar{action-if-false}, @ovar{action-if-cross-compiling})
21178 @acindex{TRY_RUN}
21179 Same as:
21181 @example
21182 AC_RUN_IFELSE(
21183   [AC_LANG_SOURCE([[@var{program}]])],
21184   [@var{action-if-true}],
21185   [@var{action-if-false}],
21186   [@var{action-if-cross-compiling}])
21187 @end example
21189 @noindent
21190 @xref{Runtime}.
21191 @end defmac
21193 @anchor{AC_TYPE_SIGNAL}
21194 @defmac AC_TYPE_SIGNAL
21195 @acindex{TYPE_SIGNAL}
21196 @cvindex RETSIGTYPE
21197 @hdrindex{signal.h}
21198 If @file{signal.h} declares @code{signal} as returning a pointer to a
21199 function returning @code{void}, define @code{RETSIGTYPE} to be
21200 @code{void}; otherwise, define it to be @code{int}.  These days, it is
21201 portable to assume C89, and that signal handlers return @code{void},
21202 without needing to use this macro or @code{RETSIGTYPE}.
21204 When targetting older K&R C, it is possible to define signal handlers as
21205 returning type @code{RETSIGTYPE}, and omit a return statement:
21207 @example
21208 @group
21209 RETSIGTYPE
21210 hup_handler ()
21212 @dots{}
21214 @end group
21215 @end example
21216 @end defmac
21218 @defmac AC_UID_T
21219 @acindex{UID_T}
21220 Replaced by @code{AC_TYPE_UID_T} (@pxref{AC_TYPE_UID_T}).
21221 @end defmac
21223 @defmac AC_UNISTD_H
21224 @acindex{UNISTD_H}
21225 Same as @samp{AC_CHECK_HEADERS([unistd.h])} (@pxref{AC_CHECK_HEADERS}).
21226 @end defmac
21228 @defmac AC_USG
21229 @acindex{USG}
21230 @cvindex USG
21231 Define @code{USG} if the @acronym{BSD} string functions are defined in
21232 @file{strings.h}.  You should no longer depend upon @code{USG}, but on
21233 @code{HAVE_STRING_H}; see @ref{Standard Symbols}.
21234 @end defmac
21236 @defmac AC_UTIME_NULL
21237 @acindex{UTIME_NULL}
21238 Replaced by @code{AC_FUNC_UTIME_NULL} (@pxref{AC_FUNC_UTIME_NULL}).
21239 @end defmac
21241 @defmac AC_VALIDATE_CACHED_SYSTEM_TUPLE (@ovar{cmd})
21242 @acindex{VALIDATE_CACHED_SYSTEM_TUPLE}
21243 If the cache file is inconsistent with the current host, target and
21244 build system types, it used to execute @var{cmd} or print a default
21245 error message.  This is now handled by default.
21246 @end defmac
21248 @defmac AC_VERBOSE (@var{result-description})
21249 @acindex{VERBOSE}
21250 Replaced by @code{AC_MSG_RESULT} (@pxref{AC_MSG_RESULT}).
21251 @end defmac
21253 @defmac AC_VFORK
21254 @acindex{VFORK}
21255 Replaced by @code{AC_FUNC_FORK} (@pxref{AC_FUNC_FORK}).
21256 @end defmac
21258 @defmac AC_VPRINTF
21259 @acindex{VPRINTF}
21260 Replaced by @code{AC_FUNC_VPRINTF} (@pxref{AC_FUNC_VPRINTF}).
21261 @end defmac
21263 @defmac AC_WAIT3
21264 @acindex{WAIT3}
21265 This macro was renamed @code{AC_FUNC_WAIT3}.  However, these days
21266 portable programs should use @code{waitpid}, not @code{wait3}, as
21267 @code{wait3} has been removed from Posix.
21268 @end defmac
21270 @defmac AC_WARN
21271 @acindex{WARN}
21272 Replaced by @code{AC_MSG_WARN} (@pxref{AC_MSG_WARN}).
21273 @end defmac
21275 @defmac AC_WITH (@var{package}, @var{action-if-given}, @
21276   @ovar{action-if-not-given})
21277 @acindex{WITH}
21278 This is an obsolete version of @code{AC_ARG_WITH} that does not
21279 support providing a help string (@pxref{AC_ARG_WITH}).
21280 @end defmac
21282 @defmac AC_WORDS_BIGENDIAN
21283 @acindex{WORDS_BIGENDIAN}
21284 Replaced by @code{AC_C_BIGENDIAN} (@pxref{AC_C_BIGENDIAN}).
21285 @end defmac
21287 @defmac AC_XENIX_DIR
21288 @acindex{XENIX_DIR}
21289 @ovindex LIBS
21290 This macro used to add @option{-lx} to output variable @code{LIBS} if on
21291 Xenix.  Also, if @file{dirent.h} is being checked for, added
21292 @option{-ldir} to @code{LIBS}.  Now it is merely an alias of
21293 @code{AC_HEADER_DIRENT} instead, plus some code to detect whether
21294 running @sc{xenix} on which you should not depend:
21296 @example
21297 AC_MSG_CHECKING([for Xenix])
21298 AC_EGREP_CPP([yes],
21299 [#if defined M_XENIX && !defined M_UNIX
21300   yes
21301 #endif],
21302              [AC_MSG_RESULT([yes]); XENIX=yes],
21303              [AC_MSG_RESULT([no]); XENIX=])
21304 @end example
21305 @noindent
21306 Don't use this macro, the dignified means to check the nature of the
21307 host is using @code{AC_CANONICAL_HOST} (@pxref{Canonicalizing}).
21308 @end defmac
21310 @defmac AC_YYTEXT_POINTER
21311 @acindex{YYTEXT_POINTER}
21312 This macro was renamed @code{AC_DECL_YYTEXT}, which in turn was
21313 integrated into @code{AC_PROG_LEX} (@pxref{AC_PROG_LEX}).
21314 @end defmac
21316 @node Autoconf 1
21317 @section Upgrading From Version 1
21318 @cindex Upgrading autoconf
21319 @cindex Autoconf upgrading
21321 Autoconf version 2 is mostly backward compatible with version 1.
21322 However, it introduces better ways to do some things, and doesn't
21323 support some of the ugly things in version 1.  So, depending on how
21324 sophisticated your @file{configure.ac} files are, you might have to do
21325 some manual work in order to upgrade to version 2.  This chapter points
21326 out some problems to watch for when upgrading.  Also, perhaps your
21327 @command{configure} scripts could benefit from some of the new features in
21328 version 2; the changes are summarized in the file @file{NEWS} in the
21329 Autoconf distribution.
21331 @menu
21332 * Changed File Names::          Files you might rename
21333 * Changed Makefiles::           New things to put in @file{Makefile.in}
21334 * Changed Macros::              Macro calls you might replace
21335 * Changed Results::             Changes in how to check test results
21336 * Changed Macro Writing::       Better ways to write your own macros
21337 @end menu
21339 @node Changed File Names
21340 @subsection Changed File Names
21342 If you have an @file{aclocal.m4} installed with Autoconf (as opposed to
21343 in a particular package's source directory), you must rename it to
21344 @file{acsite.m4}.  @xref{autoconf Invocation}.
21346 If you distribute @file{install.sh} with your package, rename it to
21347 @file{install-sh} so @command{make} builtin rules don't inadvertently
21348 create a file called @file{install} from it.  @code{AC_PROG_INSTALL}
21349 looks for the script under both names, but it is best to use the new name.
21351 If you were using @file{config.h.top}, @file{config.h.bot}, or
21352 @file{acconfig.h}, you still can, but you have less clutter if you
21353 use the @code{AH_} macros.  @xref{Autoheader Macros}.
21355 @node Changed Makefiles
21356 @subsection Changed Makefiles
21358 Add @samp{@@CFLAGS@@}, @samp{@@CPPFLAGS@@}, and @samp{@@LDFLAGS@@} in
21359 your @file{Makefile.in} files, so they can take advantage of the values
21360 of those variables in the environment when @command{configure} is run.
21361 Doing this isn't necessary, but it's a convenience for users.
21363 Also add @samp{@@configure_input@@} in a comment to each input file for
21364 @code{AC_OUTPUT}, so that the output files contain a comment saying
21365 they were produced by @command{configure}.  Automatically selecting the
21366 right comment syntax for all the kinds of files that people call
21367 @code{AC_OUTPUT} on became too much work.
21369 Add @file{config.log} and @file{config.cache} to the list of files you
21370 remove in @code{distclean} targets.
21372 If you have the following in @file{Makefile.in}:
21374 @example
21375 prefix = /usr/local
21376 exec_prefix = $(prefix)
21377 @end example
21379 @noindent
21380 you must change it to:
21382 @example
21383 prefix = @@prefix@@
21384 exec_prefix = @@exec_prefix@@
21385 @end example
21387 @noindent
21388 The old behavior of replacing those variables without @samp{@@}
21389 characters around them has been removed.
21391 @node Changed Macros
21392 @subsection Changed Macros
21394 Many of the macros were renamed in Autoconf version 2.  You can still
21395 use the old names, but the new ones are clearer, and it's easier to find
21396 the documentation for them.  @xref{Obsolete Macros}, for a table showing the
21397 new names for the old macros.  Use the @command{autoupdate} program to
21398 convert your @file{configure.ac} to using the new macro names.
21399 @xref{autoupdate Invocation}.
21401 Some macros have been superseded by similar ones that do the job better,
21402 but are not call-compatible.  If you get warnings about calling obsolete
21403 macros while running @command{autoconf}, you may safely ignore them, but
21404 your @command{configure} script generally works better if you follow
21405 the advice that is printed about what to replace the obsolete macros with.  In
21406 particular, the mechanism for reporting the results of tests has
21407 changed.  If you were using @command{echo} or @code{AC_VERBOSE} (perhaps
21408 via @code{AC_COMPILE_CHECK}), your @command{configure} script's output
21409 looks better if you switch to @code{AC_MSG_CHECKING} and
21410 @code{AC_MSG_RESULT}.  @xref{Printing Messages}.  Those macros work best
21411 in conjunction with cache variables.  @xref{Caching Results}.
21415 @node Changed Results
21416 @subsection Changed Results
21418 If you were checking the results of previous tests by examining the
21419 shell variable @code{DEFS}, you need to switch to checking the values of
21420 the cache variables for those tests.  @code{DEFS} no longer exists while
21421 @command{configure} is running; it is only created when generating output
21422 files.  This difference from version 1 is because properly quoting the
21423 contents of that variable turned out to be too cumbersome and
21424 inefficient to do every time @code{AC_DEFINE} is called.  @xref{Cache
21425 Variable Names}.
21427 For example, here is a @file{configure.ac} fragment written for Autoconf
21428 version 1:
21430 @example
21431 AC_HAVE_FUNCS(syslog)
21432 case "$DEFS" in
21433 *-DHAVE_SYSLOG*) ;;
21434 *) # syslog is not in the default libraries.  See if it's in some other.
21435   saved_LIBS="$LIBS"
21436   for lib in bsd socket inet; do
21437     AC_CHECKING(for syslog in -l$lib)
21438     LIBS="-l$lib $saved_LIBS"
21439     AC_HAVE_FUNCS(syslog)
21440     case "$DEFS" in
21441     *-DHAVE_SYSLOG*) break ;;
21442     *) ;;
21443     esac
21444     LIBS="$saved_LIBS"
21445   done ;;
21446 esac
21447 @end example
21449 Here is a way to write it for version 2:
21451 @example
21452 AC_CHECK_FUNCS([syslog])
21453 if test $ac_cv_func_syslog = no; then
21454   # syslog is not in the default libraries.  See if it's in some other.
21455   for lib in bsd socket inet; do
21456     AC_CHECK_LIB([$lib], [syslog], [AC_DEFINE([HAVE_SYSLOG])
21457       LIBS="-l$lib $LIBS"; break])
21458   done
21460 @end example
21462 If you were working around bugs in @code{AC_DEFINE_UNQUOTED} by adding
21463 backslashes before quotes, you need to remove them.  It now works
21464 predictably, and does not treat quotes (except back quotes) specially.
21465 @xref{Setting Output Variables}.
21467 All of the Boolean shell variables set by Autoconf macros now use
21468 @samp{yes} for the true value.  Most of them use @samp{no} for false,
21469 though for backward compatibility some use the empty string instead.  If
21470 you were relying on a shell variable being set to something like 1 or
21471 @samp{t} for true, you need to change your tests.
21473 @node Changed Macro Writing
21474 @subsection Changed Macro Writing
21476 When defining your own macros, you should now use @code{AC_DEFUN}
21477 instead of @code{define}.  @code{AC_DEFUN} automatically calls
21478 @code{AC_PROVIDE} and ensures that macros called via @code{AC_REQUIRE}
21479 do not interrupt other macros, to prevent nested @samp{checking@dots{}}
21480 messages on the screen.  There's no actual harm in continuing to use the
21481 older way, but it's less convenient and attractive.  @xref{Macro
21482 Definitions}.
21484 You probably looked at the macros that came with Autoconf as a guide for
21485 how to do things.  It would be a good idea to take a look at the new
21486 versions of them, as the style is somewhat improved and they take
21487 advantage of some new features.
21489 If you were doing tricky things with undocumented Autoconf internals
21490 (macros, variables, diversions), check whether you need to change
21491 anything to account for changes that have been made.  Perhaps you can
21492 even use an officially supported technique in version 2 instead of
21493 kludging.  Or perhaps not.
21495 To speed up your locally written feature tests, add caching to them.
21496 See whether any of your tests are of general enough usefulness to
21497 encapsulate them into macros that you can share.
21500 @node Autoconf 2.13
21501 @section Upgrading From Version 2.13
21502 @cindex Upgrading autoconf
21503 @cindex Autoconf upgrading
21505 The introduction of the previous section (@pxref{Autoconf 1}) perfectly
21506 suits this section@enddots{}
21508 @quotation
21509 Autoconf version 2.50 is mostly backward compatible with version 2.13.
21510 However, it introduces better ways to do some things, and doesn't
21511 support some of the ugly things in version 2.13.  So, depending on how
21512 sophisticated your @file{configure.ac} files are, you might have to do
21513 some manual work in order to upgrade to version 2.50.  This chapter
21514 points out some problems to watch for when upgrading.  Also, perhaps
21515 your @command{configure} scripts could benefit from some of the new
21516 features in version 2.50; the changes are summarized in the file
21517 @file{NEWS} in the Autoconf distribution.
21518 @end quotation
21520 @menu
21521 * Changed Quotation::           Broken code which used to work
21522 * New Macros::                  Interaction with foreign macros
21523 * Hosts and Cross-Compilation::  Bugward compatibility kludges
21524 * AC_LIBOBJ vs LIBOBJS::        LIBOBJS is a forbidden token
21525 * AC_FOO_IFELSE vs AC_TRY_FOO::  A more generic scheme for testing sources
21526 @end menu
21528 @node Changed Quotation
21529 @subsection Changed Quotation
21531 The most important changes are invisible to you: the implementation of
21532 most macros have completely changed.  This allowed more factorization of
21533 the code, better error messages, a higher uniformity of the user's
21534 interface etc.  Unfortunately, as a side effect, some construct which
21535 used to (miraculously) work might break starting with Autoconf 2.50.
21536 The most common culprit is bad quotation.
21538 For instance, in the following example, the message is not properly
21539 quoted:
21541 @example
21542 AC_INIT
21543 AC_CHECK_HEADERS(foo.h, ,
21544   AC_MSG_ERROR(cannot find foo.h, bailing out))
21545 AC_OUTPUT
21546 @end example
21548 @noindent
21549 Autoconf 2.13 simply ignores it:
21551 @example
21552 $ @kbd{autoconf-2.13; ./configure --silent}
21553 creating cache ./config.cache
21554 configure: error: cannot find foo.h
21556 @end example
21558 @noindent
21559 while Autoconf 2.50 produces a broken @file{configure}:
21561 @example
21562 $ @kbd{autoconf-2.50; ./configure --silent}
21563 configure: error: cannot find foo.h
21564 ./configure: exit: bad non-numeric arg `bailing'
21565 ./configure: exit: bad non-numeric arg `bailing'
21567 @end example
21569 The message needs to be quoted, and the @code{AC_MSG_ERROR} invocation
21570 too!
21572 @example
21573 AC_INIT([Example], [1.0], [bug-example@@example.org])
21574 AC_CHECK_HEADERS([foo.h], [],
21575   [AC_MSG_ERROR([cannot find foo.h, bailing out])])
21576 AC_OUTPUT
21577 @end example
21579 Many many (and many more) Autoconf macros were lacking proper quotation,
21580 including no less than@dots{} @code{AC_DEFUN} itself!
21582 @example
21583 $ @kbd{cat configure.in}
21584 AC_DEFUN([AC_PROG_INSTALL],
21585 [# My own much better version
21587 AC_INIT
21588 AC_PROG_INSTALL
21589 AC_OUTPUT
21590 $ @kbd{autoconf-2.13}
21591 autoconf: Undefined macros:
21592 ***BUG in Autoconf--please report*** AC_FD_MSG
21593 ***BUG in Autoconf--please report*** AC_EPI
21594 configure.in:1:AC_DEFUN([AC_PROG_INSTALL],
21595 configure.in:5:AC_PROG_INSTALL
21596 $ @kbd{autoconf-2.50}
21598 @end example
21601 @node New Macros
21602 @subsection New Macros
21604 @cindex undefined macro
21605 @cindex @code{_m4_divert_diversion}
21607 While Autoconf was relatively dormant in the late 1990s, Automake
21608 provided Autoconf-like macros for a while.  Starting with Autoconf 2.50
21609 in 2001, Autoconf provided
21610 versions of these macros, integrated in the @code{AC_} namespace,
21611 instead of @code{AM_}.  But in order to ease the upgrading via
21612 @command{autoupdate}, bindings to such @code{AM_} macros are provided.
21614 Unfortunately older versions of Automake (e.g., Automake 1.4)
21615 did not quote the names of these macros.
21616 Therefore, when @command{m4} finds something like
21617 @samp{AC_DEFUN(AM_TYPE_PTRDIFF_T, @dots{})} in @file{aclocal.m4},
21618 @code{AM_TYPE_PTRDIFF_T} is
21619 expanded, replaced with its Autoconf definition.
21621 Fortunately Autoconf catches pre-@code{AC_INIT} expansions, and
21622 complains, in its own words:
21624 @example
21625 $ @kbd{cat configure.ac}
21626 AC_INIT([Example], [1.0], [bug-example@@example.org])
21627 AM_TYPE_PTRDIFF_T
21628 $ @kbd{aclocal-1.4}
21629 $ @kbd{autoconf}
21630 aclocal.m4:17: error: m4_defn: undefined macro: _m4_divert_diversion
21631 aclocal.m4:17: the top level
21632 autom4te: m4 failed with exit status: 1
21634 @end example
21636 Modern versions of Automake no longer define most of these
21637 macros, and properly quote the names of the remaining macros.
21638 If you must use an old Automake, do not depend upon macros from Automake
21639 as it is simply not its job
21640 to provide macros (but the one it requires itself):
21642 @example
21643 $ @kbd{cat configure.ac}
21644 AC_INIT([Example], [1.0], [bug-example@@example.org])
21645 AM_TYPE_PTRDIFF_T
21646 $ @kbd{rm aclocal.m4}
21647 $ @kbd{autoupdate}
21648 autoupdate: `configure.ac' is updated
21649 $ @kbd{cat configure.ac}
21650 AC_INIT([Example], [1.0], [bug-example@@example.org])
21651 AC_CHECK_TYPES([ptrdiff_t])
21652 $ @kbd{aclocal-1.4}
21653 $ @kbd{autoconf}
21655 @end example
21658 @node Hosts and Cross-Compilation
21659 @subsection Hosts and Cross-Compilation
21660 @cindex Cross compilation
21662 Based on the experience of compiler writers, and after long public
21663 debates, many aspects of the cross-compilation chain have changed:
21665 @itemize @minus
21666 @item
21667 the relationship between the build, host, and target architecture types,
21669 @item
21670 the command line interface for specifying them to @command{configure},
21672 @item
21673 the variables defined in @command{configure},
21675 @item
21676 the enabling of cross-compilation mode.
21677 @end itemize
21679 @sp 1
21681 The relationship between build, host, and target have been cleaned up:
21682 the chain of default is now simply: target defaults to host, host to
21683 build, and build to the result of @command{config.guess}.  Nevertheless,
21684 in order to ease the transition from 2.13 to 2.50, the following
21685 transition scheme is implemented.  @emph{Do not rely on it}, as it will
21686 be completely disabled in a couple of releases (we cannot keep it, as it
21687 proves to cause more problems than it cures).
21689 They all default to the result of running @command{config.guess}, unless
21690 you specify either @option{--build} or @option{--host}.  In this case,
21691 the default becomes the system type you specified.  If you specify both,
21692 and they're different, @command{configure} enters cross compilation
21693 mode, so it doesn't run any tests that require execution.
21695 Hint: if you mean to override the result of @command{config.guess},
21696 prefer @option{--build} over @option{--host}.  In the future,
21697 @option{--host} will not override the name of the build system type.
21698 Whenever you specify @option{--host}, be sure to specify @option{--build}
21699 too.
21701 @sp 1
21703 For backward compatibility, @command{configure} accepts a system
21704 type as an option by itself.  Such an option overrides the
21705 defaults for build, host, and target system types.  The following
21706 configure statement configures a cross toolchain that runs on
21707 Net@acronym{BSD}/alpha but generates code for @acronym{GNU} Hurd/sparc,
21708 which is also the build platform.
21710 @example
21711 ./configure --host=alpha-netbsd sparc-gnu
21712 @end example
21714 @sp 1
21716 In Autoconf 2.13 and before, the variables @code{build}, @code{host},
21717 and @code{target} had a different semantics before and after the
21718 invocation of @code{AC_CANONICAL_BUILD} etc.  Now, the argument of
21719 @option{--build} is strictly copied into @code{build_alias}, and is left
21720 empty otherwise.  After the @code{AC_CANONICAL_BUILD}, @code{build} is
21721 set to the canonicalized build type.  To ease the transition, before,
21722 its contents is the same as that of @code{build_alias}.  Do @emph{not}
21723 rely on this broken feature.
21725 For consistency with the backward compatibility scheme exposed above,
21726 when @option{--host} is specified but @option{--build} isn't, the build
21727 system is assumed to be the same as @option{--host}, and
21728 @samp{build_alias} is set to that value.  Eventually, this
21729 historically incorrect behavior will go away.
21731 @sp 1
21733 The former scheme to enable cross-compilation proved to cause more harm
21734 than good, in particular, it used to be triggered too easily, leaving
21735 regular end users puzzled in front of cryptic error messages.
21736 @command{configure} could even enter cross-compilation mode only
21737 because the compiler was not functional.  This is mainly because
21738 @command{configure} used to try to detect cross-compilation, instead of
21739 waiting for an explicit flag from the user.
21741 Now, @command{configure} enters cross-compilation mode if and only if
21742 @option{--host} is passed.
21744 That's the short documentation.  To ease the transition between 2.13 and
21745 its successors, a more complicated scheme is implemented.  @emph{Do not
21746 rely on the following}, as it will be removed in the near future.
21748 If you specify @option{--host}, but not @option{--build}, when
21749 @command{configure} performs the first compiler test it tries to run
21750 an executable produced by the compiler.  If the execution fails, it
21751 enters cross-compilation mode.  This is fragile.  Moreover, by the time
21752 the compiler test is performed, it may be too late to modify the
21753 build-system type: other tests may have already been performed.
21754 Therefore, whenever you specify @option{--host}, be sure to specify
21755 @option{--build} too.
21757 @example
21758 ./configure --build=i686-pc-linux-gnu --host=m68k-coff
21759 @end example
21761 @noindent
21762 enters cross-compilation mode.  The former interface, which
21763 consisted in setting the compiler to a cross-compiler without informing
21764 @command{configure} is obsolete.  For instance, @command{configure}
21765 fails if it can't run the code generated by the specified compiler if you
21766 configure as follows:
21768 @example
21769 ./configure CC=m68k-coff-gcc
21770 @end example
21773 @node AC_LIBOBJ vs LIBOBJS
21774 @subsection @code{AC_LIBOBJ} vs.@: @code{LIBOBJS}
21776 Up to Autoconf 2.13, the replacement of functions was triggered via the
21777 variable @code{LIBOBJS}.  Since Autoconf 2.50, the macro
21778 @code{AC_LIBOBJ} should be used instead (@pxref{Generic Functions}).
21779 Starting at Autoconf 2.53, the use of @code{LIBOBJS} is an error.
21781 This change is mandated by the unification of the @acronym{GNU} Build System
21782 components.  In particular, the various fragile techniques used to parse
21783 a @file{configure.ac} are all replaced with the use of traces.  As a
21784 consequence, any action must be traceable, which obsoletes critical
21785 variable assignments.  Fortunately, @code{LIBOBJS} was the only problem,
21786 and it can even be handled gracefully (read, ``without your having to
21787 change something'').
21789 There were two typical uses of @code{LIBOBJS}: asking for a replacement
21790 function, and adjusting @code{LIBOBJS} for Automake and/or Libtool.
21792 @sp 1
21794 As for function replacement, the fix is immediate: use
21795 @code{AC_LIBOBJ}.  For instance:
21797 @example
21798 LIBOBJS="$LIBOBJS fnmatch.o"
21799 LIBOBJS="$LIBOBJS malloc.$ac_objext"
21800 @end example
21802 @noindent
21803 should be replaced with:
21805 @example
21806 AC_LIBOBJ([fnmatch])
21807 AC_LIBOBJ([malloc])
21808 @end example
21810 @sp 1
21812 @ovindex LIBOBJDIR
21813 When used with Automake 1.10 or newer, a suitable value for
21814 @code{LIBOBJDIR} is set so that the @code{LIBOBJS} and @code{LTLIBOBJS}
21815 can be referenced from any @file{Makefile.am}.  Even without Automake,
21816 arranging for @code{LIBOBJDIR} to be set correctly enables
21817 referencing @code{LIBOBJS} and @code{LTLIBOBJS} in another directory.
21818 The @code{LIBOBJDIR} feature is experimental.
21821 @node AC_FOO_IFELSE vs AC_TRY_FOO
21822 @subsection @code{AC_FOO_IFELSE} vs.@: @code{AC_TRY_FOO}
21824 Since Autoconf 2.50, internal codes uses @code{AC_PREPROC_IFELSE},
21825 @code{AC_COMPILE_IFELSE}, @code{AC_LINK_IFELSE}, and
21826 @code{AC_RUN_IFELSE} on one hand and @code{AC_LANG_SOURCES},
21827 and @code{AC_LANG_PROGRAM} on the other hand instead of the deprecated
21828 @code{AC_TRY_CPP}, @code{AC_TRY_COMPILE}, @code{AC_TRY_LINK}, and
21829 @code{AC_TRY_RUN}.  The motivations where:
21830 @itemize @minus
21831 @item
21832 a more consistent interface: @code{AC_TRY_COMPILE} etc.@: were double
21833 quoting their arguments;
21835 @item
21836 the combinatoric explosion is solved by decomposing on the one hand the
21837 generation of sources, and on the other hand executing the program;
21839 @item
21840 this scheme helps supporting more languages than plain C and C++.
21841 @end itemize
21843 In addition to the change of syntax, the philosophy has changed too:
21844 while emphasis was put on speed at the expense of accuracy, today's
21845 Autoconf promotes accuracy of the testing framework at, ahem@dots{}, the
21846 expense of speed.
21849 As a perfect example of what is @emph{not} to be done, here is how to
21850 find out whether a header file contains a particular declaration, such
21851 as a typedef, a structure, a structure member, or a function.  Use
21852 @code{AC_EGREP_HEADER} instead of running @code{grep} directly on the
21853 header file; on some systems the symbol might be defined in another
21854 header file that the file you are checking includes.
21856 As a (bad) example, here is how you should not check for C preprocessor
21857 symbols, either defined by header files or predefined by the C
21858 preprocessor: using @code{AC_EGREP_CPP}:
21860 @example
21861 @group
21862 AC_EGREP_CPP(yes,
21863 [#ifdef _AIX
21864   yes
21865 #endif
21866 ], is_aix=yes, is_aix=no)
21867 @end group
21868 @end example
21870 The above example, properly written would (i) use
21871 @code{AC_LANG_PROGRAM}, and (ii) run the compiler:
21873 @example
21874 @group
21875 AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
21876 [[#ifndef _AIX
21877  error: This isn't AIX!
21878 #endif
21879 ]])],
21880                    [is_aix=yes],
21881                    [is_aix=no])
21882 @end group
21883 @end example
21886 @c ============================= Generating Test Suites with Autotest
21888 @node Using Autotest
21889 @chapter Generating Test Suites with Autotest
21891 @cindex Autotest
21893 @display
21894 @strong{N.B.: This section describes a feature which is still
21895 stabilizing.  Although we believe that Autotest is useful as-is, this
21896 documentation describes an interface which might change in the future:
21897 do not depend upon Autotest without subscribing to the Autoconf mailing
21898 lists.}
21899 @end display
21901 It is paradoxical that portable projects depend on nonportable tools
21902 to run their test suite.  Autoconf by itself is the paragon of this
21903 problem: although it aims at perfectly portability, up to 2.13 its
21904 test suite was using Deja@acronym{GNU}, a rich and complex testing
21905 framework, but which is far from being standard on Posix systems.
21906 Worse yet, it was likely to be missing on the most fragile platforms,
21907 the very platforms that are most likely to torture Autoconf and
21908 exhibit deficiencies.
21910 To circumvent this problem, many package maintainers have developed their
21911 own testing framework, based on simple shell scripts whose sole outputs
21912 are exit status values describing whether the test succeeded.  Most of
21913 these tests share common patterns, and this can result in lots of
21914 duplicated code and tedious maintenance.
21916 Following exactly the same reasoning that yielded to the inception of
21917 Autoconf, Autotest provides a test suite generation framework, based on
21918 M4 macros building a portable shell script.  The suite itself is
21919 equipped with automatic logging and tracing facilities which greatly
21920 diminish the interaction with bug reporters, and simple timing reports.
21922 Autoconf itself has been using Autotest for years, and we do attest that
21923 it has considerably improved the strength of the test suite and the
21924 quality of bug reports.  Other projects are known to use some generation
21925 of Autotest, such as Bison, Free Recode, Free Wdiff, @acronym{GNU} Tar, each of
21926 them with different needs, and this usage has validated Autotest as a general
21927 testing framework.
21929 Nonetheless, compared to Deja@acronym{GNU}, Autotest is inadequate for
21930 interactive tool testing, which is probably its main limitation.
21932 @menu
21933 * Using an Autotest Test Suite::  Autotest and the user
21934 * Writing Testsuites::          Autotest macros
21935 * testsuite Invocation::        Running @command{testsuite} scripts
21936 * Making testsuite Scripts::    Using autom4te to create @command{testsuite}
21937 @end menu
21939 @node Using an Autotest Test Suite
21940 @section Using an Autotest Test Suite
21942 @menu
21943 * testsuite Scripts::           The concepts of Autotest
21944 * Autotest Logs::               Their contents
21945 @end menu
21947 @node testsuite Scripts
21948 @subsection @command{testsuite} Scripts
21950 @cindex @command{testsuite}
21952 Generating testing or validation suites using Autotest is rather easy.
21953 The whole validation suite is held in a file to be processed through
21954 @command{autom4te}, itself using @acronym{GNU} M4 under the scene, to
21955 produce a stand-alone Bourne shell script which then gets distributed.
21956 Neither @command{autom4te} nor @acronym{GNU} M4 are needed at
21957 the installer's end.
21959 @cindex test group
21960 Each test of the validation suite should be part of some test group.  A
21961 @dfn{test group} is a sequence of interwoven tests that ought to be
21962 executed together, usually because one test in the group creates data
21963 files than a later test in the same group needs to read.  Complex test
21964 groups make later debugging more tedious.  It is much better to
21965 keep only a few tests per test group.  Ideally there is only one test
21966 per test group.
21968 For all but the simplest packages, some file such as @file{testsuite.at}
21969 does not fully hold all test sources, as these are often easier to
21970 maintain in separate files.  Each of these separate files holds a single
21971 test group, or a sequence of test groups all addressing some common
21972 functionality in the package.  In such cases, @file{testsuite.at}
21973 merely initializes the validation suite, and sometimes does elementary
21974 health checking, before listing include statements for all other test
21975 files.  The special file @file{package.m4}, containing the
21976 identification of the package, is automatically included if found.
21978 A convenient alternative consists in moving all the global issues
21979 (local Autotest macros, elementary health checking, and @code{AT_INIT}
21980 invocation) into the file @code{local.at}, and making
21981 @file{testsuite.at} be a simple list of @code{m4_include} of sub test
21982 suites.  In such case, generating the whole test suite or pieces of it
21983 is only a matter of choosing the @command{autom4te} command line
21984 arguments.
21986 The validation scripts that Autotest produces are by convention called
21987 @command{testsuite}.  When run, @command{testsuite} executes each test
21988 group in turn, producing only one summary line per test to say if that
21989 particular test succeeded or failed.  At end of all tests, summarizing
21990 counters get printed.  One debugging directory is left for each test
21991 group which failed, if any: such directories are named
21992 @file{testsuite.dir/@var{nn}}, where @var{nn} is the sequence number of
21993 the test group, and they include:
21995 @itemize @bullet
21996 @item a debugging script named @file{run} which reruns the test in
21997 @dfn{debug mode} (@pxref{testsuite Invocation}).  The automatic generation
21998 of debugging scripts has the purpose of easing the chase for bugs.
22000 @item all the files created with @code{AT_DATA}
22002 @item a log of the run, named @file{testsuite.log}
22003 @end itemize
22005 In the ideal situation, none of the tests fail, and consequently no
22006 debugging directory is left behind for validation.
22008 It often happens in practice that individual tests in the validation
22009 suite need to get information coming out of the configuration process.
22010 Some of this information, common for all validation suites, is provided
22011 through the file @file{atconfig}, automatically created by
22012 @code{AC_CONFIG_TESTDIR}.  For configuration informations which your
22013 testing environment specifically needs, you might prepare an optional
22014 file named @file{atlocal.in}, instantiated by @code{AC_CONFIG_FILES}.
22015 The configuration process produces @file{atconfig} and @file{atlocal}
22016 out of these two input files, and these two produced files are
22017 automatically read by the @file{testsuite} script.
22019 Here is a diagram showing the relationship between files.
22021 @noindent
22022 Files used in preparing a software package for distribution:
22024 @example
22025                 [package.m4] -->.
22026                                  \
22027 subfile-1.at ->.  [local.at] ---->+
22028     ...         \                  \
22029 subfile-i.at ---->-- testsuite.at -->-- autom4te* -->testsuite
22030     ...         /
22031 subfile-n.at ->'
22032 @end example
22034 @noindent
22035 Files used in configuring a software package:
22037 @example
22038                                      .--> atconfig
22039                                     /
22040 [atlocal.in] -->  config.status* --<
22041                                     \
22042                                      `--> [atlocal]
22043 @end example
22045 @noindent
22046 Files created during the test suite execution:
22048 @example
22049 atconfig -->.                    .--> testsuite.log
22050              \                  /
22051               >-- testsuite* --<
22052              /                  \
22053 [atlocal] ->'                    `--> [testsuite.dir]
22054 @end example
22057 @node Autotest Logs
22058 @subsection Autotest Logs
22060 When run, the test suite creates a log file named after itself, e.g., a
22061 test suite named @command{testsuite} creates @file{testsuite.log}.  It
22062 contains a lot of information, usually more than maintainers actually
22063 need, but therefore most of the time it contains all that is needed:
22065 @table @asis
22066 @item command line arguments
22067 @c akim s/to consist in/to consist of/
22068 A bad but unfortunately widespread habit consists of
22069 setting environment variables before the command, such as in
22070 @samp{CC=my-home-grown-cc ./testsuite}.  The test suite does not
22071 know this change, hence (i) it cannot report it to you, and (ii)
22072 it cannot preserve the value of @code{CC} for subsequent runs.
22073 Autoconf faced exactly the same problem, and solved it by asking
22074 users to pass the variable definitions as command line arguments.
22075 Autotest requires this rule, too, but has no means to enforce it; the log
22076 then contains a trace of the variables that were changed by the user.
22078 @item @file{ChangeLog} excerpts
22079 The topmost lines of all the @file{ChangeLog} files found in the source
22080 hierarchy.  This is especially useful when bugs are reported against
22081 development versions of the package, since the version string does not
22082 provide sufficient information to know the exact state of the sources
22083 the user compiled.  Of course, this relies on the use of a
22084 @file{ChangeLog}.
22086 @item build machine
22087 Running a test suite in a cross-compile environment is not an easy task,
22088 since it would mean having the test suite run on a machine @var{build},
22089 while running programs on a machine @var{host}.  It is much simpler to
22090 run both the test suite and the programs on @var{host}, but then, from
22091 the point of view of the test suite, there remains a single environment,
22092 @var{host} = @var{build}.  The log contains relevant information on the
22093 state of the build machine, including some important environment
22094 variables.
22095 @c FIXME: How about having an M4sh macro to say `hey, log the value
22096 @c of `@dots{}'?  This would help both Autoconf and Autotest.
22098 @item tested programs
22099 The absolute file name and answers to @option{--version} of the tested
22100 programs (see @ref{Writing Testsuites}, @code{AT_TESTED}).
22102 @item configuration log
22103 The contents of @file{config.log}, as created by @command{configure},
22104 are appended.  It contains the configuration flags and a detailed report
22105 on the configuration itself.
22106 @end table
22109 @node Writing Testsuites
22110 @section Writing @file{testsuite.at}
22112 The @file{testsuite.at} is a Bourne shell script making use of special
22113 Autotest M4 macros.  It often contains a call to @code{AT_INIT} near
22114 its beginning followed by one call to @code{m4_include} per source file
22115 for tests.  Each such included file, or the remainder of
22116 @file{testsuite.at} if include files are not used, contain a sequence of
22117 test groups.  Each test group begins with a call to @code{AT_SETUP},
22118 then an arbitrary number of shell commands or calls to @code{AT_CHECK},
22119 and then completes with a call to @code{AT_CLEANUP}.  Multiple test
22120 groups can be categorized by a call to @code{AT_BANNER}.
22122 All of the public Autotest macros have all-uppercase names in the
22123 namespace @samp{^AT_} to prevent them from accidentally conflicting with
22124 other text; Autoconf also reserves the namespace @samp{^_AT_} for
22125 internal macros.  All shell variables used in the testsuite for internal
22126 purposes have mostly-lowercase names starting with @samp{at_}.  Autotest
22127 also uses here-doc delimiters in the namespace @samp{^_AT[A-Z]}, and
22128 makes use of the file system namespace @samp{^at-}.
22130 Since Autoconf is built on top of M4sugar (@pxref{Programming in
22131 M4sugar}) and M4sh (@pxref{Programming in M4sh}), you must also be aware
22132 of those namespaces (@samp{^_?\(m4\|AS\)_}).  In general, you
22133 @emph{should not use} the namespace of a package that does not own the
22134 macro or shell code you are writing.
22136 @defmac AT_INIT (@ovar{name})
22137 @atindex{INIT}
22138 @c FIXME: Not clear, plus duplication of the information.
22139 Initialize Autotest.  Giving a @var{name} to the test suite is
22140 encouraged if your package includes several test suites.  Before this
22141 macro is called, @code{AT_PACKAGE_STRING} and
22142 @code{AT_PACKAGE_BUGREPORT} must be defined, which are used to display
22143 information about the testsuite to the user.  Typically, these macros
22144 are provided by a file @file{package.m4} built by @command{make}
22145 (@pxref{Making testsuite Scripts}), in order to inherit the package
22146 name, version, and bug reporting address from @file{configure.ac}.
22147 @end defmac
22149 @defmac AT_COPYRIGHT (@var{copyright-notice})
22150 @atindex{COPYRIGHT}
22151 @cindex Copyright Notice
22152 State that, in addition to the Free Software Foundation's copyright on
22153 the Autotest macros, parts of your test suite are covered by
22154 @var{copyright-notice}.
22156 The @var{copyright-notice} shows up in both the head of
22157 @command{testsuite} and in @samp{testsuite --version}.
22158 @end defmac
22160 @defmac AT_TESTED (@var{executables})
22161 @atindex{TESTED}
22162 Log the file name and answer to @option{--version} of each program in
22163 space-separated list @var{executables}.  Several invocations register
22164 new executables, in other words, don't fear registering one program
22165 several times.
22166 @end defmac
22168 Autotest test suites rely on @env{PATH} to find the tested program.
22169 This avoids the need to generate absolute names of the various tools, and
22170 makes it possible to test installed programs.  Therefore, knowing which
22171 programs are being exercised is crucial to understanding problems in
22172 the test suite itself, or its occasional misuses.  It is a good idea to
22173 also subscribe foreign programs you depend upon, to avoid incompatible
22174 diagnostics.
22176 @sp 1
22178 @defmac AT_BANNER (@var{test-category-name})
22179 @atindex{BANNER}
22180 This macro identifies the start of a category of related test groups.
22181 When the resulting @file{testsuite} is invoked with more than one test
22182 group to run, its output will include a banner containing
22183 @var{test-category-name} prior to any tests run from that category.  The
22184 banner should be no more than about 40 or 50 characters.  A blank banner
22185 will not print, effectively ending a category and letting subsequent
22186 test groups behave as though they are uncategorized when run in
22187 isolation.
22188 @end defmac
22190 @defmac AT_SETUP (@var{test-group-name})
22191 @atindex{SETUP}
22192 This macro starts a group of related tests, all to be executed in the
22193 same subshell.  It accepts a single argument, which holds a few words
22194 (no more than about 30 or 40 characters) quickly describing the purpose
22195 of the test group being started.  @var{test-group-name} must not expand
22196 to unbalanced quotes, although quadrigraphs can be used.
22197 @end defmac
22199 @defmac AT_KEYWORDS (@var{keywords})
22200 @atindex{KEYWORDS}
22201 Associate the space-separated list of @var{keywords} to the enclosing
22202 test group.  This makes it possible to run ``slices'' of the test suite.
22203 For instance, if some of your test groups exercise some @samp{foo}
22204 feature, then using @samp{AT_KEYWORDS(foo)} lets you run
22205 @samp{./testsuite -k foo} to run exclusively these test groups.  The
22206 @var{title} of the test group is automatically recorded to
22207 @code{AT_KEYWORDS}.
22209 Several invocations within a test group accumulate new keywords.  In
22210 other words, don't fear registering the same keyword several times in a
22211 test group.
22212 @end defmac
22214 @defmac AT_CAPTURE_FILE (@var{file})
22215 @atindex{CAPTURE_FILE}
22216 If the current test group fails, log the contents of @var{file}.
22217 Several identical calls within one test group have no additional effect.
22218 @end defmac
22220 @defmac AT_XFAIL_IF (@var{shell-condition})
22221 @atindex{XFAIL_IF}
22222 Determine whether the test is expected to fail because it is a known
22223 bug (for unsupported features, you should skip the test).
22224 @var{shell-condition} is a shell expression such as a @code{test}
22225 command; you can instantiate this macro many times from within the
22226 same test group, and one of the conditions is enough to turn
22227 the test into an expected failure.
22228 @end defmac
22230 @defmac AT_CLEANUP
22231 @atindex{CLEANUP}
22232 End the current test group.
22233 @end defmac
22235 @sp 1
22237 @defmac AT_DATA (@var{file}, @var{contents})
22238 @atindex{DATA}
22239 Initialize an input data @var{file} with given @var{contents}.  Of
22240 course, the @var{contents} have to be properly quoted between square
22241 brackets to protect against included commas or spurious M4
22242 expansion.  The contents must end with an end of line.  @var{file} must
22243 be a single shell word that expands into a single file name.
22244 @end defmac
22246 @defmac AT_CHECK (@var{commands}, @dvar{status, 0}, @dvar{stdout, }, @
22247   @dvar{stderr, }, @ovar{run-if-fail}, @ovar{run-if-pass})
22248 @atindex{CHECK}
22249 Execute a test by performing given shell @var{commands}.  These commands
22250 should normally exit with @var{status}, while producing expected
22251 @var{stdout} and @var{stderr} contents.  If @var{commands} exit with
22252 status 77, then the whole test group is skipped.  Otherwise, if this test
22253 fails, run shell commands @var{run-if-fail} or, if this test passes, run shell
22254 commands @var{run-if-pass}.
22256 This macro must be invoked in between @code{AT_SETUP} and @code{AT_CLEANUP}.
22258 @c Previously, we had this:
22259 @c  The @var{commands} @emph{must not} redirect the standard output, nor the
22260 @c  standard error.
22261 @c to prevent trigerring the double redirect bug on Ultrix, see
22262 @c `File Descriptors'.  This was too restricting, and Ultrix is pretty
22263 @c much dead, so we dropped the limitation; the obvious workaround on
22264 @c Ultrix is to use a working shell there.
22266 If @var{status}, or @var{stdout}, or @var{stderr} is @samp{ignore}, then
22267 the corresponding value is not checked.
22269 The special value @samp{expout} for @var{stdout} means the expected
22270 output of the @var{commands} is the content of the file @file{expout}.
22271 If @var{stdout} is @samp{stdout}, then the standard output of the
22272 @var{commands} is available for further tests in the file @file{stdout}.
22273 Similarly for @var{stderr} with @samp{experr} and @samp{stderr}.
22274 @end defmac
22277 @node testsuite Invocation
22278 @section Running @command{testsuite} Scripts
22279 @cindex @command{testsuite}
22281 Autotest test suites support the following arguments:
22283 @table @option
22284 @item --help
22285 @itemx -h
22286 Display the list of options and exit successfully.
22288 @item --version
22289 @itemx -V
22290 Display the version of the test suite and exit successfully.
22292 @item --directory=@var{dir}
22293 @itemx -C @var{dir}
22294 Change the current directory to @var{dir} before creating any files.
22295 Useful for running the testsuite in a subdirectory from a top-level
22296 Makefile.
22298 @item --jobs@r{[}=@var{n}@r{]}
22299 @itemx -j@ovar{n}
22300 Run @var{n} tests in parallel, if possible.  If @var{n} is not given,
22301 run all given tests in parallel.  Note that there should be no space
22302 before the argument to @option{-j}, as @option{-j @var{number}} denotes
22303 the separate arguments @option{-j} and @option{@var{number}}, see below.
22305 In parallel mode, the standard input device of the testsuite script is
22306 not available to commands inside a test group.  Furthermore, banner
22307 lines are not printed, and the summary line for each test group is
22308 output after the test group completes.  Summary lines may appear
22309 unordered.  If verbose and trace output are enabled (see below), they
22310 may appear intermixed from concurrently running tests.
22312 Parallel mode requires the @command{mkfifo} command to work, and will be
22313 silently disabled otherwise.
22315 @item --clean
22316 @itemx -c
22317 Remove all the files the test suite might have created and exit.  Meant
22318 for @code{clean} Make targets.
22320 @item --list
22321 @itemx -l
22322 List all the tests (or only the selection), including their possible
22323 keywords.
22324 @end table
22326 @sp 1
22328 By default all tests are performed (or described with
22329 @option{--list}) in the default environment first silently, then
22330 verbosely, but the environment, set of tests, and verbosity level can be
22331 tuned:
22333 @table @samp
22334 @item @var{variable}=@var{value}
22335 Set the environment @var{variable} to @var{value}.  Use this rather
22336 than @samp{FOO=foo ./testsuite} as debugging scripts would then run in a
22337 different environment.
22339 @cindex @code{AUTOTEST_PATH}
22340 The variable @code{AUTOTEST_PATH} specifies the testing path to prepend
22341 to @env{PATH}.  Relative directory names (not starting with
22342 @samp{/}) are considered to be relative to the top level of the
22343 package being built.  All directories are made absolute, first
22344 starting from the top level @emph{build} tree, then from the
22345 @emph{source} tree.  For instance @samp{./testsuite
22346 AUTOTEST_PATH=tests:bin} for a @file{/src/foo-1.0} source package built
22347 in @file{/tmp/foo} results in @samp{/tmp/foo/tests:/tmp/foo/bin} and
22348 then @samp{/src/foo-1.0/tests:/src/foo-1.0/bin} being prepended to
22349 @env{PATH}.
22351 @item @var{number}
22352 @itemx @var{number}-@var{number}
22353 @itemx @var{number}-
22354 @itemx -@var{number}
22355 Add the corresponding test groups, with obvious semantics, to the
22356 selection.
22358 @item --keywords=@var{keywords}
22359 @itemx -k @var{keywords}
22360 Add to the selection the test groups with title or keywords (arguments
22361 to @code{AT_SETUP} or @code{AT_KEYWORDS}) that match @emph{all} keywords
22362 of the comma separated list @var{keywords}, case-insensitively.  Use
22363 @samp{!} immediately before the keyword to invert the selection for this
22364 keyword.  By default, the keywords match whole words; enclose them in
22365 @samp{.*} to also match parts of words.
22367 For example, running
22369 @example
22370 @kbd{./testsuite -k 'autoupdate,.*FUNC.*'}
22371 @end example
22373 @noindent
22374 selects all tests tagged @samp{autoupdate} @emph{and} with tags
22375 containing @samp{FUNC} (as in @samp{AC_CHECK_FUNC}, @samp{AC_FUNC_ALLOCA},
22376 etc.), while
22378 @example
22379 @kbd{./testsuite -k '!autoupdate' -k '.*FUNC.*'}
22380 @end example
22382 @noindent
22383 selects all tests not tagged @samp{autoupdate} @emph{or} with tags
22384 containing @samp{FUNC}.
22386 @item --errexit
22387 @itemx -e
22388 If any test fails, immediately abort testing.  It implies
22389 @option{--debug}: post test group clean up, and top-level logging
22390 are inhibited.  This option is meant for the full test
22391 suite, it is not really useful for generated debugging scripts.
22392 If the testsuite is run in parallel mode using @option{--jobs},
22393 then concurrently running tests will finish before exiting.
22395 @item --verbose
22396 @itemx -v
22397 Force more verbosity in the detailed output of what is being done.  This
22398 is the default for debugging scripts.
22400 @item --debug
22401 @itemx -d
22402 Do not remove the files after a test group was performed ---but they are
22403 still removed @emph{before}, therefore using this option is sane when
22404 running several test groups.  Create debugging scripts.  Do not
22405 overwrite the top-level
22406 log (in order to preserve supposedly existing full log file).  This is
22407 the default for debugging scripts, but it can also be useful to debug
22408 the testsuite itself.
22410 @item --trace
22411 @itemx -x
22412 Trigger shell tracing of the test groups.
22413 @end table
22416 @node Making testsuite Scripts
22417 @section Making @command{testsuite} Scripts
22419 For putting Autotest into movement, you need some configuration and
22420 makefile machinery.  We recommend, at least if your package uses deep or
22421 shallow hierarchies, that you use @file{tests/} as the name of the
22422 directory holding all your tests and their makefile.  Here is a
22423 check list of things to do.
22425 @itemize @minus
22427 @item
22428 @cindex @file{package.m4}
22429 @atindex{PACKAGE_STRING}
22430 @atindex{PACKAGE_BUGREPORT}
22431 @atindex{PACKAGE_NAME}
22432 @atindex{PACKAGE_TARNAME}
22433 @atindex{PACKAGE_VERSION}
22434 @atindex{PACKAGE_URL}
22435 Make sure to create the file @file{package.m4}, which defines the
22436 identity of the package.  It must define @code{AT_PACKAGE_STRING}, the
22437 full signature of the package, and @code{AT_PACKAGE_BUGREPORT}, the
22438 address to which bug reports should be sent.  For sake of completeness,
22439 we suggest that you also define @code{AT_PACKAGE_NAME},
22440 @code{AT_PACKAGE_TARNAME}, @code{AT_PACKAGE_VERSION}, and
22441 @code{AT_PACKAGE_URL}.
22442 @xref{Initializing configure}, for a description of these variables.
22443 Be sure to distribute @file{package.m4} and to put it into the source
22444 hierarchy: the test suite ought to be shipped!  See below for an example
22445 @file{Makefile} excerpt.
22447 @item
22448 Invoke @code{AC_CONFIG_TESTDIR}.
22450 @defmac AC_CONFIG_TESTDIR (@var{directory}, @dvar{test-path, directory})
22451 @acindex{CONFIG_TESTDIR}
22452 An Autotest test suite is to be configured in @var{directory}.  This
22453 macro requires the instantiation of @file{@var{directory}/atconfig} from
22454 @file{@var{directory}/atconfig.in}, and sets the default
22455 @code{AUTOTEST_PATH} to @var{test-path} (@pxref{testsuite Invocation}).
22456 @end defmac
22458 @item
22459 Still within @file{configure.ac}, as appropriate, ensure that some
22460 @code{AC_CONFIG_FILES} command includes substitution for
22461 @file{tests/atlocal}.
22463 @item
22464 The appropriate @file{Makefile} should be modified so the validation in
22465 your package is triggered by @samp{make check}.  An example is provided
22466 below.
22467 @end itemize
22469 With Automake, here is a minimal example for inclusion in
22470 @file{tests/Makefile.am}, in order to link @samp{make check} with a
22471 validation suite.
22473 @example
22474 # The `:;' works around a Bash 3.2 bug when the output is not writeable.
22475 $(srcdir)/package.m4: $(top_srcdir)/configure.ac
22476         :;@{ \
22477           echo '# Signature of the current package.' && \
22478           echo 'm4_define([AT_PACKAGE_NAME],' && \
22479           echo '  [@@PACKAGE_NAME@@])' && \
22480           echo 'm4_define([AT_PACKAGE_TARNAME],' && \
22481           echo '  [@@PACKAGE_TARNAME@@])' && \
22482           echo 'm4_define([AT_PACKAGE_VERSION],' && \
22483           echo '  [@@PACKAGE_VERSION@@])' && \
22484           echo 'm4_define([AT_PACKAGE_STRING],' && \
22485           echo '  [@@PACKAGE_STRING@@])' && \
22486           echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \
22487           echo '  [@@PACKAGE_BUGREPORT@@])'; \
22488           echo 'm4_define([AT_PACKAGE_URL],' && \
22489           echo '  [@@PACKAGE_URL@@])'; \
22490         @} >'$(srcdir)/package.m4'
22492 EXTRA_DIST = testsuite.at $(srcdir)/package.m4 $(TESTSUITE) atlocal.in
22493 TESTSUITE = $(srcdir)/testsuite
22495 check-local: atconfig atlocal $(TESTSUITE)
22496         $(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS)
22498 installcheck-local: atconfig atlocal $(TESTSUITE)
22499         $(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='$(bindir)' \
22500           $(TESTSUITEFLAGS)
22502 clean-local:
22503         test ! -f '$(TESTSUITE)' || \
22504          $(SHELL) '$(TESTSUITE)' --clean
22506 AUTOM4TE = $(SHELL) $(srcdir)/build-aux/missing --run autom4te
22507 AUTOTEST = $(AUTOM4TE) --language=autotest
22508 $(TESTSUITE): $(srcdir)/testsuite.at $(srcdir)/package.m4
22509         $(AUTOTEST) -I '$(srcdir)' -o $@@.tmp $@@.at
22510         mv $@@.tmp $@@
22511 @end example
22513 Note that the built testsuite is distributed; this is necessary because
22514 users might not have Autoconf installed, and thus would not be able to
22515 rebuild it.  Likewise, the use of @file{missing} provides the user with
22516 a nicer error message if they modify a source file to the testsuite, and
22517 accidentally trigger the rebuild rules.
22519 You might want to list explicitly the dependencies, i.e., the list of
22520 the files @file{testsuite.at} includes.
22522 If you don't use Automake, you should include the above example in
22523 @file{tests/@/Makefile.in}, along with additional lines inspired from
22524 the following:
22526 @example
22527 subdir = tests
22529 atconfig: $(top_builddir)/config.status
22530         cd $(top_builddir) && \
22531            $(SHELL) ./config.status $(subdir)/$@@
22533 atlocal: $(srcdir)/atlocal.in $(top_builddir)/config.status
22534         cd $(top_builddir) && \
22535            $(SHELL) ./config.status $(subdir)/$@@
22536 @end example
22538 @noindent
22539 and manage to have @code{$(EXTRA_DIST)} distributed.  You will also want
22540 to distribute the file @file{build-aux/@/missing} from the Automake
22541 project; a copy of this file resides in the Autoconf source.
22543 With all this in place, and if you have not initialized @samp{TESTSUITEFLAGS}
22544 within your makefile, you can fine-tune test suite execution with this
22545 variable, for example:
22547 @example
22548 make check TESTSUITEFLAGS='-v -d -x 75 -k AC_PROG_CC CFLAGS=-g'
22549 @end example
22553 @c =============================== Frequent Autoconf Questions, with answers
22555 @node FAQ
22556 @chapter Frequent Autoconf Questions, with answers
22558 Several questions about Autoconf come up occasionally.  Here some of them
22559 are addressed.
22561 @menu
22562 * Distributing::                Distributing @command{configure} scripts
22563 * Why GNU M4::                  Why not use the standard M4?
22564 * Bootstrapping::               Autoconf and @acronym{GNU} M4 require each other?
22565 * Why Not Imake::               Why @acronym{GNU} uses @command{configure} instead of Imake
22566 * Defining Directories::        Passing @code{datadir} to program
22567 * Autom4te Cache::              What is it?  Can I remove it?
22568 * Present But Cannot Be Compiled::  Compiler and Preprocessor Disagree
22569 * Expanded Before Required::    Expanded Before Required
22570 @end menu
22572 @node Distributing
22573 @section Distributing @command{configure} Scripts
22574 @cindex License
22576 @display
22577 What are the restrictions on distributing @command{configure}
22578 scripts that Autoconf generates?  How does that affect my
22579 programs that use them?
22580 @end display
22582 There are no restrictions on how the configuration scripts that Autoconf
22583 produces may be distributed or used.  In Autoconf version 1, they were
22584 covered by the @acronym{GNU} General Public License.  We still encourage
22585 software authors to distribute their work under terms like those of the
22586 @acronym{GPL}, but doing so is not required to use Autoconf.
22588 Of the other files that might be used with @command{configure},
22589 @file{config.h.in} is under whatever copyright you use for your
22590 @file{configure.ac}.  @file{config.sub} and @file{config.guess} have an
22591 exception to the @acronym{GPL} when they are used with an Autoconf-generated
22592 @command{configure} script, which permits you to distribute them under the
22593 same terms as the rest of your package.  @file{install-sh} is from the X
22594 Consortium and is not copyrighted.
22596 @node Why GNU M4
22597 @section Why Require @acronym{GNU} M4?
22599 @display
22600 Why does Autoconf require @acronym{GNU} M4?
22601 @end display
22603 Many M4 implementations have hard-coded limitations on the size and
22604 number of macros that Autoconf exceeds.  They also lack several
22605 builtin macros that it would be difficult to get along without in a
22606 sophisticated application like Autoconf, including:
22608 @example
22609 m4_builtin
22610 m4_indir
22611 m4_bpatsubst
22612 __file__
22613 __line__
22614 @end example
22616 Autoconf requires version 1.4.5 or later of @acronym{GNU} M4.
22618 Since only software maintainers need to use Autoconf, and since @acronym{GNU}
22619 M4 is simple to configure and install, it seems reasonable to require
22620 @acronym{GNU} M4 to be installed also.  Many maintainers of @acronym{GNU} and
22621 other free software already have most of the @acronym{GNU} utilities
22622 installed, since they prefer them.
22624 @node Bootstrapping
22625 @section How Can I Bootstrap?
22626 @cindex Bootstrap
22628 @display
22629 If Autoconf requires @acronym{GNU} M4 and @acronym{GNU} M4 has an Autoconf
22630 @command{configure} script, how do I bootstrap?  It seems like a chicken
22631 and egg problem!
22632 @end display
22634 This is a misunderstanding.  Although @acronym{GNU} M4 does come with a
22635 @command{configure} script produced by Autoconf, Autoconf is not required
22636 in order to run the script and install @acronym{GNU} M4.  Autoconf is only
22637 required if you want to change the M4 @command{configure} script, which few
22638 people have to do (mainly its maintainer).
22640 @node Why Not Imake
22641 @section Why Not Imake?
22642 @cindex Imake
22644 @display
22645 Why not use Imake instead of @command{configure} scripts?
22646 @end display
22648 Several people have written addressing this question, so I include
22649 adaptations of their explanations here.
22651 The following answer is based on one written by Richard Pixley:
22653 @quotation
22654 Autoconf generated scripts frequently work on machines that it has
22655 never been set up to handle before.  That is, it does a good job of
22656 inferring a configuration for a new system.  Imake cannot do this.
22658 Imake uses a common database of host specific data.  For X11, this makes
22659 sense because the distribution is made as a collection of tools, by one
22660 central authority who has control over the database.
22662 @acronym{GNU} tools are not released this way.  Each @acronym{GNU} tool has a
22663 maintainer; these maintainers are scattered across the world.  Using a
22664 common database would be a maintenance nightmare.  Autoconf may appear
22665 to be this kind of database, but in fact it is not.  Instead of listing
22666 host dependencies, it lists program requirements.
22668 If you view the @acronym{GNU} suite as a collection of native tools, then the
22669 problems are similar.  But the @acronym{GNU} development tools can be
22670 configured as cross tools in almost any host+target permutation.  All of
22671 these configurations can be installed concurrently.  They can even be
22672 configured to share host independent files across hosts.  Imake doesn't
22673 address these issues.
22675 Imake templates are a form of standardization.  The @acronym{GNU} coding
22676 standards address the same issues without necessarily imposing the same
22677 restrictions.
22678 @end quotation
22681 Here is some further explanation, written by Per Bothner:
22683 @quotation
22684 One of the advantages of Imake is that it easy to generate large
22685 makefiles using the @samp{#include} and macro mechanisms of @command{cpp}.
22686 However, @code{cpp} is not programmable: it has limited conditional
22687 facilities, and no looping.  And @code{cpp} cannot inspect its
22688 environment.
22690 All of these problems are solved by using @code{sh} instead of
22691 @code{cpp}.  The shell is fully programmable, has macro substitution,
22692 can execute (or source) other shell scripts, and can inspect its
22693 environment.
22694 @end quotation
22697 Paul Eggert elaborates more:
22699 @quotation
22700 With Autoconf, installers need not assume that Imake itself is already
22701 installed and working well.  This may not seem like much of an advantage
22702 to people who are accustomed to Imake.  But on many hosts Imake is not
22703 installed or the default installation is not working well, and requiring
22704 Imake to install a package hinders the acceptance of that package on
22705 those hosts.  For example, the Imake template and configuration files
22706 might not be installed properly on a host, or the Imake build procedure
22707 might wrongly assume that all source files are in one big directory
22708 tree, or the Imake configuration might assume one compiler whereas the
22709 package or the installer needs to use another, or there might be a
22710 version mismatch between the Imake expected by the package and the Imake
22711 supported by the host.  These problems are much rarer with Autoconf,
22712 where each package comes with its own independent configuration
22713 processor.
22715 Also, Imake often suffers from unexpected interactions between
22716 @command{make} and the installer's C preprocessor.  The fundamental problem
22717 here is that the C preprocessor was designed to preprocess C programs,
22718 not makefiles.  This is much less of a problem with Autoconf,
22719 which uses the general-purpose preprocessor M4, and where the
22720 package's author (rather than the installer) does the preprocessing in a
22721 standard way.
22722 @end quotation
22725 Finally, Mark Eichin notes:
22727 @quotation
22728 Imake isn't all that extensible, either.  In order to add new features to
22729 Imake, you need to provide your own project template, and duplicate most
22730 of the features of the existing one.  This means that for a sophisticated
22731 project, using the vendor-provided Imake templates fails to provide any
22732 leverage---since they don't cover anything that your own project needs
22733 (unless it is an X11 program).
22735 On the other side, though:
22737 The one advantage that Imake has over @command{configure}:
22738 @file{Imakefile} files tend to be much shorter (likewise, less redundant)
22739 than @file{Makefile.in} files.  There is a fix to this, however---at least
22740 for the Kerberos V5 tree, we've modified things to call in common
22741 @file{post.in} and @file{pre.in} makefile fragments for the
22742 entire tree.  This means that a lot of common things don't have to be
22743 duplicated, even though they normally are in @command{configure} setups.
22744 @end quotation
22747 @node Defining Directories
22748 @section How Do I @code{#define} Installation Directories?
22750 @display
22751 My program needs library files, installed in @code{datadir} and
22752 similar.  If I use
22754 @example
22755 AC_DEFINE_UNQUOTED([DATADIR], [$datadir],
22756   [Define to the read-only architecture-independent
22757    data directory.])
22758 @end example
22760 @noindent
22761 I get
22763 @example
22764 #define DATADIR "$@{prefix@}/share"
22765 @end example
22766 @end display
22768 As already explained, this behavior is on purpose, mandated by the
22769 @acronym{GNU} Coding Standards, see @ref{Installation Directory
22770 Variables}.  There are several means to achieve a similar goal:
22772 @itemize @minus
22773 @item
22774 Do not use @code{AC_DEFINE} but use your makefile to pass the
22775 actual value of @code{datadir} via compilation flags.
22776 @xref{Installation Directory Variables}, for the details.
22778 @item
22779 This solution can be simplified when compiling a program: you may either
22780 extend the @code{CPPFLAGS}:
22782 @example
22783 CPPFLAGS = -DDATADIR='"$(datadir)"' @@CPPFLAGS@@
22784 @end example
22786 @noindent
22787 If you are using Automake, you should use @code{AM_CPPFLAGS} instead:
22789 @example
22790 AM_CPPFLAGS = -DDATADIR='"$(datadir)"'
22791 @end example
22793 @noindent
22794 Alternatively, create a dedicated header file:
22796 @example
22797 DISTCLEANFILES = myprog-paths.h
22798 myprog-paths.h: Makefile
22799         echo '#define DATADIR "$(datadir)"' >$@@
22800 @end example
22802 @item
22803 Use @code{AC_DEFINE} but have @command{configure} compute the literal
22804 value of @code{datadir} and others.  Many people have wrapped macros to
22805 automate this task; for an example, see the macro @code{AC_DEFINE_DIR} from
22806 the @uref{http://@/autoconf-archive@/.cryp.to/, Autoconf Macro
22807 Archive}.
22809 This solution does not conform to the @acronym{GNU} Coding Standards.
22811 @item
22812 Note that all the previous solutions hard wire the absolute name of
22813 these directories in the executables, which is not a good property.  You
22814 may try to compute the names relative to @code{prefix}, and try to
22815 find @code{prefix} at runtime, this way your package is relocatable.
22816 @end itemize
22819 @node Autom4te Cache
22820 @section What is @file{autom4te.cache}?
22822 @display
22823 What is this directory @file{autom4te.cache}?  Can I safely remove it?
22824 @end display
22826 In the @acronym{GNU} Build System, @file{configure.ac} plays a central
22827 role and is read by many tools: @command{autoconf} to create
22828 @file{configure}, @command{autoheader} to create @file{config.h.in},
22829 @command{automake} to create @file{Makefile.in}, @command{autoscan} to
22830 check the completeness of @file{configure.ac}, @command{autoreconf} to
22831 check the @acronym{GNU} Build System components that are used.  To
22832 ``read @file{configure.ac}'' actually means to compile it with M4,
22833 which can be a long process for complex @file{configure.ac}.
22835 This is why all these tools, instead of running directly M4, invoke
22836 @command{autom4te} (@pxref{autom4te Invocation}) which, while answering to
22837 a specific demand, stores additional information in
22838 @file{autom4te.cache} for future runs.  For instance, if you run
22839 @command{autoconf}, behind the scenes, @command{autom4te} also
22840 stores information for the other tools, so that when you invoke
22841 @command{autoheader} or @command{automake} etc., reprocessing
22842 @file{configure.ac} is not needed.  The speed up is frequently 30%,
22843 and is increasing with the size of @file{configure.ac}.
22845 But it is and remains being simply a cache: you can safely remove it.
22847 @sp 1
22849 @display
22850 Can I permanently get rid of it?
22851 @end display
22853 The creation of this cache can be disabled from
22854 @file{~/.autom4te.cfg}, see @ref{Customizing autom4te}, for more
22855 details.  You should be aware that disabling the cache slows down the
22856 Autoconf test suite by 40%.  The more @acronym{GNU} Build System
22857 components are used, the more the cache is useful; for instance
22858 running @samp{autoreconf -f} on the Core Utilities is twice slower without
22859 the cache @emph{although @option{--force} implies that the cache is
22860 not fully exploited}, and eight times slower than without
22861 @option{--force}.
22864 @node Present But Cannot Be Compiled
22865 @section Header Present But Cannot Be Compiled
22867 The most important guideline to bear in mind when checking for
22868 features is to mimic as much as possible the intended use.
22869 Unfortunately, old versions of @code{AC_CHECK_HEADER} and
22870 @code{AC_CHECK_HEADERS} failed to follow this idea, and called
22871 the preprocessor, instead of the compiler, to check for headers.  As a
22872 result, incompatibilities between headers went unnoticed during
22873 configuration, and maintainers finally had to deal with this issue
22874 elsewhere.
22876 The transition began with Autoconf 2.56.  As of Autoconf 2.64 both
22877 checks are performed, and @command{configure} complains loudly if the
22878 compiler and the preprocessor do not agree.  However, only the compiler
22879 result is considered.
22881 Consider the following example:
22883 @smallexample
22884 $ @kbd{cat number.h}
22885 typedef int number;
22886 $ @kbd{cat pi.h}
22887 const number pi = 3;
22888 $ @kbd{cat configure.ac}
22889 AC_INIT([Example], [1.0], [bug-example@@example.org])
22890 AC_CHECK_HEADERS([pi.h])
22891 $ @kbd{autoconf -Wall}
22892 $ @kbd{./configure}
22893 checking for gcc... gcc
22894 checking for C compiler default output file name... a.out
22895 checking whether the C compiler works... yes
22896 checking whether we are cross compiling... no
22897 checking for suffix of executables...
22898 checking for suffix of object files... o
22899 checking whether we are using the GNU C compiler... yes
22900 checking whether gcc accepts -g... yes
22901 checking for gcc option to accept ISO C89... none needed
22902 checking how to run the C preprocessor... gcc -E
22903 checking for grep that handles long lines and -e... grep
22904 checking for egrep... grep -E
22905 checking for ANSI C header files... yes
22906 checking for sys/types.h... yes
22907 checking for sys/stat.h... yes
22908 checking for stdlib.h... yes
22909 checking for string.h... yes
22910 checking for memory.h... yes
22911 checking for strings.h... yes
22912 checking for inttypes.h... yes
22913 checking for stdint.h... yes
22914 checking for unistd.h... yes
22915 checking pi.h usability... no
22916 checking pi.h presence... yes
22917 configure: WARNING: pi.h: present but cannot be compiled
22918 configure: WARNING: pi.h:     check for missing prerequisite headers?
22919 configure: WARNING: pi.h: see the Autoconf documentation
22920 configure: WARNING: pi.h:     section "Present But Cannot Be Compiled"
22921 configure: WARNING: pi.h: proceeding with the compiler's result
22922 configure: WARNING:     ## -------------------------------------- ##
22923 configure: WARNING:     ## Report this to bug-example@@example.org ##
22924 configure: WARNING:     ## -------------------------------------- ##
22925 checking for pi.h... yes
22926 @end smallexample
22928 @noindent
22929 The proper way the handle this case is using the fourth argument
22930 (@pxref{Generic Headers}):
22932 @example
22933 $ @kbd{cat configure.ac}
22934 AC_INIT([Example], [1.0], [bug-example@@example.org])
22935 AC_CHECK_HEADERS([number.h pi.h], [], [],
22936 [[#ifdef HAVE_NUMBER_H
22937 # include <number.h>
22938 #endif
22940 $ @kbd{autoconf -Wall}
22941 $ @kbd{./configure}
22942 checking for gcc... gcc
22943 checking for C compiler default output... a.out
22944 checking whether the C compiler works... yes
22945 checking whether we are cross compiling... no
22946 checking for suffix of executables...
22947 checking for suffix of object files... o
22948 checking whether we are using the GNU C compiler... yes
22949 checking whether gcc accepts -g... yes
22950 checking for gcc option to accept ANSI C... none needed
22951 checking for number.h... yes
22952 checking for pi.h... yes
22953 @end example
22955 See @ref{Particular Headers}, for a list of headers with their
22956 prerequisites.
22958 @node Expanded Before Required
22959 @section Expanded Before Required
22961 @cindex expanded before required
22962 Older versions of Autoconf silently built files with incorrect ordering
22963 between dependent macros if an outer macro first expanded, then later
22964 indirectly required, an inner macro.  Starting with Autoconf 2.64, this
22965 situation no longer generates out-of-order code, but results in
22966 duplicate output and a syntax warning:
22968 @example
22969 $ @kbd{cat configure.ac}
22970 @result{}AC_DEFUN([TESTA], [[echo in A
22971 @result{}if test -n "$SEEN_A" ; then echo duplicate ; fi
22972 @result{}SEEN_A=:]])
22973 @result{}AC_DEFUN([TESTB], [AC_REQUIRE([TESTA])[echo in B
22974 @result{}if test -z "$SEEN_A" ; then echo bug ; fi]])
22975 @result{}AC_DEFUN([TESTC], [AC_REQUIRE([TESTB])[echo in C]])
22976 @result{}AC_DEFUN([OUTER], [[echo in OUTER]
22977 @result{}TESTA
22978 @result{}TESTC])
22979 @result{}AC_INIT
22980 @result{}OUTER
22981 @result{}AC_OUTPUT
22982 $ @kbd{autoconf}
22983 @result{}configure.ac:11: warning: AC_REQUIRE:
22984 @result{} `TESTA' was expanded before it was required
22985 @result{}configure.ac:4: TESTB is expanded from...
22986 @result{}configure.ac:6: TESTC is expanded from...
22987 @result{}configure.ac:7: OUTER is expanded from...
22988 @result{}configure.ac:11: the top level
22989 @end example
22991 @noindent
22992 To avoid this warning, decide what purpose the macro in question serves.
22993 If it only needs to be expanded once (for example, if it provides
22994 initialization text used by later macros), then the simplest fix is to
22995 change the macro to be declared with @code{AC_DEFUN_ONCE}
22996 (@pxref{One-Shot Macros}), although this only works in Autoconf 2.64 and
22997 newer.  A more portable fix is to change all
22998 instances of direct calls to instead go through @code{AC_REQUIRE}
22999 (@pxref{Prerequisite Macros}).  If, instead, the macro is parameterized
23000 by arguments or by the current definition of other macros in the m4
23001 environment, then the macro should always be directly expanded instead
23002 of required.
23004 @c ===================================================== History of Autoconf.
23006 @node History
23007 @chapter History of Autoconf
23008 @cindex History of autoconf
23010 You may be wondering, Why was Autoconf originally written?  How did it
23011 get into its present form?  (Why does it look like gorilla spit?)  If
23012 you're not wondering, then this chapter contains no information useful
23013 to you, and you might as well skip it.  If you @emph{are} wondering,
23014 then let there be light@enddots{}
23016 @menu
23017 * Genesis::                     Prehistory and naming of @command{configure}
23018 * Exodus::                      The plagues of M4 and Perl
23019 * Leviticus::                   The priestly code of portability arrives
23020 * Numbers::                     Growth and contributors
23021 * Deuteronomy::                 Approaching the promises of easy configuration
23022 @end menu
23024 @node Genesis
23025 @section Genesis
23027 In June 1991 I was maintaining many of the @acronym{GNU} utilities for the
23028 Free Software Foundation.  As they were ported to more platforms and
23029 more programs were added, the number of @option{-D} options that users
23030 had to select in the makefile (around 20) became burdensome.
23031 Especially for me---I had to test each new release on a bunch of
23032 different systems.  So I wrote a little shell script to guess some of
23033 the correct settings for the fileutils package, and released it as part
23034 of fileutils 2.0.  That @command{configure} script worked well enough that
23035 the next month I adapted it (by hand) to create similar @command{configure}
23036 scripts for several other @acronym{GNU} utilities packages.  Brian Berliner
23037 also adapted one of my scripts for his @acronym{CVS} revision control system.
23039 Later that summer, I learned that Richard Stallman and Richard Pixley
23040 were developing similar scripts to use in the @acronym{GNU} compiler tools;
23041 so I adapted my @command{configure} scripts to support their evolving
23042 interface: using the file name @file{Makefile.in} as the templates;
23043 adding @samp{+srcdir}, the first option (of many); and creating
23044 @file{config.status} files.
23046 @node Exodus
23047 @section Exodus
23049 As I got feedback from users, I incorporated many improvements, using
23050 Emacs to search and replace, cut and paste, similar changes in each of
23051 the scripts.  As I adapted more @acronym{GNU} utilities packages to use
23052 @command{configure} scripts, updating them all by hand became impractical.
23053 Rich Murphey, the maintainer of the @acronym{GNU} graphics utilities, sent me
23054 mail saying that the @command{configure} scripts were great, and asking if
23055 I had a tool for generating them that I could send him.  No, I thought,
23056 but I should!  So I started to work out how to generate them.  And the
23057 journey from the slavery of hand-written @command{configure} scripts to the
23058 abundance and ease of Autoconf began.
23060 Cygnus @command{configure}, which was being developed at around that time,
23061 is table driven; it is meant to deal mainly with a discrete number of
23062 system types with a small number of mainly unguessable features (such as
23063 details of the object file format).  The automatic configuration system
23064 that Brian Fox had developed for Bash takes a similar approach.  For
23065 general use, it seems to me a hopeless cause to try to maintain an
23066 up-to-date database of which features each variant of each operating
23067 system has.  It's easier and more reliable to check for most features on
23068 the fly---especially on hybrid systems that people have hacked on
23069 locally or that have patches from vendors installed.
23071 I considered using an architecture similar to that of Cygnus
23072 @command{configure}, where there is a single @command{configure} script that
23073 reads pieces of @file{configure.in} when run.  But I didn't want to have
23074 to distribute all of the feature tests with every package, so I settled
23075 on having a different @command{configure} made from each
23076 @file{configure.in} by a preprocessor.  That approach also offered more
23077 control and flexibility.
23079 I looked briefly into using the Metaconfig package, by Larry Wall,
23080 Harlan Stenn, and Raphael Manfredi, but I decided not to for several
23081 reasons.  The @command{Configure} scripts it produces are interactive,
23082 which I find quite inconvenient; I didn't like the ways it checked for
23083 some features (such as library functions); I didn't know that it was
23084 still being maintained, and the @command{Configure} scripts I had
23085 seen didn't work on many modern systems (such as System V R4 and NeXT);
23086 it wasn't flexible in what it could do in response to a feature's
23087 presence or absence; I found it confusing to learn; and it was too big
23088 and complex for my needs (I didn't realize then how much Autoconf would
23089 eventually have to grow).
23091 I considered using Perl to generate my style of @command{configure}
23092 scripts, but decided that M4 was better suited to the job of simple
23093 textual substitutions: it gets in the way less, because output is
23094 implicit.  Plus, everyone already has it.  (Initially I didn't rely on
23095 the @acronym{GNU} extensions to M4.)  Also, some of my friends at the
23096 University of Maryland had recently been putting M4 front ends on
23097 several programs, including @code{tvtwm}, and I was interested in trying
23098 out a new language.
23100 @node Leviticus
23101 @section Leviticus
23103 Since my @command{configure} scripts determine the system's capabilities
23104 automatically, with no interactive user intervention, I decided to call
23105 the program that generates them Autoconfig.  But with a version number
23106 tacked on, that name would be too long for old Unix file systems,
23107 so I shortened it to Autoconf.
23109 In the fall of 1991 I called together a group of fellow questers after
23110 the Holy Grail of portability (er, that is, alpha testers) to give me
23111 feedback as I encapsulated pieces of my handwritten scripts in M4 macros
23112 and continued to add features and improve the techniques used in the
23113 checks.  Prominent among the testers were Fran@,{c}ois Pinard, who came up
23114 with the idea of making an Autoconf shell script to run M4
23115 and check for unresolved macro calls; Richard Pixley, who suggested
23116 running the compiler instead of searching the file system to find
23117 include files and symbols, for more accurate results; Karl Berry, who
23118 got Autoconf to configure @TeX{} and added the macro index to the
23119 documentation; and Ian Lance Taylor, who added support for creating a C
23120 header file as an alternative to putting @option{-D} options in a
23121 makefile, so he could use Autoconf for his @acronym{UUCP} package.
23122 The alpha testers cheerfully adjusted their files again and again as the
23123 names and calling conventions of the Autoconf macros changed from
23124 release to release.  They all contributed many specific checks, great
23125 ideas, and bug fixes.
23127 @node Numbers
23128 @section Numbers
23130 In July 1992, after months of alpha testing, I released Autoconf 1.0,
23131 and converted many @acronym{GNU} packages to use it.  I was surprised by how
23132 positive the reaction to it was.  More people started using it than I
23133 could keep track of, including people working on software that wasn't
23134 part of the @acronym{GNU} Project (such as TCL, FSP, and Kerberos V5).
23135 Autoconf continued to improve rapidly, as many people using the
23136 @command{configure} scripts reported problems they encountered.
23138 Autoconf turned out to be a good torture test for M4 implementations.
23139 Unix M4 started to dump core because of the length of the
23140 macros that Autoconf defined, and several bugs showed up in @acronym{GNU}
23141 M4 as well.  Eventually, we realized that we needed to use some
23142 features that only @acronym{GNU} M4 has.  4.3@acronym{BSD} M4, in
23143 particular, has an impoverished set of builtin macros; the System V
23144 version is better, but still doesn't provide everything we need.
23146 More development occurred as people put Autoconf under more stresses
23147 (and to uses I hadn't anticipated).  Karl Berry added checks for X11.
23148 david zuhn contributed C++ support.  Fran@,{c}ois Pinard made it diagnose
23149 invalid arguments.  Jim Blandy bravely coerced it into configuring
23150 @acronym{GNU} Emacs, laying the groundwork for several later improvements.
23151 Roland McGrath got it to configure the @acronym{GNU} C Library, wrote the
23152 @command{autoheader} script to automate the creation of C header file
23153 templates, and added a @option{--verbose} option to @command{configure}.
23154 Noah Friedman added the @option{--autoconf-dir} option and
23155 @code{AC_MACRODIR} environment variable.  (He also coined the term
23156 @dfn{autoconfiscate} to mean ``adapt a software package to use
23157 Autoconf''.)  Roland and Noah improved the quoting protection in
23158 @code{AC_DEFINE} and fixed many bugs, especially when I got sick of
23159 dealing with portability problems from February through June, 1993.
23161 @node Deuteronomy
23162 @section Deuteronomy
23164 A long wish list for major features had accumulated, and the effect of
23165 several years of patching by various people had left some residual
23166 cruft.  In April 1994, while working for Cygnus Support, I began a major
23167 revision of Autoconf.  I added most of the features of the Cygnus
23168 @command{configure} that Autoconf had lacked, largely by adapting the
23169 relevant parts of Cygnus @command{configure} with the help of david zuhn
23170 and Ken Raeburn.  These features include support for using
23171 @file{config.sub}, @file{config.guess}, @option{--host}, and
23172 @option{--target}; making links to files; and running @command{configure}
23173 scripts in subdirectories.  Adding these features enabled Ken to convert
23174 @acronym{GNU} @code{as}, and Rob Savoye to convert Deja@acronym{GNU}, to using
23175 Autoconf.
23177 I added more features in response to other peoples' requests.  Many
23178 people had asked for @command{configure} scripts to share the results of
23179 the checks between runs, because (particularly when configuring a large
23180 source tree, like Cygnus does) they were frustratingly slow.  Mike
23181 Haertel suggested adding site-specific initialization scripts.  People
23182 distributing software that had to unpack on MS-DOS asked for a way to
23183 override the @file{.in} extension on the file names, which produced file
23184 names like @file{config.h.in} containing two dots.  Jim Avera did an
23185 extensive examination of the problems with quoting in @code{AC_DEFINE}
23186 and @code{AC_SUBST}; his insights led to significant improvements.
23187 Richard Stallman asked that compiler output be sent to @file{config.log}
23188 instead of @file{/dev/null}, to help people debug the Emacs
23189 @command{configure} script.
23191 I made some other changes because of my dissatisfaction with the quality
23192 of the program.  I made the messages showing results of the checks less
23193 ambiguous, always printing a result.  I regularized the names of the
23194 macros and cleaned up coding style inconsistencies.  I added some
23195 auxiliary utilities that I had developed to help convert source code
23196 packages to use Autoconf.  With the help of Fran@,{c}ois Pinard, I made
23197 the macros not interrupt each others' messages.  (That feature revealed
23198 some performance bottlenecks in @acronym{GNU} M4, which he hastily
23199 corrected!)  I reorganized the documentation around problems people want
23200 to solve.  And I began a test suite, because experience had shown that
23201 Autoconf has a pronounced tendency to regress when we change it.
23203 Again, several alpha testers gave invaluable feedback, especially
23204 Fran@,{c}ois Pinard, Jim Meyering, Karl Berry, Rob Savoye, Ken Raeburn,
23205 and Mark Eichin.
23207 Finally, version 2.0 was ready.  And there was much rejoicing.  (And I
23208 have free time again.  I think.  Yeah, right.)
23211 @c ========================================================== Appendices
23214 @node GNU Free Documentation License
23215 @appendix GNU Free Documentation License
23217 @include fdl.texi
23219 @node Indices
23220 @appendix Indices
23222 @menu
23223 * Environment Variable Index::  Index of environment variables used
23224 * Output Variable Index::       Index of variables set in output files
23225 * Preprocessor Symbol Index::   Index of C preprocessor symbols defined
23226 * Autoconf Macro Index::        Index of Autoconf macros
23227 * M4 Macro Index::              Index of M4, M4sugar, and M4sh macros
23228 * Autotest Macro Index::        Index of Autotest macros
23229 * Program & Function Index::    Index of those with portability problems
23230 * Concept Index::               General index
23231 @end menu
23233 @node Environment Variable Index
23234 @appendixsec Environment Variable Index
23236 This is an alphabetical list of the environment variables that Autoconf
23237 checks.
23239 @printindex ev
23241 @node Output Variable Index
23242 @appendixsec Output Variable Index
23244 This is an alphabetical list of the variables that Autoconf can
23245 substitute into files that it creates, typically one or more
23246 makefiles.  @xref{Setting Output Variables}, for more information
23247 on how this is done.
23249 @printindex ov
23251 @node Preprocessor Symbol Index
23252 @appendixsec Preprocessor Symbol Index
23254 This is an alphabetical list of the C preprocessor symbols that the
23255 Autoconf macros define.  To work with Autoconf, C source code needs to
23256 use these names in @code{#if} or @code{#ifdef} directives.
23258 @printindex cv
23260 @node Autoconf Macro Index
23261 @appendixsec Autoconf Macro Index
23263 This is an alphabetical list of the Autoconf macros.
23264 @ifset shortindexflag
23265 To make the list easier to use, the macros are listed without their
23266 preceding @samp{AC_}.
23267 @end ifset
23269 @printindex AC
23271 @node M4 Macro Index
23272 @appendixsec M4 Macro Index
23274 This is an alphabetical list of the M4, M4sugar, and M4sh macros.
23275 @ifset shortindexflag
23276 To make the list easier to use, the macros are listed without their
23277 preceding @samp{m4_} or @samp{AS_}.
23278 @end ifset
23280 @printindex MS
23282 @node Autotest Macro Index
23283 @appendixsec Autotest Macro Index
23285 This is an alphabetical list of the Autotest macros.
23286 @ifset shortindexflag
23287 To make the list easier to use, the macros are listed without their
23288 preceding @samp{AT_}.
23289 @end ifset
23291 @printindex AT
23293 @node Program & Function Index
23294 @appendixsec Program and Function Index
23296 This is an alphabetical list of the programs and functions whose
23297 portability is discussed in this document.
23299 @printindex pr
23301 @node Concept Index
23302 @appendixsec Concept Index
23304 This is an alphabetical list of the files, tools, and concepts
23305 introduced in this document.
23307 @printindex cp
23309 @bye
23311 @c  LocalWords:  texinfo setfilename autoconf texi settitle setchapternewpage
23312 @c  LocalWords:  setcontentsaftertitlepage finalout ARG ovar varname dvar acx
23313 @c  LocalWords:  makeinfo dvi defcodeindex ev ov CPP cv Autotest mv defindex fn
23314 @c  LocalWords:  shortindexflag iftex ifset acindex ACindex ifclear ahindex fu
23315 @c  LocalWords:  asindex MSindex atindex ATindex auindex hdrindex prindex FIXME
23316 @c  LocalWords:  msindex alloca fnindex Aaarg indices FSF's dircategory ifnames
23317 @c  LocalWords:  direntry autoscan autoreconf autoheader autoupdate config FDs
23318 @c  LocalWords:  testsuite titlepage Elliston Demaille vskip filll ifnottex hmm
23319 @c  LocalWords:  insertcopying Autoconf's detailmenu Automake Libtool Posix ois
23320 @c  LocalWords:  Systemology Checkpointing Changequote INTERCAL changequote dfn
23321 @c  LocalWords:  Quadrigraphs builtins Shellology acconfig Bugward LIBOBJ Imake
23322 @c  LocalWords:  LIBOBJS IFELSE cindex flushright Pinard Metaconfig uref Simons
23323 @c  LocalWords:  distclean uninstall noindent versioning Tromey dir
23324 @c  LocalWords:  SAMS samp aclocal acsite underquoted emph itemx prepend SUBST
23325 @c  LocalWords:  evindex automake Gettext autopoint gettext symlink libtoolize
23326 @c  LocalWords:  defmac INIT tarname ovindex cvindex BUGREPORT PREREQ asis PROG
23327 @c  LocalWords:  SRCDIR srcdir globbing afterwards cmds foos fooo foooo init cd
23328 @c  LocalWords:  builddir timestamp src Imakefile chmod defvar CFLAGS CPPFLAGS
23329 @c  LocalWords:  CXXFLAGS DEFS DHAVE defvarx FCFLAGS FFLAGS LDFLAGS bindir GCC
23330 @c  LocalWords:  datadir datarootdir docdir dvidir htmldir libdir ifnothtml kbd
23331 @c  LocalWords:  includedir infodir libexecdir localedir localstatedir mandir
23332 @c  LocalWords:  oldincludedir pdfdir PDF psdir PostScript sbindir sysconfdir
23333 @c  LocalWords:  sharedstatedir DDATADIR sed tmp pkgdatadir VPATH conf unistd
23334 @c  LocalWords:  undef endif builtin FUNCS ifndef STACKSEG getb GETB YMP fubar
23335 @c  LocalWords:  PRE dest SUBDIRS subdirs fi struct STDC stdlib stddef INTTYPES
23336 @c  LocalWords:  inttypes STDINT stdint AWK AIX Solaris NeXT env EGREP FGREP yy
23337 @c  LocalWords:  LEXLIB YYTEXT lfl nonportable Automake's LN RANLIB byacc INETD
23338 @c  LocalWords:  inetd prog PROGS progs ranlib lmp lXt lX nsl gethostbyname UX
23339 @c  LocalWords:  NextStep isinf isnan glibc IRIX sunmath lm lsunmath pre sizeof
23340 @c  LocalWords:  ld inline malloc putenv setenv FreeBSD realloc SunOS MinGW
23341 @c  LocalWords:  snprintf vsnprintf sprintf vsprintf sscanf gcc strerror ifdef
23342 @c  LocalWords:  strnlen sysconf PAGESIZE unsetenv va fallback memcpy dst FUNC
23343 @c  LocalWords:  PowerPC GNUC libPW pragma Olibcalls CHOWN chown CLOSEDIR VFORK
23344 @c  LocalWords:  closedir FNMATCH fnmatch vfork FSEEKO LARGEFILE fseeko SVR sc
23345 @c  LocalWords:  largefile GETGROUPS getgroups GETLOADAVG DGUX UMAX NLIST KMEM
23346 @c  LocalWords:  SETGID getloadavg nlist GETMNTENT irix
23347 @c  LocalWords:  getmntent UnixWare GETPGRP getpgid getpgrp Posix's pid LSTAT
23348 @c  LocalWords:  lstat rpl MEMCMP memcmp OpenStep MBRTOWC mbrtowc MKTIME mktime
23349 @c  LocalWords:  localtime MMAP mmap OBSTACK obstack obstacks ARGTYPES timeval
23350 @c  LocalWords:  SETPGRP setpgrp defmacx Hurd SETVBUF setvbuf STRCOLL strcoll
23351 @c  LocalWords:  STRTOD strtod DECL STRFTIME strftime SCO UTIME utime VPRINTF
23352 @c  LocalWords:  DOPRNT vprintf doprnt sp unfixable LIBSOURCE LIBSOURCES Eggert
23353 @c  LocalWords:  linux netinet ia Tru XFree DIRENT NDIR dirent ndir multitable
23354 @c  LocalWords:  NAMLEN strlen namlen MKDEV SYSMACROS makedev RESOLV resolv DNS
23355 @c  LocalWords:  inet structs NAMESER arpa NETDB netdb UTekV UTS GCC's kB
23356 @c  LocalWords:  STDBOOL BOOL stdbool conformant cplusplus bool Bool stdarg tm
23357 @c  LocalWords:  ctype strchr strrchr rindex bcopy memmove memchr WEXITSTATUS
23358 @c  LocalWords:  WIFEXITED TIOCGWINSZ GWINSZ termios preprocess preprocessable
23359 @c  LocalWords:  DECLS strdup calloc BLKSIZE blksize RDEV rdev TZNAME tzname pw
23360 @c  LocalWords:  passwd gecos pwd MBSTATE mbstate wchar RETSIGTYPE hup UID uid
23361 @c  LocalWords:  gid ptrdiff uintmax EXEEXT OBJEXT Ae conftest AXP str
23362 @c  LocalWords:  ALIGNOF WERROR Werror cpp HP's WorkShop egcs un fied stdc CXX
23363 @c  LocalWords:  varargs BIGENDIAN Endianness SPARC endianness grep'ed CONST FC
23364 @c  LocalWords:  const STRINGIZE stringizing PARAMS unprotoize protos KCC cxx
23365 @c  LocalWords:  xlC aCC CXXCPP FREEFORM xlf FLIBS FCLIBS ish SRCEXT XTRA LFS
23366 @c  LocalWords:  ISC lcposix MINIX Minix conditionalized inlines hw dD confdefs
23367 @c  LocalWords:  fputs stdout PREPROC ar UFS HFS QNX realtime fstype STATVFS se
23368 @c  LocalWords:  statvfs STATFS statfs func machfile hdr lelf raboof DEFUN GTK
23369 @c  LocalWords:  GTKMM Grmph ified ine defn baz EOF qar Ahhh changecom algol io
23370 @c  LocalWords:  changeword quadrigraphs quadrigraph dnl SGI atoi overquoting
23371 @c  LocalWords:  Aas Wcross sep args namespace undefine bpatsubst popdef dquote
23372 @c  LocalWords:  bregexp Overquote overquotation meisch maisch meische maische
23373 @c  LocalWords:  miscian DIRNAME dirname MKDIR CATFILE XMKMF TRAVOLTA celsius
23374 @c  LocalWords:  EMX emxos Emacsen Korn DYNIX subshell posix Ksh ksh Pdksh Zsh
23375 @c  LocalWords:  pdksh zsh Allbery Lipe Kubota UWS zorglub stderr eval esac lfn
23376 @c  LocalWords:  drivespec Posixy DJGPP doschk prettybird LPT pfew Zsh's yu yaa
23377 @c  LocalWords:  yM uM aM firebird IP subdir misparses ok Unpatched abc bc zA
23378 @c  LocalWords:  CDPATH DUALCASE LINENO prepass Subshells lineno NULLCMD cmp wc
23379 @c  LocalWords:  MAILPATH scanset arg NetBSD Almquist printf expr cp
23380 @c  LocalWords:  Oliva awk Aaaaarg cmd regex xfoo GNV OpenVMS VM
23381 @c  LocalWords:  sparc Proulx nbar nfoo maxdepth acdilrtu TWG mc
23382 @c  LocalWords:  mkdir exe uname OpenBSD Fileutils mktemp umask TMPDIR guid os
23383 @c  LocalWords:  fooXXXXXX Unicos utimes hpux hppa unescaped
23384 @c  LocalWords:  pmake DOS's gmake ifoo DESTDIR autoconfiscated pc coff mips gg
23385 @c  LocalWords:  dec ultrix cpu wildcards rpcc rdtsc powerpc readline
23386 @c  LocalWords:  withval vxworks gless localcache usr LOFF loff CYGWIN Cygwin
23387 @c  LocalWords:  cygwin SIGLIST siglist SYSNDIR SYSDIR ptx lseq rusage elif MSC
23388 @c  LocalWords:  lfoo POUNDBANG lsun NIS getpwnam SYSCALLS RSH INTL lintl aix
23389 @c  LocalWords:  intl lx ldir syslog bsd EPI toolchain netbsd objext de KNR nn
23390 @c  LocalWords:  fication LTLIBOBJS Wdiff TESTDIR atconfig atlocal akim XFAIL
23391 @c  LocalWords:  ChangeLog prepended errexit smallexample TESTSUITEFLAGS GPL er
23392 @c  LocalWords:  installcheck autotest indir Pixley Bothner Eichin Kerberos adl
23393 @c  LocalWords:  DISTCLEANFILES preprocessor's fileutils Stallman Murphey Stenn
23394 @c  LocalWords:  Manfredi Autoconfig TCL FSP david zuhn Blandy MACRODIR Raeburn
23395 @c  LocalWords:  autoconfiscate Savoye Haertel Avera Meyering fdl appendixsec
23396 @c  LocalWords:  printindex american LIBOBJDIR LibdirTest ERLCFLAGS OBJCFLAGS
23397 @c  LocalWords:  VER Gnulib online xyes strcpy TYPEOF typeof OBJC objcc objc ln
23398 @c  LocalWords:  GOBJC OTP ERLC erl valloc decr dumpdef errprint incr
23399 @c  LocalWords:  esyscmd len maketemp pushdef substr syscmd sysval translit txt
23400 @c  LocalWords:  sinclude foreach myvar tolower toupper uniq BASENAME STDIN
23401 @c  LocalWords:  Dynix descrips basename aname cname macroexpands xno xcheck
23402 @c  LocalWords:  LIBREADLINE lreadline lncurses libreadline
23404 @c Local Variables:
23405 @c fill-column: 72
23406 @c ispell-local-dictionary: "american"
23407 @c indent-tabs-mode: nil
23408 @c whitespace-check-buffer-indent: nil
23409 @c End: